Remittances draft the items due, write the RiBa CBI or SEPA pain.001/pain.008 file, present them (bills account and advance, or supplier payments), credit them and record unpaid effects with their fees. The reconciliation imports CSV, CBI and CAMT.053 statements without duplicates and proposes matches with open items, payments, F24, remittances and saved rules. Reminders follow three levels with late interest, e-mail/PEC/letter and customer block, also from a scheduled task; the cash flow forecasts 90 days by week. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
562bf98092
commit
5bbc2120a1
12 files changed
+2869
No files matched your search
@@ -60,6 +60,7 @@ public sealed class JobScheduler
|
||||
new("system.ecb-rates", "Cambi di riferimento BCE", Tables.EcbRatesJob.JobType, "30 16 * * 1-5", 300, UsesNetwork: true),
|
||||
new("inventory.rebuild", "Ricostruzione del magazzino", Inventory.InventoryRebuildJob.JobType, "15 2 * * 0", 3600),
|
||||
new("ledger.recurring", "Registrazioni ricorrenti", Ledger.RecurringEntriesJob.JobType, "0 5 * * *", 1800),
|
||||
new("finance.dunning", "Solleciti automatici", Treasury.DunningJob.JobType, "0 7 * * 1-5", 1800, UsesNetwork: true),
|
||||
];
|
||||
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
|
||||
@@ -0,0 +1,925 @@
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
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.Core.Validation;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Application.Treasury;
|
||||
|
||||
/// <summary>The result of an import of a bank statement.</summary>
|
||||
/// <param name="Statement">The statement.</param>
|
||||
/// <param name="Added">The new movements.</param>
|
||||
/// <param name="Duplicates">The movements already imported and skipped.</param>
|
||||
/// <param name="Suggested">The movements with a proposal.</param>
|
||||
public sealed record StatementImport(BankStatement Statement, int Added, int Duplicates, int Suggested);
|
||||
|
||||
/// <summary>A movement with the name of its party.</summary>
|
||||
/// <param name="Line">The movement.</param>
|
||||
/// <param name="PartyName">The customer or supplier of the match.</param>
|
||||
public sealed record StatementLineRow(BankStatementLine Line, string? PartyName);
|
||||
|
||||
/// <summary>The position of a bank account: the ledger against the bank.</summary>
|
||||
/// <param name="BankAccountId">The bank account.</param>
|
||||
/// <param name="BookBalance">The balance of its ledger account to the day.</param>
|
||||
/// <param name="BankBalance">The closing balance of its last statement.</param>
|
||||
/// <param name="BankBalanceDate">The day of that balance.</param>
|
||||
/// <param name="ToMatch">Movements still to reconcile.</param>
|
||||
/// <param name="ToMatchAmount">Their sum.</param>
|
||||
public sealed record BankPosition(long BankAccountId, decimal BookBalance, decimal? BankBalance, DateOnly? BankBalanceDate, int ToMatch, decimal ToMatchAmount);
|
||||
|
||||
/// <summary>A saved rule being written.</summary>
|
||||
/// <param name="Id">The rule, or <see langword="null"/>.</param>
|
||||
/// <param name="Name">The name.</param>
|
||||
/// <param name="Pattern">The text looked for in the description.</param>
|
||||
/// <param name="Direction">Money in, out or both.</param>
|
||||
/// <param name="AccountId">The account posted against the bank.</param>
|
||||
/// <param name="EntryDescription">The description of the entry.</param>
|
||||
/// <param name="Disabled">Not used.</param>
|
||||
public sealed record BankRuleInput(long? Id, string Name, string Pattern, BankRuleDirection Direction, long AccountId, string? EntryDescription, bool Disabled);
|
||||
|
||||
/// <summary>
|
||||
/// The bank reconciliation (SPEC §11.8, mockup 057, ADR 0038): import of CSV, CBI and CAMT.053 statements without
|
||||
/// duplicates, proposals with confidence from open items, payments recorded, F24, remittances, unpaid effects and saved
|
||||
/// rules, confirmation one by one or of every proposal above the threshold, manual matching, entries on an account and
|
||||
/// the position of the bank against the ledger.
|
||||
/// </summary>
|
||||
public sealed class BankReconciliationService
|
||||
{
|
||||
/// <summary>The confidence from which the proposals are confirmed together.</summary>
|
||||
public const int AutoConfirmThreshold = 90;
|
||||
|
||||
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 BankReconciliationService(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 fingerprint of a movement: the same movement imported twice has the same one.</summary>
|
||||
/// <param name="bankAccountId">The bank account.</param>
|
||||
/// <param name="movement">The movement.</param>
|
||||
/// <param name="occurrence">How many equal movements came before it in the same file.</param>
|
||||
/// <returns>64 hexadecimal characters.</returns>
|
||||
public static string Fingerprint(long bankAccountId, StatementMovement movement, int occurrence)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(movement);
|
||||
var text = string.Join(
|
||||
"|",
|
||||
bankAccountId.ToString(CultureInfo.InvariantCulture),
|
||||
movement.BookingDate.ToString("yyyyMMdd", CultureInfo.InvariantCulture),
|
||||
movement.Amount.ToString("0.00", CultureInfo.InvariantCulture),
|
||||
BankMatcher.Normalize(movement.Description),
|
||||
BankMatcher.Normalize(movement.Reference),
|
||||
occurrence.ToString(CultureInfo.InvariantCulture));
|
||||
return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text))).ToLowerInvariant();
|
||||
}
|
||||
|
||||
/// <summary>Reads a bank file of any supported format.</summary>
|
||||
/// <param name="content">The file.</param>
|
||||
/// <param name="pack">The fiscal pack (its readers, such as CBI).</param>
|
||||
/// <returns>The statement.</returns>
|
||||
/// <exception cref="ValidationFailedException">The format is not recognized or the file cannot be read.</exception>
|
||||
public static StatementFile Read(byte[] content, IFiscalPack? pack)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(content);
|
||||
var head = content.AsSpan(0, Math.Min(content.Length, 4096));
|
||||
try
|
||||
{
|
||||
if (Camt053Reader.Recognizes(head))
|
||||
{
|
||||
using var stream = new MemoryStream(content);
|
||||
return Camt053Reader.Read(stream);
|
||||
}
|
||||
|
||||
if (pack?.GetFeature<IBankStatementReader>() is { } reader && reader.Recognizes(head))
|
||||
{
|
||||
using var stream = new MemoryStream(content);
|
||||
return reader.Read(stream);
|
||||
}
|
||||
|
||||
var text = Encoding.UTF8.GetString(head).TrimStart('');
|
||||
var firstLine = text.Split('\n', 2)[0].TrimEnd('\r');
|
||||
if (CsvStatementReader.Detect(firstLine) is { } layout)
|
||||
{
|
||||
using var stream = new MemoryStream(content);
|
||||
return CsvStatementReader.Read(stream, layout);
|
||||
}
|
||||
}
|
||||
catch (BankFileException)
|
||||
{
|
||||
throw new ValidationFailedException(["File:" + TreasuryErrors.StatementFormat]);
|
||||
}
|
||||
|
||||
throw new ValidationFailedException(["File:" + TreasuryErrors.StatementFormat]);
|
||||
}
|
||||
|
||||
/// <summary>The statements imported for a bank account.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="bankAccountId">The bank account.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The statements, latest first.</returns>
|
||||
public async Task<IReadOnlyList<BankStatement>> StatementsAsync(Actor actor, string companyCode, long bankAccountId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return (await uow.Repository<BankStatement, long>().ListAsync(
|
||||
Query.For<BankStatement>().Where(s => s.BankAccountId == bankAccountId).OrderByDescending(s => s.ToDate).OrderByDescending(s => s.Id), cancellationToken).ConfigureAwait(false)).Items;
|
||||
}
|
||||
|
||||
/// <summary>Imports a bank file: the movements already imported are skipped, the new ones get their proposals.</summary>
|
||||
/// <param name="actor">Who imports it.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="bankAccountId">The bank account.</param>
|
||||
/// <param name="fileName">The name of the file.</param>
|
||||
/// <param name="content">The file.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>What was imported.</returns>
|
||||
public async Task<StatementImport> ImportAsync(Actor actor, string companyCode, long bankAccountId, string? fileName, byte[] content, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
ArgumentNullException.ThrowIfNull(content);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, cancellationToken).ConfigureAwait(false);
|
||||
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
var file = Read(content, pack);
|
||||
if (file.Movements.Count == 0)
|
||||
{
|
||||
throw new ValidationFailedException(["File:" + TreasuryErrors.StatementEmpty]);
|
||||
}
|
||||
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var bank = await uow.Repository<BankAccount, long>().GetAsync(bankAccountId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ValidationFailedException(["BankAccountId:" + TreasuryErrors.NotFound]);
|
||||
if (!string.IsNullOrWhiteSpace(file.AccountIban) && !string.IsNullOrWhiteSpace(bank.Iban)
|
||||
&& !string.Equals(IbanValidator.Normalize(file.AccountIban), IbanValidator.Normalize(bank.Iban), StringComparison.Ordinal))
|
||||
{
|
||||
throw new ValidationFailedException(["File:" + TreasuryErrors.StatementAccount]);
|
||||
}
|
||||
|
||||
var statement = new BankStatement
|
||||
{
|
||||
BankAccountId = bankAccountId,
|
||||
Format = file.Format,
|
||||
FileName = LedgerStore.Trim(fileName, 200),
|
||||
FromDate = file.FromDate ?? file.Movements.Min(m => m.BookingDate),
|
||||
ToDate = file.ToDate ?? file.Movements.Max(m => m.BookingDate),
|
||||
OpeningBalance = file.OpeningBalance,
|
||||
ClosingBalance = file.ClosingBalance,
|
||||
};
|
||||
statement.Id = await uow.Repository<BankStatement, long>().InsertAsync(statement, cancellationToken).ConfigureAwait(false);
|
||||
var lines = uow.Repository<BankStatementLine, long>();
|
||||
var seen = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
int added = 0, duplicates = 0;
|
||||
foreach (var movement in file.Movements)
|
||||
{
|
||||
var key = Fingerprint(bankAccountId, movement, 0);
|
||||
seen[key] = seen.TryGetValue(key, out var count) ? count + 1 : 0;
|
||||
var fingerprint = Fingerprint(bankAccountId, movement, seen[key]);
|
||||
if (await lines.CountAsync(Query.For<BankStatementLine>().Where(l => l.BankAccountId == bankAccountId && l.Fingerprint == fingerprint), cancellationToken).ConfigureAwait(false) > 0)
|
||||
{
|
||||
duplicates++;
|
||||
continue;
|
||||
}
|
||||
|
||||
await lines.InsertAsync(new BankStatementLine
|
||||
{
|
||||
StatementId = statement.Id,
|
||||
BankAccountId = bankAccountId,
|
||||
BookingDate = movement.BookingDate,
|
||||
ValueDate = movement.ValueDate,
|
||||
Amount = movement.Amount,
|
||||
Description = LedgerStore.Trim(string.IsNullOrWhiteSpace(movement.Description) ? "-" : movement.Description.Trim(), 500)!,
|
||||
Reference = LedgerStore.Trim(movement.Reference, 60),
|
||||
CounterpartyName = LedgerStore.Trim(movement.CounterpartyName, 140),
|
||||
CounterpartyIban = LedgerStore.Trim(movement.CounterpartyIban, 34),
|
||||
BankCode = LedgerStore.Trim(movement.BankCode, 40),
|
||||
Fingerprint = fingerprint,
|
||||
Status = StatementLineStatus.ToMatch,
|
||||
MatchKind = StatementMatchKind.None,
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
added++;
|
||||
}
|
||||
|
||||
statement.MovementCount = added;
|
||||
await uow.Repository<BankStatement, long>().UpdateAsync(statement, cancellationToken).ConfigureAwait(false);
|
||||
var suggested = await SuggestAsync(uow, bankAccountId, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync<BankStatement>(uow, AuditAction.Insert, statement.Id, null, statement, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return new StatementImport(statement, added, duplicates, suggested);
|
||||
}
|
||||
|
||||
/// <summary>The movements of a bank account.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="bankAccountId">The bank account.</param>
|
||||
/// <param name="onlyOpen">Only those to reconcile (to match or suggested).</param>
|
||||
/// <param name="from">From this day.</param>
|
||||
/// <param name="to">Up to this day.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The movements, by date.</returns>
|
||||
public async Task<IReadOnlyList<StatementLineRow>> LinesAsync(
|
||||
Actor actor, string companyCode, long bankAccountId, bool onlyOpen, DateOnly? from = null, DateOnly? to = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var query = Query.For<BankStatementLine>().Where(l => l.BankAccountId == bankAccountId);
|
||||
if (onlyOpen)
|
||||
{
|
||||
query = query.Where(l => l.Status == StatementLineStatus.ToMatch || l.Status == StatementLineStatus.Suggested);
|
||||
}
|
||||
|
||||
if (from is { } f)
|
||||
{
|
||||
query = query.Where(l => l.BookingDate >= f);
|
||||
}
|
||||
|
||||
if (to is { } t)
|
||||
{
|
||||
query = query.Where(l => l.BookingDate <= t);
|
||||
}
|
||||
|
||||
var lines = (await uow.Repository<BankStatementLine, long>().ListAsync(query.OrderByDescending(l => l.BookingDate).OrderBy(l => l.Id), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var parties = await TreasuryStore.PartiesAsync(uow, lines.Where(l => l.PartyId is not null).Select(l => l.PartyId!.Value), cancellationToken).ConfigureAwait(false);
|
||||
return [.. lines.Select(l => new StatementLineRow(l, l.PartyId is { } p ? parties.GetValueOrDefault(p)?.Name : null))];
|
||||
}
|
||||
|
||||
/// <summary>The position of a bank account.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="bankAccountId">The bank account.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The position.</returns>
|
||||
public async Task<BankPosition> PositionAsync(Actor actor, string companyCode, long bankAccountId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var bank = await uow.Repository<BankAccount, long>().GetAsync(bankAccountId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound);
|
||||
var account = await LedgerStore.AccountAsync(uow, bank.AccountCode, cancellationToken).ConfigureAwait(false);
|
||||
var today = TreasuryStore.Today(_clock);
|
||||
var draft = nameof(GlEntryStatus.Draft);
|
||||
var book = account is null
|
||||
? 0m
|
||||
: await uow.QuerySingleAsync<decimal?>(
|
||||
SqlFragment.Of($"SELECT SUM(debit - credit) FROM gl_entry_lines WHERE account_id = {account.Id} AND status <> {draft} AND entry_date <= {today}"), cancellationToken).ConfigureAwait(false) ?? 0m;
|
||||
var last = await uow.Repository<BankStatement, long>().FindAsync(
|
||||
Query.For<BankStatement>().Where(s => s.BankAccountId == bankAccountId && s.ClosingBalance != null).OrderByDescending(s => s.ToDate).OrderByDescending(s => s.Id), cancellationToken).ConfigureAwait(false);
|
||||
var open = (await uow.Repository<BankStatementLine, long>().ListAsync(
|
||||
Query.For<BankStatementLine>().Where(l => l.BankAccountId == bankAccountId && (l.Status == StatementLineStatus.ToMatch || l.Status == StatementLineStatus.Suggested)), cancellationToken)
|
||||
.ConfigureAwait(false)).Items;
|
||||
return new BankPosition(bankAccountId, book, last?.ClosingBalance, last?.ToDate, open.Count, open.Sum(l => l.Amount));
|
||||
}
|
||||
|
||||
/// <summary>Computes the proposals again for the movements to reconcile.</summary>
|
||||
/// <param name="actor">Who does it.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="bankAccountId">The bank account.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The movements with a proposal.</returns>
|
||||
public async Task<int> RefreshAsync(Actor actor, string companyCode, long bankAccountId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var count = await SuggestAsync(uow, bankAccountId, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return count;
|
||||
}
|
||||
|
||||
/// <summary>Confirms the proposal of a movement.</summary>
|
||||
/// <param name="actor">Who confirms.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="lineId">The movement.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The movement.</returns>
|
||||
public async Task<BankStatementLine> ConfirmAsync(Actor actor, string companyCode, long lineId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, 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 line = await OpenLineAsync(uow, lineId, cancellationToken).ConfigureAwait(false);
|
||||
await ApplyAsync(uow, pack, line, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return line;
|
||||
}
|
||||
|
||||
/// <summary>Confirms every proposal at or above the threshold.</summary>
|
||||
/// <param name="actor">Who confirms.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="bankAccountId">The bank account.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>How many movements were reconciled.</returns>
|
||||
public async Task<int> ConfirmAllAsync(Actor actor, string companyCode, long bankAccountId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, 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 lines = (await uow.Repository<BankStatementLine, long>().ListAsync(
|
||||
Query.For<BankStatementLine>().Where(l => l.BankAccountId == bankAccountId && l.Status == StatementLineStatus.Suggested && l.Confidence >= AutoConfirmThreshold)
|
||||
.OrderBy(l => l.BookingDate).OrderBy(l => l.Id), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var done = 0;
|
||||
var used = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var line in lines)
|
||||
{
|
||||
// Two movements proposing the same target: only the first is confirmed, the other waits.
|
||||
if (line.Targets is { } targets && !used.Add(line.MatchKind + ":" + targets))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await ApplyAsync(uow, pack, line, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
done++;
|
||||
}
|
||||
catch (ValidationFailedException)
|
||||
{
|
||||
// A proposal no longer valid (the item was settled meanwhile) stays to be reviewed.
|
||||
}
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return done;
|
||||
}
|
||||
|
||||
/// <summary>Reconciles a movement with open items chosen by hand: a collection or payment is recorded.</summary>
|
||||
/// <param name="actor">Who does it.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="lineId">The movement.</param>
|
||||
/// <param name="openItemIds">The items, oldest first.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The movement.</returns>
|
||||
public async Task<BankStatementLine> MatchItemsAsync(Actor actor, string companyCode, long lineId, IReadOnlyList<long> openItemIds, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
ArgumentNullException.ThrowIfNull(openItemIds);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, 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 line = await OpenLineAsync(uow, lineId, cancellationToken).ConfigureAwait(false);
|
||||
line.MatchKind = StatementMatchKind.OpenItems;
|
||||
line.Targets = string.Join(",", openItemIds.Select(i => i.ToString(CultureInfo.InvariantCulture)));
|
||||
await ApplyAsync(uow, pack, line, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return line;
|
||||
}
|
||||
|
||||
/// <summary>Reconciles a movement with a collection or payment already recorded.</summary>
|
||||
/// <param name="actor">Who does it.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="lineId">The movement.</param>
|
||||
/// <param name="paymentId">The payment.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The movement.</returns>
|
||||
public async Task<BankStatementLine> MatchPaymentAsync(Actor actor, string companyCode, long lineId, long paymentId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, 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 line = await OpenLineAsync(uow, lineId, cancellationToken).ConfigureAwait(false);
|
||||
line.MatchKind = StatementMatchKind.Payment;
|
||||
line.Targets = paymentId.ToString(CultureInfo.InvariantCulture);
|
||||
await ApplyAsync(uow, pack, line, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return line;
|
||||
}
|
||||
|
||||
/// <summary>Posts a movement on an account against the bank, and may save a rule for the next ones.</summary>
|
||||
/// <param name="actor">Who does it.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="lineId">The movement.</param>
|
||||
/// <param name="accountId">The account.</param>
|
||||
/// <param name="description">The description of the entry.</param>
|
||||
/// <param name="rulePattern">The text of a rule to save, or <see langword="null"/>.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The movement.</returns>
|
||||
public async Task<BankStatementLine> PostAsync(
|
||||
Actor actor, string companyCode, long lineId, long accountId, string? description, string? rulePattern, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, 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 line = await OpenLineAsync(uow, lineId, cancellationToken).ConfigureAwait(false);
|
||||
var account = await uow.Repository<GlAccount, long>().GetAsync(accountId, cancellationToken).ConfigureAwait(false);
|
||||
if (account is null || !account.Postable || account.Disabled || account.SubLedger)
|
||||
{
|
||||
throw new ValidationFailedException(["AccountId:" + LedgerErrors.AccountNotPostable]);
|
||||
}
|
||||
|
||||
long? ruleId = null;
|
||||
if (!string.IsNullOrWhiteSpace(rulePattern))
|
||||
{
|
||||
var rule = new BankMatchRule
|
||||
{
|
||||
Name = LedgerStore.Trim(rulePattern.Trim(), 100)!,
|
||||
Pattern = LedgerStore.Trim(rulePattern.Trim().ToUpperInvariant(), 100)!,
|
||||
Direction = line.Amount < 0m ? BankRuleDirection.Out : BankRuleDirection.In,
|
||||
AccountId = accountId,
|
||||
TemplateCode = "SPB",
|
||||
EntryDescription = LedgerStore.Trim(string.IsNullOrWhiteSpace(description) ? null : description.Trim(), 200),
|
||||
};
|
||||
ruleId = await uow.Repository<BankMatchRule, long>().InsertAsync(rule, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await PostEntryAsync(uow, pack, line, accountId, string.IsNullOrWhiteSpace(description) ? line.Description : description.Trim(), "SPB", cancellationToken).ConfigureAwait(false);
|
||||
Matched(line, StatementMatchKind.Entry, actor.UserName);
|
||||
line.RuleId = ruleId;
|
||||
await uow.Repository<BankStatementLine, long>().UpdateAsync(line, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return line;
|
||||
}
|
||||
|
||||
/// <summary>Leaves a movement out of the reconciliation (a transfer between own accounts already posted).</summary>
|
||||
/// <param name="actor">Who does it.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="lineId">The movement.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task IgnoreAsync(Actor actor, string companyCode, long lineId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var line = await OpenLineAsync(uow, lineId, cancellationToken).ConfigureAwait(false);
|
||||
line.Status = StatementLineStatus.Ignored;
|
||||
line.MatchedAt = _clock.GetUtcNow().UtcDateTime;
|
||||
line.MatchedBy = actor.UserName;
|
||||
await uow.Repository<BankStatementLine, long>().UpdateAsync(line, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Takes a reconciliation back: the collection or entry it made is cancelled, a link to a payment is removed.
|
||||
/// Credits and unpaid effects of remittances are taken back from the remittance.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who does it.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="lineId">The movement.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task ResetAsync(Actor actor, string companyCode, long lineId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var line = await uow.Repository<BankStatementLine, long>().GetAsync(lineId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound);
|
||||
var today = TreasuryStore.Today(_clock);
|
||||
if (line.Status == StatementLineStatus.Matched)
|
||||
{
|
||||
switch (line.MatchKind)
|
||||
{
|
||||
case StatementMatchKind.OpenItems when line.PaymentId is { } paymentId:
|
||||
if (await uow.Repository<Payment, long>().GetAsync(paymentId, cancellationToken).ConfigureAwait(false) is { } payment)
|
||||
{
|
||||
await PaymentService.CancelAsync(uow, payment, today, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
break;
|
||||
case StatementMatchKind.Payment when line.PaymentId is { } linked:
|
||||
await uow.ExecuteAsync(SqlFragment.Of($"UPDATE payments SET statement_line_id = NULL WHERE id = {linked}"), cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
case StatementMatchKind.Rule or StatementMatchKind.Entry:
|
||||
await TreasuryStore.UndoEntryAsync(uow, line.GlEntryId, today, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
case StatementMatchKind.RemittanceCredit or StatementMatchKind.Unpaid:
|
||||
throw new ValidationFailedException(["Id:" + TreasuryErrors.FromRemittance]);
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
line = await uow.Repository<BankStatementLine, long>().GetAsync(lineId, cancellationToken).ConfigureAwait(false) ?? line;
|
||||
line.Status = StatementLineStatus.ToMatch;
|
||||
line.MatchKind = StatementMatchKind.None;
|
||||
line.Confidence = 0;
|
||||
line.Proposal = null;
|
||||
line.Targets = null;
|
||||
line.PartyId = null;
|
||||
line.RuleId = null;
|
||||
line.PaymentId = null;
|
||||
line.GlEntryId = null;
|
||||
line.MatchedAt = null;
|
||||
line.MatchedBy = null;
|
||||
await uow.Repository<BankStatementLine, long>().UpdateAsync(line, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The saved rules.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rules, by name.</returns>
|
||||
public async Task<IReadOnlyList<BankMatchRule>> RulesAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return (await uow.Repository<BankMatchRule, long>().ListAsync(Query.For<BankMatchRule>().OrderBy(r => r.Name), cancellationToken).ConfigureAwait(false)).Items;
|
||||
}
|
||||
|
||||
/// <summary>Writes a rule.</summary>
|
||||
/// <param name="actor">Who writes.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="input">The rule.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rule.</returns>
|
||||
public async Task<BankMatchRule> SaveRuleAsync(Actor actor, string companyCode, BankRuleInput input, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
ArgumentNullException.ThrowIfNull(input);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, cancellationToken).ConfigureAwait(false);
|
||||
if (string.IsNullOrWhiteSpace(input.Pattern) || string.IsNullOrWhiteSpace(input.Name) || input.AccountId <= 0)
|
||||
{
|
||||
throw new ValidationFailedException(["Pattern:" + TreasuryErrors.RulePattern]);
|
||||
}
|
||||
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var repository = uow.Repository<BankMatchRule, long>();
|
||||
var rule = input.Id is { } id ? await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound) : new BankMatchRule();
|
||||
rule.Name = LedgerStore.Trim(input.Name.Trim(), 100)!;
|
||||
rule.Pattern = LedgerStore.Trim(input.Pattern.Trim().ToUpperInvariant(), 100)!;
|
||||
rule.Direction = input.Direction;
|
||||
rule.AccountId = input.AccountId;
|
||||
rule.TemplateCode ??= "SPB";
|
||||
rule.EntryDescription = LedgerStore.Trim(string.IsNullOrWhiteSpace(input.EntryDescription) ? null : input.EntryDescription.Trim(), 200);
|
||||
rule.Disabled = input.Disabled;
|
||||
if (input.Id is null)
|
||||
{
|
||||
rule.Id = await repository.InsertAsync(rule, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await repository.UpdateAsync(rule, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return rule;
|
||||
}
|
||||
|
||||
/// <summary>Deletes a rule.</summary>
|
||||
/// <param name="actor">Who does it.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The rule.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task DeleteRuleAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.BankReconcile, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
await uow.ExecuteAsync(SqlFragment.Of($"UPDATE bank_statement_lines SET rule_id = NULL WHERE rule_id = {id}"), cancellationToken).ConfigureAwait(false);
|
||||
await uow.Repository<BankMatchRule, long>().DeleteAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Gives the movements to reconcile of a bank account their best proposal.</summary>
|
||||
internal static async Task<int> SuggestAsync(IUnitOfWork uow, long bankAccountId, CancellationToken cancellationToken)
|
||||
{
|
||||
var lines = (await uow.Repository<BankStatementLine, long>().ListAsync(
|
||||
Query.For<BankStatementLine>().Where(l => l.BankAccountId == bankAccountId && (l.Status == StatementLineStatus.ToMatch || l.Status == StatementLineStatus.Suggested)),
|
||||
cancellationToken).ConfigureAwait(false)).Items;
|
||||
if (lines.Count == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var candidates = await CandidatesAsync(uow, bankAccountId, lines.Min(l => l.BookingDate).AddDays(-60), cancellationToken).ConfigureAwait(false);
|
||||
var accounts = (await uow.Repository<GlAccount, long>().ListAsync(Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(a => a.Id);
|
||||
var rules = (await uow.Repository<BankMatchRule, long>().ListAsync(Query.For<BankMatchRule>().Where(r => !r.Disabled), cancellationToken).ConfigureAwait(false)).Items
|
||||
.Select(r => new MatchRule(r.Id, r.Pattern, r.Direction, "Regola '" + r.Name + "' → " + (accounts.TryGetValue(r.AccountId, out var a) ? a.Code + " " + a.Description : string.Empty)))
|
||||
.ToList();
|
||||
var count = 0;
|
||||
foreach (var line in lines)
|
||||
{
|
||||
var movement = new StatementMovement(line.BookingDate, line.ValueDate, line.Amount, line.Description, line.Reference, line.CounterpartyName, line.CounterpartyIban, line.BankCode);
|
||||
var best = BankMatcher.Best(movement, candidates, rules);
|
||||
if (best is null)
|
||||
{
|
||||
line.Status = StatementLineStatus.ToMatch;
|
||||
line.MatchKind = StatementMatchKind.None;
|
||||
line.Confidence = 0;
|
||||
line.Proposal = null;
|
||||
line.Targets = null;
|
||||
line.PartyId = null;
|
||||
line.RuleId = null;
|
||||
}
|
||||
else
|
||||
{
|
||||
line.Status = StatementLineStatus.Suggested;
|
||||
line.MatchKind = best.Kind;
|
||||
line.Confidence = best.Confidence;
|
||||
line.Proposal = LedgerStore.Trim(best.Label, 300);
|
||||
line.Targets = LedgerStore.Trim(best.Targets, 300);
|
||||
line.PartyId = best.PartyId;
|
||||
line.RuleId = best.RuleId;
|
||||
count++;
|
||||
}
|
||||
|
||||
await uow.Repository<BankStatementLine, long>().UpdateAsync(line, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
private static async Task<List<MatchCandidate>> CandidatesAsync(IUnitOfWork uow, long bankAccountId, DateOnly since, CancellationToken cancellationToken)
|
||||
{
|
||||
var result = new List<MatchCandidate>();
|
||||
var items = (await uow.Repository<OpenItem, long>().ListAsync(
|
||||
Query.For<OpenItem>().Where(o => !o.Closed && o.Status != OpenItemStatus.InRemittance && !o.Disputed).OrderBy(o => o.DueDate).OrderBy(o => o.Id), cancellationToken).ConfigureAwait(false)).Items
|
||||
.Where(o => o.Residual != 0m).ToList();
|
||||
var payments = (await uow.Repository<Payment, long>().ListAsync(
|
||||
Query.For<Payment>().Where(p => p.StatementLineId == null && p.PaymentDate >= since && (p.BankAccountId == bankAccountId || p.BankAccountId == null)), cancellationToken).ConfigureAwait(false)).Items
|
||||
.Where(p => p.Origin != PaymentOrigin.Remittance).ToList();
|
||||
var partyIds = items.Select(i => i.PartyId).Concat(payments.Select(p => p.PartyId)).Distinct().ToList();
|
||||
var parties = await TreasuryStore.PartiesAsync(uow, partyIds, cancellationToken).ConfigureAwait(false);
|
||||
var ibans = new Dictionary<long, List<string>>();
|
||||
foreach (var chunk in partyIds.Chunk(500))
|
||||
{
|
||||
var list = chunk.ToList();
|
||||
foreach (var account in (await uow.Repository<PartyBankAccount, long>().ListAsync(Query.For<PartyBankAccount>().Where(a => list.Contains(a.PartyId)), cancellationToken).ConfigureAwait(false)).Items)
|
||||
{
|
||||
(ibans.TryGetValue(account.PartyId, out var found) ? found : ibans[account.PartyId] = []).Add(IbanValidator.Normalize(account.Iban));
|
||||
}
|
||||
}
|
||||
|
||||
IReadOnlyList<string> Names(long partyId) => parties.GetValueOrDefault(partyId) is { } p ? [p.Name, .. p.FiscalName is { } f ? new[] { f } : []] : [];
|
||||
IReadOnlyList<string> Ibans(long partyId) => ibans.GetValueOrDefault(partyId) ?? [];
|
||||
foreach (var item in items)
|
||||
{
|
||||
var receivable = item.Direction == OpenItemDirection.Receivable;
|
||||
var name = parties.GetValueOrDefault(item.PartyId)?.Name ?? string.Empty;
|
||||
result.Add(new MatchCandidate(
|
||||
StatementMatchKind.OpenItems,
|
||||
item.Id.ToString(CultureInfo.InvariantCulture),
|
||||
item.PartyId,
|
||||
receivable ? item.Residual : -item.Residual,
|
||||
item.DueDate,
|
||||
(receivable ? "Incasso " : "Pagamento ") + (item.DocumentNumber ?? string.Empty) + " · " + name,
|
||||
item.DocumentNumber is { } number ? [number] : [],
|
||||
Names(item.PartyId),
|
||||
Ibans(item.PartyId),
|
||||
[]));
|
||||
}
|
||||
|
||||
// Several items of a party paid together.
|
||||
foreach (var group in items.GroupBy(i => (i.PartyId, i.Direction)).Where(g => g.Count() > 1))
|
||||
{
|
||||
var list = group.ToList();
|
||||
var receivable = group.Key.Direction == OpenItemDirection.Receivable;
|
||||
var total = list.Sum(i => i.Residual);
|
||||
result.Add(new MatchCandidate(
|
||||
StatementMatchKind.OpenItems,
|
||||
string.Join(",", list.Select(i => i.Id.ToString(CultureInfo.InvariantCulture))),
|
||||
group.Key.PartyId,
|
||||
receivable ? total : -total,
|
||||
list.Max(i => i.DueDate),
|
||||
(receivable ? "Incasso " : "Pagamento ") + list.Count.ToString(CultureInfo.InvariantCulture) + " partite · " + (parties.GetValueOrDefault(group.Key.PartyId)?.Name ?? string.Empty),
|
||||
[.. list.Where(i => i.DocumentNumber is not null).Select(i => i.DocumentNumber!)],
|
||||
Names(group.Key.PartyId),
|
||||
Ibans(group.Key.PartyId),
|
||||
[]));
|
||||
}
|
||||
|
||||
foreach (var payment in payments)
|
||||
{
|
||||
var receipt = payment.Direction == PaymentDirection.Receipt;
|
||||
var money = receipt ? payment.Amount - payment.Fees : -(payment.Amount + payment.Fees);
|
||||
result.Add(new MatchCandidate(
|
||||
StatementMatchKind.Payment,
|
||||
payment.Id.ToString(CultureInfo.InvariantCulture),
|
||||
payment.PartyId,
|
||||
money,
|
||||
payment.PaymentDate,
|
||||
(receipt ? "Incasso registrato " : "Pagamento registrato ") + payment.PaymentDate.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture) + " · " + (parties.GetValueOrDefault(payment.PartyId)?.Name ?? string.Empty),
|
||||
payment.Reference is { } reference ? [reference] : [],
|
||||
Names(payment.PartyId),
|
||||
Ibans(payment.PartyId),
|
||||
[]));
|
||||
}
|
||||
|
||||
// F24 paid from this bank: one movement per day.
|
||||
var linked = (await uow.QueryAsync<long>(SqlFragment.Of($"SELECT gl_entry_id FROM bank_statement_lines WHERE gl_entry_id IS NOT NULL AND match_kind = {nameof(StatementMatchKind.TaxPayment)}"), cancellationToken)
|
||||
.ConfigureAwait(false)).ToHashSet();
|
||||
var taxes = (await uow.Repository<TaxPayment, long>().ListAsync(
|
||||
Query.For<TaxPayment>().Where(t => t.PaidOn != null && t.PaidOn >= since && t.GlEntryId != null), cancellationToken).ConfigureAwait(false)).Items
|
||||
.Where(t => !linked.Contains(t.GlEntryId!.Value) && (t.BankAccountId is null || t.BankAccountId == bankAccountId)).ToList();
|
||||
foreach (var group in taxes.GroupBy(t => t.GlEntryId!.Value))
|
||||
{
|
||||
var total = group.Sum(t => t.Amount);
|
||||
result.Add(new MatchCandidate(
|
||||
StatementMatchKind.TaxPayment, group.Key.ToString(CultureInfo.InvariantCulture), null, -total, group.First().PaidOn!.Value,
|
||||
"Versamento F24 del " + group.First().PaidOn!.Value.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture), [], [], [], ["F24"]));
|
||||
}
|
||||
|
||||
// Remittances to credit and their effects that may come back unpaid.
|
||||
var remittances = (await uow.Repository<Remittance, long>().ListAsync(
|
||||
Query.For<Remittance>().Where(r => r.BankAccountId == bankAccountId && (r.Status == RemittanceStatus.Presented || r.Status == RemittanceStatus.Closed) && r.Kind != RemittanceKind.SepaCreditTransfer),
|
||||
cancellationToken).ConfigureAwait(false)).Items;
|
||||
foreach (var remittance in remittances)
|
||||
{
|
||||
var lines = await RemittanceService.LinesAsync(uow, remittance.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (remittance.Status == RemittanceStatus.Presented && !remittance.Advance)
|
||||
{
|
||||
var included = lines.Where(l => l.Status == RemittanceLineStatus.Included).ToList();
|
||||
if (included.Count > 0)
|
||||
{
|
||||
result.Add(new MatchCandidate(
|
||||
StatementMatchKind.RemittanceCredit, remittance.Id.ToString(CultureInfo.InvariantCulture), null, included.Sum(l => l.Amount), included.Max(l => l.DueDate),
|
||||
"Accredito distinta " + remittance.DisplayNumber, [remittance.DisplayNumber, .. remittance.MessageId is { } m ? new[] { m } : []], [], [], []));
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var line in lines.Where(l => l.Status != RemittanceLineStatus.Unpaid))
|
||||
{
|
||||
result.Add(new MatchCandidate(
|
||||
StatementMatchKind.Unpaid, line.Id.ToString(CultureInfo.InvariantCulture), line.PartyId, -line.Amount, line.DueDate,
|
||||
"Insoluto " + (parties.GetValueOrDefault(line.PartyId)?.Name ?? string.Empty) + " distinta " + remittance.DisplayNumber,
|
||||
line.EndToEndId is { } e ? [e] : [], Names(line.PartyId), Ibans(line.PartyId), ["INSOLUT"], 30m));
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private async Task ApplyAsync(IUnitOfWork uow, IFiscalPack pack, BankStatementLine line, string? userName, CancellationToken cancellationToken)
|
||||
{
|
||||
var targets = (line.Targets ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
|
||||
.Select(t => long.Parse(t, CultureInfo.InvariantCulture)).ToList();
|
||||
switch (line.MatchKind)
|
||||
{
|
||||
case StatementMatchKind.OpenItems:
|
||||
{
|
||||
var repository = uow.Repository<OpenItem, long>();
|
||||
var items = new List<OpenItem>();
|
||||
foreach (var id in targets)
|
||||
{
|
||||
items.Add(await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new ValidationFailedException(["Targets:" + TreasuryErrors.NotFound]));
|
||||
}
|
||||
|
||||
if (items.Count == 0 || items.Select(i => (i.PartyId, i.Direction)).Distinct().Count() != 1
|
||||
|| (items[0].Direction == OpenItemDirection.Receivable) != (line.Amount > 0m))
|
||||
{
|
||||
throw new ValidationFailedException(["Targets:" + TreasuryErrors.MatchAmount]);
|
||||
}
|
||||
|
||||
var amount = Math.Abs(line.Amount);
|
||||
var residuals = items.Select(i => Math.Abs(i.Residual)).ToList();
|
||||
if (amount > residuals.Sum())
|
||||
{
|
||||
throw new ValidationFailedException(["Targets:" + TreasuryErrors.MatchAmount]);
|
||||
}
|
||||
|
||||
var allocation = PaymentAllocator.Allocate(residuals, amount);
|
||||
var input = new PaymentInput(
|
||||
line.Amount > 0m ? PaymentDirection.Receipt : PaymentDirection.Disbursement,
|
||||
items[0].PartyId,
|
||||
line.BookingDate,
|
||||
null,
|
||||
line.BankAccountId,
|
||||
0m,
|
||||
line.Reference,
|
||||
LedgerStore.Trim(line.Description, 500),
|
||||
[.. items.Select((item, i) => new PaymentLineInput(item.Id, Math.Sign(item.Residual) * allocation[i])).Where(l => l.Amount != 0m)]);
|
||||
var payment = await PaymentService.RegisterAsync(uow, pack, input, PaymentOrigin.BankStatement, null, line.Id, cancellationToken).ConfigureAwait(false);
|
||||
line.PaymentId = payment.Id;
|
||||
line.GlEntryId = payment.GlEntryId;
|
||||
line.PartyId = payment.PartyId;
|
||||
break;
|
||||
}
|
||||
|
||||
case StatementMatchKind.Payment:
|
||||
{
|
||||
var payment = await uow.Repository<Payment, long>().GetAsync(targets.Single(), cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ValidationFailedException(["Targets:" + TreasuryErrors.NotFound]);
|
||||
if (payment.StatementLineId is not null)
|
||||
{
|
||||
throw new ValidationFailedException(["Targets:" + TreasuryErrors.MatchDone]);
|
||||
}
|
||||
|
||||
payment.StatementLineId = line.Id;
|
||||
await uow.Repository<Payment, long>().UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
|
||||
line.PaymentId = payment.Id;
|
||||
line.GlEntryId = payment.GlEntryId;
|
||||
line.PartyId = payment.PartyId;
|
||||
break;
|
||||
}
|
||||
|
||||
case StatementMatchKind.TaxPayment:
|
||||
line.GlEntryId = targets.Single();
|
||||
break;
|
||||
|
||||
case StatementMatchKind.RemittanceCredit:
|
||||
{
|
||||
var remittance = await uow.Repository<Remittance, long>().GetAsync(targets.Single(), cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ValidationFailedException(["Targets:" + TreasuryErrors.NotFound]);
|
||||
await RemittanceService.CreditInsideAsync(uow, pack, remittance, line.BookingDate, cancellationToken).ConfigureAwait(false);
|
||||
line.GlEntryId = remittance.CreditEntryId;
|
||||
break;
|
||||
}
|
||||
|
||||
case StatementMatchKind.Unpaid:
|
||||
{
|
||||
var remittanceLine = await uow.Repository<RemittanceLine, long>().GetAsync(targets.Single(), cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ValidationFailedException(["Targets:" + TreasuryErrors.NotFound]);
|
||||
var fees = Math.Max(0m, Math.Abs(line.Amount) - remittanceLine.Amount);
|
||||
await RemittanceService.UnpaidInsideAsync(uow, pack, remittanceLine, line.BookingDate, fees, cancellationToken).ConfigureAwait(false);
|
||||
line.GlEntryId = remittanceLine.UnpaidEntryId;
|
||||
line.PartyId = remittanceLine.PartyId;
|
||||
break;
|
||||
}
|
||||
|
||||
case StatementMatchKind.Rule:
|
||||
{
|
||||
var rule = line.RuleId is { } ruleId ? await uow.Repository<BankMatchRule, long>().GetAsync(ruleId, cancellationToken).ConfigureAwait(false) : null;
|
||||
if (rule is null)
|
||||
{
|
||||
throw new ValidationFailedException(["RuleId:" + TreasuryErrors.NotFound]);
|
||||
}
|
||||
|
||||
await PostEntryAsync(uow, pack, line, rule.AccountId, rule.EntryDescription ?? line.Description, rule.TemplateCode ?? "SPB", cancellationToken).ConfigureAwait(false);
|
||||
rule.Uses++;
|
||||
await uow.Repository<BankMatchRule, long>().UpdateAsync(rule, cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
throw new ValidationFailedException(["Targets:" + TreasuryErrors.MatchAmount]);
|
||||
}
|
||||
|
||||
Matched(line, line.MatchKind, userName);
|
||||
await uow.Repository<BankStatementLine, long>().UpdateAsync(line, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static async Task PostEntryAsync(IUnitOfWork uow, IFiscalPack pack, BankStatementLine line, long accountId, string description, string templateCode, CancellationToken cancellationToken)
|
||||
{
|
||||
var template = await LedgerStore.TemplateAsync(uow, templateCode, cancellationToken).ConfigureAwait(false);
|
||||
var bank = await TreasuryStore.BankAsync(uow, line.BankAccountId, cancellationToken).ConfigureAwait(false);
|
||||
var money = await TreasuryStore.MoneyAccountAsync(uow, bank, false, template?.Lines, pack.GetFeature<ILedgerTemplate>(), cancellationToken).ConfigureAwait(false);
|
||||
var amount = Math.Abs(line.Amount);
|
||||
var text = LedgerStore.Trim(description, 200)!;
|
||||
IReadOnlyList<PaymentPostedLine> lines = line.Amount < 0m
|
||||
? [new PaymentPostedLine(accountId, null, null, text, amount, 0m), new PaymentPostedLine(money, null, null, text, 0m, amount)]
|
||||
: [new PaymentPostedLine(money, null, null, text, amount, 0m), new PaymentPostedLine(accountId, null, null, text, 0m, amount)];
|
||||
var entry = await TreasuryStore.PostAsync(uow, templateCode, line.BookingDate, text, null, lines, line.IsDemo, cancellationToken).ConfigureAwait(false);
|
||||
line.GlEntryId = entry.Id;
|
||||
}
|
||||
|
||||
private static async Task<BankStatementLine> OpenLineAsync(IUnitOfWork uow, long lineId, CancellationToken cancellationToken)
|
||||
{
|
||||
var line = await uow.Repository<BankStatementLine, long>().GetAsync(lineId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound);
|
||||
if (line.Status is StatementLineStatus.Matched or StatementLineStatus.Ignored)
|
||||
{
|
||||
throw new ValidationFailedException(["Id:" + TreasuryErrors.MatchDone]);
|
||||
}
|
||||
|
||||
return line;
|
||||
}
|
||||
|
||||
private void Matched(BankStatementLine line, StatementMatchKind kind, string? userName)
|
||||
{
|
||||
line.Status = StatementLineStatus.Matched;
|
||||
line.MatchKind = kind;
|
||||
line.MatchedAt = _clock.GetUtcNow().UtcDateTime;
|
||||
line.MatchedBy = userName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
using System.Globalization;
|
||||
using Khaemhat.Application.Ledger;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Accounting;
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Core.Treasury;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Treasury;
|
||||
|
||||
/// <summary>The balance of a bank or cash account in the ledger.</summary>
|
||||
/// <param name="BankAccountId">The bank account, or <see langword="null"/> for the cash.</param>
|
||||
/// <param name="Name">Its name.</param>
|
||||
/// <param name="Balance">Its ledger balance today.</param>
|
||||
public sealed record CashAccountBalance(long? BankAccountId, string Name, decimal Balance);
|
||||
|
||||
/// <summary>The cash flow forecast.</summary>
|
||||
/// <param name="From">The first day.</param>
|
||||
/// <param name="Days">How many days.</param>
|
||||
/// <param name="Accounts">The banks and the cash with their balance.</param>
|
||||
/// <param name="Opening">The money today.</param>
|
||||
/// <param name="Periods">The periods with what comes in, goes out and the balance after.</param>
|
||||
/// <param name="Movements">The movements forecast, by date.</param>
|
||||
/// <param name="Sources">The sources included.</param>
|
||||
public sealed record CashFlowForecast(
|
||||
DateOnly From, int Days, IReadOnlyList<CashAccountBalance> Accounts, decimal Opening, IReadOnlyList<CashFlowPeriod> Periods, IReadOnlyList<CashFlowMovement> Movements,
|
||||
IReadOnlySet<CashFlowSource> Sources);
|
||||
|
||||
/// <summary>
|
||||
/// The cash flow forecast (SPEC §11.8 report "flusso di cassa 90 gg", ADR 0038): the money of the banks and the cash
|
||||
/// today and what the open items, the remittances presented, the orders not yet invoiced, the recurring entries and the
|
||||
/// taxes to pay will move, week by week. The overdue items fall in the first week.
|
||||
/// </summary>
|
||||
public sealed class CashFlowService
|
||||
{
|
||||
/// <summary>The days after the delivery when an order is expected to be paid.</summary>
|
||||
public const int OrderPaymentDays = 30;
|
||||
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
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="clock">The clock.</param>
|
||||
public CashFlowService(IUnitOfWorkFactory factory, PermissionService permissions, TimeProvider clock)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
_clock = clock;
|
||||
}
|
||||
|
||||
/// <summary>The forecast.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="days">How many days ahead (30 to 365).</param>
|
||||
/// <param name="sources">The sources to include, or <see langword="null"/> for all.</param>
|
||||
/// <param name="periodDays">The length of a period (7 for weeks, 30 for months).</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The forecast.</returns>
|
||||
public async Task<CashFlowForecast> ForecastAsync(
|
||||
Actor actor, string companyCode, int days = 90, IReadOnlySet<CashFlowSource>? sources = null, int periodDays = 7, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleRead, cancellationToken).ConfigureAwait(false);
|
||||
days = Math.Clamp(days, 30, 365);
|
||||
var include = sources ?? Enum.GetValues<CashFlowSource>().ToHashSet();
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var today = TreasuryStore.Today(_clock);
|
||||
var until = today.AddDays(days - 1);
|
||||
var accounts = await BalancesAsync(uow, today, cancellationToken).ConfigureAwait(false);
|
||||
var movements = new List<CashFlowMovement>();
|
||||
var parties = new Dictionary<long, string>();
|
||||
|
||||
if (include.Contains(CashFlowSource.Receivables) || include.Contains(CashFlowSource.Payables))
|
||||
{
|
||||
var items = (await uow.Repository<OpenItem, long>().ListAsync(
|
||||
Query.For<OpenItem>().Where(o => !o.Closed && o.DueDate <= until), cancellationToken).ConfigureAwait(false)).Items;
|
||||
foreach (var (id, party) in await TreasuryStore.PartiesAsync(uow, items.Select(i => i.PartyId), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
parties[id] = party.Name;
|
||||
}
|
||||
|
||||
foreach (var item in items.Where(i => i.Residual != 0m))
|
||||
{
|
||||
var receivable = item.Direction == OpenItemDirection.Receivable;
|
||||
if (!include.Contains(receivable ? CashFlowSource.Receivables : CashFlowSource.Payables))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
movements.Add(new CashFlowMovement(
|
||||
item.DueDate, receivable ? item.Residual : -item.Residual, receivable ? CashFlowSource.Receivables : CashFlowSource.Payables,
|
||||
(item.DocumentNumber ?? string.Empty) + " · " + parties.GetValueOrDefault(item.PartyId)));
|
||||
}
|
||||
|
||||
if (include.Contains(CashFlowSource.Receivables))
|
||||
{
|
||||
// Effects presented without advance: the bank credits them at maturity.
|
||||
var presented = (await uow.Repository<Remittance, long>().ListAsync(
|
||||
Query.For<Remittance>().Where(r => r.Status == RemittanceStatus.Presented && !r.Advance), cancellationToken).ConfigureAwait(false)).Items;
|
||||
foreach (var remittance in presented)
|
||||
{
|
||||
foreach (var line in (await RemittanceService.LinesAsync(uow, remittance.Id, cancellationToken).ConfigureAwait(false)).Where(l => l.Status == RemittanceLineStatus.Included))
|
||||
{
|
||||
movements.Add(new CashFlowMovement(line.DueDate, line.Amount, CashFlowSource.Receivables, "Distinta " + remittance.DisplayNumber));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (include.Contains(CashFlowSource.SaleOrders))
|
||||
{
|
||||
movements.AddRange(await OrdersAsync<SaleOrder, SaleOrderLine>(uow, 1m, CashFlowSource.SaleOrders, until, cancellationToken).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
if (include.Contains(CashFlowSource.PurchaseOrders))
|
||||
{
|
||||
movements.AddRange(await OrdersAsync<PurchaseOrder, PurchaseOrderLine>(uow, -1m, CashFlowSource.PurchaseOrders, until, cancellationToken).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
if (include.Contains(CashFlowSource.Recurring))
|
||||
{
|
||||
movements.AddRange(await RecurringAsync(uow, today, until, cancellationToken).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
if (include.Contains(CashFlowSource.Taxes))
|
||||
{
|
||||
var taxes = (await uow.Repository<TaxPayment, long>().ListAsync(
|
||||
Query.For<TaxPayment>().Where(t => t.PaidOn == null && t.DueDate <= until), cancellationToken).ConfigureAwait(false)).Items;
|
||||
movements.AddRange(taxes.Select(t => new CashFlowMovement(t.DueDate, -t.Amount, CashFlowSource.Taxes, "F24 " + t.PaymentCode + " · " + t.Description)));
|
||||
}
|
||||
|
||||
var opening = accounts.Sum(a => a.Balance);
|
||||
var periods = CashFlowForecaster.Periods(opening, movements, today, days, periodDays);
|
||||
return new CashFlowForecast(today, days, accounts, opening, periods, [.. movements.OrderBy(m => m.Date)], include);
|
||||
}
|
||||
|
||||
private static async Task<IReadOnlyList<CashAccountBalance>> BalancesAsync(IUnitOfWork uow, DateOnly today, CancellationToken cancellationToken)
|
||||
{
|
||||
var result = new List<CashAccountBalance>();
|
||||
var draft = nameof(GlEntryStatus.Draft);
|
||||
var banks = (await uow.Repository<BankAccount, long>().ListAsync(Query.For<BankAccount>().OrderBy(b => b.Code), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var seen = new HashSet<long>();
|
||||
foreach (var bank in banks)
|
||||
{
|
||||
if (await LedgerStore.AccountAsync(uow, bank.AccountCode, cancellationToken).ConfigureAwait(false) is not { } account || !seen.Add(account.Id))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var balance = await uow.QuerySingleAsync<decimal?>(
|
||||
SqlFragment.Of($"SELECT SUM(debit - credit) FROM gl_entry_lines WHERE account_id = {account.Id} AND status <> {draft} AND entry_date <= {today}"), cancellationToken).ConfigureAwait(false) ?? 0m;
|
||||
result.Add(new CashAccountBalance(bank.Id, bank.Code + " · " + (bank.BankName ?? bank.Description), balance));
|
||||
}
|
||||
|
||||
var cash = await uow.QuerySingleAsync<decimal?>(
|
||||
SqlFragment.Of($"SELECT SUM(l.debit - l.credit) FROM gl_entry_lines l JOIN gl_accounts a ON a.id = l.account_id WHERE a.type = {nameof(AccountType.Cash)} AND l.status <> {draft} AND l.entry_date <= {today}"),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
if (cash is { } amount && amount != 0m)
|
||||
{
|
||||
result.Add(new CashAccountBalance(null, "Cassa", amount));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static async Task<IReadOnlyList<CashFlowMovement>> OrdersAsync<THeader, TLine>(
|
||||
IUnitOfWork uow, decimal sign, CashFlowSource source, DateOnly until, CancellationToken cancellationToken)
|
||||
where THeader : DocumentHeader, new()
|
||||
where TLine : DocumentLine, new()
|
||||
{
|
||||
var orders = (await uow.Repository<THeader, long>().ListAsync(
|
||||
Query.For<THeader>().Where(o => o.Status == DocumentStatus.Confirmed || o.Status == DocumentStatus.PartiallyFulfilled), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var result = new List<CashFlowMovement>();
|
||||
foreach (var chunk in orders.Chunk(200))
|
||||
{
|
||||
var ids = chunk.Select(o => o.Id).ToList();
|
||||
var lines = (await uow.Repository<TLine, long>().ListAsync(Query.For<TLine>().Where(l => ids.Contains(l.DocumentId)), cancellationToken).ConfigureAwait(false)).Items
|
||||
.GroupBy(l => l.DocumentId).ToDictionary(g => g.Key, g => g.ToList());
|
||||
foreach (var order in chunk)
|
||||
{
|
||||
var date = (order.DeliveryDate ?? order.DocumentDate).AddDays(OrderPaymentDays);
|
||||
if (date > until || order.TaxableAmount == 0m || !lines.TryGetValue(order.Id, out var orderLines))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// What is still to deliver, with the VAT in the proportion of the order.
|
||||
var taxable = orderLines.Where(l => l.Quantity != 0m).Sum(l => l.TaxableAmount * l.Residual / l.Quantity);
|
||||
var gross = Math.Round(taxable * order.TotalAmount / order.TaxableAmount, 2, MidpointRounding.AwayFromZero);
|
||||
if (gross != 0m)
|
||||
{
|
||||
result.Add(new CashFlowMovement(date, sign * gross, source, (order.DocumentNumber ?? order.Id.ToString(CultureInfo.InvariantCulture))));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static async Task<IReadOnlyList<CashFlowMovement>> RecurringAsync(IUnitOfWork uow, DateOnly today, DateOnly until, CancellationToken cancellationToken)
|
||||
{
|
||||
var recurring = (await uow.Repository<RecurringEntry, long>().ListAsync(Query.For<RecurringEntry>().Where(r => !r.Disabled), cancellationToken).ConfigureAwait(false)).Items;
|
||||
if (recurring.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var moneyAccounts = new HashSet<long>();
|
||||
foreach (var bank in (await uow.Repository<BankAccount, long>().ListAsync(Query.For<BankAccount>(), cancellationToken).ConfigureAwait(false)).Items)
|
||||
{
|
||||
if (await LedgerStore.AccountAsync(uow, bank.AccountCode, cancellationToken).ConfigureAwait(false) is { } account)
|
||||
{
|
||||
moneyAccounts.Add(account.Id);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var account in (await uow.Repository<GlAccount, long>().ListAsync(Query.For<GlAccount>().Where(a => a.Type == AccountType.Cash || a.Type == AccountType.Bank), cancellationToken).ConfigureAwait(false)).Items)
|
||||
{
|
||||
moneyAccounts.Add(account.Id);
|
||||
}
|
||||
|
||||
var result = new List<CashFlowMovement>();
|
||||
foreach (var entry in recurring)
|
||||
{
|
||||
var lines = await LedgerStore.LinesAsync(uow, entry.ModelEntryId, cancellationToken).ConfigureAwait(false);
|
||||
var amount = lines.Where(l => moneyAccounts.Contains(l.AccountId)).Sum(l => l.Debit - l.Credit);
|
||||
if (amount == 0m)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
for (var date = entry.NextDate; date <= until && (entry.EndDate is null || date <= entry.EndDate); date = RecurringEntryService.Next(date, entry.Frequency))
|
||||
{
|
||||
if (date >= today)
|
||||
{
|
||||
result.Add(new CashFlowMovement(date, amount, CashFlowSource.Recurring, entry.Description));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,606 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Khaemhat.Application.Audit;
|
||||
using Khaemhat.Data.Companies;
|
||||
using Khaemhat.Application.Jobs;
|
||||
using Khaemhat.Application.Ledger;
|
||||
using Khaemhat.Application.Licensing;
|
||||
using Khaemhat.Application.Modules;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Accounting;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Core.Treasury;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
using Khaemhat.Infrastructure.Files;
|
||||
using Khaemhat.Infrastructure.Mail;
|
||||
|
||||
namespace Khaemhat.Application.Treasury;
|
||||
|
||||
/// <summary>A customer to remind, with the level due and its overdue items.</summary>
|
||||
/// <param name="PartyId">The customer.</param>
|
||||
/// <param name="PartyCode">Its code.</param>
|
||||
/// <param name="PartyName">Its name.</param>
|
||||
/// <param name="Email">Its e-mail.</param>
|
||||
/// <param name="Pec">Its PEC.</param>
|
||||
/// <param name="Level">The level due, or <see langword="null"/> when none is due yet.</param>
|
||||
/// <param name="CurrentLevel">The highest level already sent for its items.</param>
|
||||
/// <param name="Items">The overdue items.</param>
|
||||
/// <param name="Overdue">Their residual.</param>
|
||||
/// <param name="Interest">The late payment interest to the day.</param>
|
||||
/// <param name="MaxDays">The days past due of the oldest item.</param>
|
||||
/// <param name="LastSent">The last reminder.</param>
|
||||
/// <param name="Blocked">The customer is blocked.</param>
|
||||
public sealed record DunningProposal(
|
||||
long PartyId, string? PartyCode, string PartyName, string? Email, string? Pec, DunningLevel? Level, int CurrentLevel, IReadOnlyList<ScheduleRow> Items,
|
||||
decimal Overdue, decimal Interest, int MaxDays, DateOnly? LastSent, bool Blocked);
|
||||
|
||||
/// <summary>A reminder sent, with the name of its customer.</summary>
|
||||
/// <param name="Letter">The reminder.</param>
|
||||
/// <param name="PartyName">The customer.</param>
|
||||
public sealed record DunningLetterRow(DunningLetter Letter, string PartyName);
|
||||
|
||||
/// <summary>What a run of reminders did.</summary>
|
||||
/// <param name="Sent">Reminders queued by e-mail or PEC.</param>
|
||||
/// <param name="Letters">Reminders to print (letter channel).</param>
|
||||
/// <param name="Skipped">Customers left out, with the reason code.</param>
|
||||
/// <param name="Pdf">The letters to print, one file, when any.</param>
|
||||
public sealed record DunningRun(int Sent, int Letters, IReadOnlyList<(string Party, string Reason)> Skipped, LedgerFile? Pdf);
|
||||
|
||||
/// <summary>
|
||||
/// The reminders (solleciti, SPEC §11.8, mockup 056, ADR 0038): levels after the due date with their texts and
|
||||
/// channels, the proposal of the customers to remind (disputed items and public administrations left out), the
|
||||
/// sending by e-mail, PEC or printed letter with the late payment interest of the pack, the log of what was sent, the
|
||||
/// block of the customer at the last level, and the scheduled task for the automatic levels.
|
||||
/// </summary>
|
||||
public sealed class DunningService
|
||||
{
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly CompanyFiscalContext _packs;
|
||||
private readonly AuditTrail _audit;
|
||||
private readonly IMailQueue _mail;
|
||||
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="mail">The outgoing mail.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
public DunningService(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, AuditTrail audit, IMailQueue mail, TimeProvider clock)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(packs);
|
||||
ArgumentNullException.ThrowIfNull(audit);
|
||||
ArgumentNullException.ThrowIfNull(mail);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
_packs = packs;
|
||||
_audit = audit;
|
||||
_mail = mail;
|
||||
_clock = clock;
|
||||
}
|
||||
|
||||
/// <summary>The levels given to a company that has none (mockup 056).</summary>
|
||||
/// <returns>Three levels: 7, 20 and 45 days after the due date.</returns>
|
||||
public static IReadOnlyList<DunningLevel> DefaultLevels() =>
|
||||
[
|
||||
new()
|
||||
{
|
||||
Level = 1, DaysAfterDue = 7, Name = "Promemoria cortese", Channel = DunningChannel.Email, Action = DunningAction.None,
|
||||
Subject = "Promemoria scadenze - {azienda}",
|
||||
Body = "Gentile {cliente},\n\nle ricordiamo che risultano scadute le seguenti partite:\n\n{elenco}\n\nTotale scaduto: {totale}.\n\nSe ha già provveduto al pagamento, la preghiamo di non tenere conto di questo messaggio.\n\nCordiali saluti\n{azienda}",
|
||||
},
|
||||
new()
|
||||
{
|
||||
Level = 2, DaysAfterDue = 20, Name = "Sollecito", Channel = DunningChannel.Email | DunningChannel.Pec, Action = DunningAction.NotifyAgent, ChargeInterest = true,
|
||||
Subject = "Sollecito di pagamento - {azienda}",
|
||||
Body = "Gentile {cliente},\n\nnonostante il nostro precedente promemoria, risultano ancora scadute le seguenti partite:\n\n{elenco}\n\nTotale scaduto: {totale}. Interessi di mora maturati ({riferimento}): {interessi}.\n\nLa invitiamo a provvedere al pagamento entro 10 giorni.\n\nCordiali saluti\n{azienda}",
|
||||
},
|
||||
new()
|
||||
{
|
||||
Level = 3, DaysAfterDue = 45, Name = "Diffida e blocco forniture", Channel = DunningChannel.Pec | DunningChannel.Letter, Action = DunningAction.BlockCustomer, ChargeInterest = true,
|
||||
Subject = "Diffida ad adempiere - {azienda}",
|
||||
Body = "Spettabile {cliente},\n\nle partite seguenti sono scadute da oltre {giorni} giorni:\n\n{elenco}\n\nTotale scaduto: {totale}, oltre agli interessi di mora ({riferimento}) per {interessi} e al risarcimento dei costi di recupero.\n\nVi diffidiamo a pagare entro 15 giorni; in mancanza procederemo al recupero del credito senza ulteriore avviso. Le forniture sono sospese fino al saldo.\n\n{azienda}",
|
||||
},
|
||||
];
|
||||
|
||||
/// <summary>The levels, created with the defaults when the company has none.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The levels in order.</returns>
|
||||
public async Task<IReadOnlyList<DunningLevel>> LevelsAsync(Actor actor, string companyCode, 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);
|
||||
return await EnsureLevelsAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Writes a level.</summary>
|
||||
/// <param name="actor">Who writes.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="level">The level (its <c>Level</c> number identifies it).</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The level.</returns>
|
||||
public async Task<DunningLevel> SaveLevelAsync(Actor actor, string companyCode, DunningLevel level, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
ArgumentNullException.ThrowIfNull(level);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleWrite, cancellationToken).ConfigureAwait(false);
|
||||
if (level.Level is < 1 or > 9 || level.DaysAfterDue < 0 || string.IsNullOrWhiteSpace(level.Name) || string.IsNullOrWhiteSpace(level.Subject) || string.IsNullOrWhiteSpace(level.Body)
|
||||
|| level.Channel == DunningChannel.None)
|
||||
{
|
||||
throw new ValidationFailedException(["Level:" + TreasuryErrors.DunningLevel]);
|
||||
}
|
||||
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
await EnsureLevelsAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
var repository = uow.Repository<DunningLevel, long>();
|
||||
var number = level.Level;
|
||||
var existing = await repository.FindAsync(Query.For<DunningLevel>().Where(l => l.Level == number), cancellationToken).ConfigureAwait(false);
|
||||
level.Name = LedgerStore.Trim(level.Name.Trim(), 100)!;
|
||||
level.Subject = LedgerStore.Trim(level.Subject.Trim(), 200)!;
|
||||
if (existing is null)
|
||||
{
|
||||
level.Id = await repository.InsertAsync(level, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
level.Id = existing.Id;
|
||||
await repository.UpdateAsync(level, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Update, level.Id, existing, level, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return level;
|
||||
}
|
||||
|
||||
/// <summary>The customers with overdue items and the level due for each.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The proposals, the most overdue first.</returns>
|
||||
public async Task<IReadOnlyList<DunningProposal>> ProposalAsync(Actor actor, string companyCode, 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<ILatePaymentRules>();
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return await ProposalsAsync(uow, rules, TreasuryStore.Today(_clock), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The reminders sent.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="partyId">One customer.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The reminders, latest first (at most 500).</returns>
|
||||
public async Task<IReadOnlyList<DunningLetterRow>> HistoryAsync(Actor actor, string companyCode, long? partyId = null, 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 query = Query.For<DunningLetter>();
|
||||
if (partyId is { } party)
|
||||
{
|
||||
query = query.Where(l => l.PartyId == party);
|
||||
}
|
||||
|
||||
var letters = (await uow.Repository<DunningLetter, long>().ListAsync(query.OrderByDescending(l => l.SentOn).OrderByDescending(l => l.Id).Take(500), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var parties = await TreasuryStore.PartiesAsync(uow, letters.Select(l => l.PartyId), cancellationToken).ConfigureAwait(false);
|
||||
return [.. letters.Select(l => new DunningLetterRow(l, parties.GetValueOrDefault(l.PartyId)?.Name ?? string.Empty))];
|
||||
}
|
||||
|
||||
/// <summary>The letter of the level due for a customer, as a PDF, without sending it.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="partyId">The customer.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The file.</returns>
|
||||
public async Task<LedgerFile> PreviewAsync(Actor actor, string companyCode, long partyId, 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<ILatePaymentRules>();
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var today = TreasuryStore.Today(_clock);
|
||||
var proposal = (await ProposalsAsync(uow, rules, today, cancellationToken).ConfigureAwait(false)).FirstOrDefault(p => p.PartyId == partyId)
|
||||
?? throw new KeyNotFoundException(TreasuryErrors.NotFound);
|
||||
var levels = await EnsureLevelsAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
var level = proposal.Level ?? levels.FirstOrDefault(l => l.Level == Math.Max(1, proposal.CurrentLevel)) ?? levels[0];
|
||||
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
|
||||
var party = await uow.Repository<Party, long>().GetAsync(partyId, cancellationToken).ConfigureAwait(false);
|
||||
var pdf = await LetterAsync(profile, party, level, proposal, rules, today, cancellationToken).ConfigureAwait(false);
|
||||
return new LedgerFile(FileName(proposal, level, today), PdfWriter.MediaType, pdf);
|
||||
}
|
||||
|
||||
/// <summary>Sends the reminders of the level due to customers.</summary>
|
||||
/// <param name="actor">Who sends them.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="partyIds">The customers.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>What was done.</returns>
|
||||
public async Task<DunningRun> SendAsync(Actor actor, string companyCode, IReadOnlyList<long> partyIds, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
ArgumentNullException.ThrowIfNull(partyIds);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleWrite, cancellationToken).ConfigureAwait(false);
|
||||
return await RunAsync(company, partyIds.ToHashSet(), automaticOnly: false, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Sends the automatic levels of a company (the scheduled task).</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>What was done.</returns>
|
||||
public Task<DunningRun> RunAutomaticAsync(string companyCode, CancellationToken cancellationToken = default) =>
|
||||
RunAsync(Data.CompanyCodes.Normalize(companyCode), null, automaticOnly: true, "scheduler", cancellationToken);
|
||||
|
||||
private static string FileName(DunningProposal proposal, DunningLevel level, DateOnly today) =>
|
||||
"sollecito-" + level.Level.ToString(CultureInfo.InvariantCulture) + "-" + (proposal.PartyCode ?? proposal.PartyId.ToString(CultureInfo.InvariantCulture))
|
||||
+ "-" + today.ToString("yyyyMMdd", CultureInfo.InvariantCulture) + ".pdf";
|
||||
|
||||
private static async Task<IReadOnlyList<DunningLevel>> EnsureLevelsAsync(IUnitOfWork uow, CancellationToken cancellationToken)
|
||||
{
|
||||
var repository = uow.Repository<DunningLevel, long>();
|
||||
var levels = (await repository.ListAsync(Query.For<DunningLevel>().OrderBy(l => l.Level), cancellationToken).ConfigureAwait(false)).Items;
|
||||
if (levels.Count > 0)
|
||||
{
|
||||
return levels;
|
||||
}
|
||||
|
||||
var defaults = DefaultLevels();
|
||||
foreach (var level in defaults)
|
||||
{
|
||||
level.Id = await repository.InsertAsync(level, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return defaults;
|
||||
}
|
||||
|
||||
private static async Task<IReadOnlyList<DunningProposal>> ProposalsAsync(IUnitOfWork uow, ILatePaymentRules? rules, DateOnly today, CancellationToken cancellationToken)
|
||||
{
|
||||
var levels = await EnsureLevelsAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
var receivable = OpenItemDirection.Receivable;
|
||||
var items = (await uow.Repository<OpenItem, long>().ListAsync(
|
||||
Query.For<OpenItem>().Where(o => o.Direction == receivable && !o.Closed && !o.Disputed && o.DueDate < today && o.Status != OpenItemStatus.InRemittance)
|
||||
.OrderBy(o => o.DueDate).OrderBy(o => o.Id), cancellationToken).ConfigureAwait(false)).Items.Where(o => o.Residual > 0m).ToList();
|
||||
if (items.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var rows = await ScheduleService.RowsAsync(uow, items, today, cancellationToken).ConfigureAwait(false);
|
||||
var parties = await TreasuryStore.PartiesAsync(uow, items.Select(i => i.PartyId), cancellationToken).ConfigureAwait(false);
|
||||
var blocked = (await uow.Repository<PartySalesTerms, long>().ListAsync(Query.For<PartySalesTerms>().Where(t => t.Blocked), cancellationToken).ConfigureAwait(false)).Items
|
||||
.Select(t => t.PartyId).ToHashSet();
|
||||
var steps = levels.Select(l => new DunningStep(l.Level, l.DaysAfterDue)).ToList();
|
||||
var result = new List<DunningProposal>();
|
||||
foreach (var group in rows.GroupBy(r => r.Item.PartyId))
|
||||
{
|
||||
if (!parties.TryGetValue(group.Key, out var party) || party.SubjectType == SubjectType.PublicAdministration)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var list = group.ToList();
|
||||
var next = DunningRules.NextLevel(
|
||||
[.. list.Select(r => new DunningItem(r.Item.Id, r.Item.DueDate, r.Item.Residual, r.Item.DunningLevel, r.Item.LastDunningDate, r.Item.Disputed))], steps, today);
|
||||
var interest = rules is null ? 0m : list.Sum(r => LateInterestCalculator.Interest(r.Item.Residual, r.Item.DueDate, today, rules.RateOn));
|
||||
result.Add(new DunningProposal(
|
||||
party.Id, party.Code, party.Name, party.Email, party.Pec, next is { } n ? levels.FirstOrDefault(l => l.Level == n) : null,
|
||||
list.Max(r => r.Item.DunningLevel), list, list.Sum(r => r.Item.Residual), interest, list.Max(r => r.DaysOverdue),
|
||||
list.Max(r => r.Item.LastDunningDate), blocked.Contains(party.Id)));
|
||||
}
|
||||
|
||||
return [.. result.OrderByDescending(p => p.Level is not null).ThenByDescending(p => p.MaxDays).ThenBy(p => p.PartyName, StringComparer.CurrentCultureIgnoreCase)];
|
||||
}
|
||||
|
||||
private async Task<DunningRun> RunAsync(string company, HashSet<long>? partyIds, bool automaticOnly, string? userName, CancellationToken cancellationToken)
|
||||
{
|
||||
var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).GetFeature<ILatePaymentRules>();
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var today = TreasuryStore.Today(_clock);
|
||||
var proposals = (await ProposalsAsync(uow, rules, today, cancellationToken).ConfigureAwait(false))
|
||||
.Where(p => p.Level is not null && (partyIds is null || partyIds.Contains(p.PartyId)) && (!automaticOnly || p.Level.Automatic)).ToList();
|
||||
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
|
||||
var skipped = new List<(string, string)>();
|
||||
var printed = new List<byte[]>();
|
||||
int sent = 0, letters = 0;
|
||||
foreach (var proposal in proposals)
|
||||
{
|
||||
var level = proposal.Level!;
|
||||
var channel = level.Channel;
|
||||
if (automaticOnly)
|
||||
{
|
||||
channel &= ~DunningChannel.Letter;
|
||||
}
|
||||
|
||||
var party = await uow.Repository<Party, long>().GetAsync(proposal.PartyId, cancellationToken).ConfigureAwait(false);
|
||||
var recipients = new List<string>();
|
||||
if (channel.HasFlag(DunningChannel.Email) && !string.IsNullOrWhiteSpace(party?.Email))
|
||||
{
|
||||
recipients.Add(party.Email.Trim());
|
||||
}
|
||||
|
||||
if (channel.HasFlag(DunningChannel.Pec) && !string.IsNullOrWhiteSpace(party?.Pec))
|
||||
{
|
||||
recipients.Add(party.Pec.Trim());
|
||||
}
|
||||
|
||||
var letter = channel.HasFlag(DunningChannel.Letter);
|
||||
if (recipients.Count == 0 && !letter)
|
||||
{
|
||||
skipped.Add((proposal.PartyName, TreasuryErrors.DunningRecipient));
|
||||
continue;
|
||||
}
|
||||
|
||||
var pdf = await LetterAsync(profile, party, level, proposal, level.ChargeInterest ? rules : null, today, cancellationToken).ConfigureAwait(false);
|
||||
var (subject, body) = Texts(profile, level, proposal, level.ChargeInterest ? rules : null);
|
||||
var status = DunningLetterStatus.Sent;
|
||||
if (recipients.Count > 0)
|
||||
{
|
||||
var cc = new List<string>();
|
||||
if (level.Action == DunningAction.NotifyAgent && party?.SalespersonId is { } agentId
|
||||
&& await uow.Repository<Salesperson, long>().GetAsync(agentId, cancellationToken).ConfigureAwait(false) is { Email: { Length: > 0 } agentMail })
|
||||
{
|
||||
cc.Add(agentMail);
|
||||
}
|
||||
|
||||
var accepted = _mail.Enqueue(new OutgoingMail(recipients, subject, body)
|
||||
{
|
||||
Cc = cc,
|
||||
ReplyTo = profile?.Email,
|
||||
Attachments = [new MailAttachment(FileName(proposal, level, today), PdfWriter.MediaType, pdf)],
|
||||
Reference = "dunning:" + proposal.PartyId.ToString(CultureInfo.InvariantCulture),
|
||||
});
|
||||
status = accepted ? DunningLetterStatus.Queued : DunningLetterStatus.Failed;
|
||||
if (accepted)
|
||||
{
|
||||
sent++;
|
||||
}
|
||||
}
|
||||
|
||||
if (letter)
|
||||
{
|
||||
printed.Add(pdf);
|
||||
letters++;
|
||||
}
|
||||
|
||||
if (status == DunningLetterStatus.Failed && !letter)
|
||||
{
|
||||
skipped.Add((proposal.PartyName, TreasuryErrors.DunningRecipient));
|
||||
}
|
||||
|
||||
await uow.Repository<DunningLetter, long>().InsertAsync(new DunningLetter
|
||||
{
|
||||
PartyId = proposal.PartyId,
|
||||
Level = level.Level,
|
||||
SentOn = today,
|
||||
Channel = channel,
|
||||
Recipients = LedgerStore.Trim(string.Join(", ", recipients), 300),
|
||||
Subject = LedgerStore.Trim(subject, 200)!,
|
||||
ItemCount = proposal.Items.Count,
|
||||
OverdueAmount = proposal.Overdue,
|
||||
Interest = level.ChargeInterest ? proposal.Interest : 0m,
|
||||
Status = status == DunningLetterStatus.Failed && letter ? DunningLetterStatus.Sent : status,
|
||||
SentBy = userName,
|
||||
IsDemo = proposal.Items.All(i => i.Item.IsDemo),
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var row in proposal.Items)
|
||||
{
|
||||
row.Item.DunningLevel = Math.Max(row.Item.DunningLevel, level.Level);
|
||||
row.Item.LastDunningDate = today;
|
||||
await uow.Repository<OpenItem, long>().UpdateAsync(row.Item, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (level.Action == DunningAction.BlockCustomer)
|
||||
{
|
||||
var terms = uow.Repository<PartySalesTerms, long>();
|
||||
var partyId = proposal.PartyId;
|
||||
var current = await terms.FindAsync(Query.For<PartySalesTerms>().Where(t => t.PartyId == partyId), cancellationToken).ConfigureAwait(false);
|
||||
if (current is null)
|
||||
{
|
||||
await terms.InsertAsync(new PartySalesTerms { PartyId = partyId, Blocked = true }, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else if (!current.Blocked)
|
||||
{
|
||||
current.Blocked = true;
|
||||
await terms.UpdateAsync(current, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
LedgerFile? file = null;
|
||||
if (printed.Count == 1)
|
||||
{
|
||||
file = new LedgerFile("solleciti-" + today.ToString("yyyyMMdd", CultureInfo.InvariantCulture) + ".pdf", PdfWriter.MediaType, printed[0]);
|
||||
}
|
||||
else if (printed.Count > 1)
|
||||
{
|
||||
file = new LedgerFile(
|
||||
"solleciti-" + today.ToString("yyyyMMdd", CultureInfo.InvariantCulture) + ".pdf",
|
||||
PdfWriter.MediaType,
|
||||
await LettersAsync(uow, profile, proposals.Where(p => p.Level!.Channel.HasFlag(DunningChannel.Letter)).ToList(), rules, today, cancellationToken).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
return new DunningRun(sent, letters, skipped, file);
|
||||
}
|
||||
|
||||
private static (string Subject, string Body) Texts(CompanyProfile? profile, DunningLevel level, DunningProposal proposal, ILatePaymentRules? rules)
|
||||
{
|
||||
var culture = CultureInfo.GetCultureInfo("it-IT");
|
||||
var list = new StringBuilder();
|
||||
foreach (var row in proposal.Items)
|
||||
{
|
||||
list.Append("- ").Append(row.Item.DocumentNumber ?? "-").Append(" del ").Append(row.Item.DocumentDate.ToString("dd/MM/yyyy", culture))
|
||||
.Append(", scadenza ").Append(row.Item.DueDate.ToString("dd/MM/yyyy", culture)).Append(": ").Append(row.Item.Residual.ToString("C", culture)).Append('\n');
|
||||
}
|
||||
|
||||
string Fill(string text) => text
|
||||
.Replace("{cliente}", proposal.PartyName, StringComparison.Ordinal)
|
||||
.Replace("{azienda}", profile?.LegalName ?? string.Empty, StringComparison.Ordinal)
|
||||
.Replace("{elenco}", list.ToString().TrimEnd(), StringComparison.Ordinal)
|
||||
.Replace("{totale}", proposal.Overdue.ToString("C", culture), StringComparison.Ordinal)
|
||||
.Replace("{interessi}", (rules is null ? 0m : proposal.Interest).ToString("C", culture), StringComparison.Ordinal)
|
||||
.Replace("{riferimento}", rules?.LegalReference ?? string.Empty, StringComparison.Ordinal)
|
||||
.Replace("{giorni}", proposal.MaxDays.ToString(culture), StringComparison.Ordinal);
|
||||
return (Fill(level.Subject), Fill(level.Body));
|
||||
}
|
||||
|
||||
private static async Task<byte[]> LetterAsync(
|
||||
CompanyProfile? profile, Party? party, DunningLevel level, DunningProposal proposal, ILatePaymentRules? rules, DateOnly today, CancellationToken cancellationToken)
|
||||
{
|
||||
using var buffer = new MemoryStream();
|
||||
await using (var pdf = new PdfWriter(buffer, new PdfDocumentInfo { Title = level.Name, Author = profile?.LegalName }, leaveOpen: true))
|
||||
{
|
||||
await WriteLetterAsync(pdf, profile, party, level, proposal, rules, today, cancellationToken).ConfigureAwait(false);
|
||||
await pdf.CloseAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return buffer.ToArray();
|
||||
}
|
||||
|
||||
private static async Task<byte[]> LettersAsync(
|
||||
IUnitOfWork uow, CompanyProfile? profile, IReadOnlyList<DunningProposal> proposals, ILatePaymentRules? rules, DateOnly today, CancellationToken cancellationToken)
|
||||
{
|
||||
using var buffer = new MemoryStream();
|
||||
await using (var pdf = new PdfWriter(buffer, new PdfDocumentInfo { Title = "Solleciti", Author = profile?.LegalName }, leaveOpen: true))
|
||||
{
|
||||
foreach (var proposal in proposals)
|
||||
{
|
||||
var party = await uow.Repository<Party, long>().GetAsync(proposal.PartyId, cancellationToken).ConfigureAwait(false);
|
||||
await WriteLetterAsync(pdf, profile, party, proposal.Level!, proposal, proposal.Level!.ChargeInterest ? rules : null, today, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await pdf.CloseAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return buffer.ToArray();
|
||||
}
|
||||
|
||||
private static async Task WriteLetterAsync(
|
||||
PdfWriter pdf, CompanyProfile? profile, Party? party, DunningLevel level, DunningProposal proposal, ILatePaymentRules? rules, DateOnly today, CancellationToken cancellationToken)
|
||||
{
|
||||
const double margin = 56;
|
||||
var width = PdfWriter.A4Width;
|
||||
var page = await pdf.AddPageAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
var y = PdfWriter.A4Height - margin;
|
||||
page.DrawText(profile?.LegalName, margin, y, PdfFont.HelveticaBold, 12);
|
||||
y -= 13;
|
||||
page.DrawText(string.Join(" ", new[] { profile?.Address, profile?.StreetNumber }.Where(s => !string.IsNullOrWhiteSpace(s))), margin, y, PdfFont.Helvetica, 8.5);
|
||||
y -= 10;
|
||||
page.DrawText(string.Join(" ", new[] { profile?.PostalCode, profile?.City, profile?.ProvinceCode is null ? null : "(" + profile.ProvinceCode + ")" }.Where(s => !string.IsNullOrWhiteSpace(s))), margin, y, PdfFont.Helvetica, 8.5);
|
||||
y -= 10;
|
||||
page.DrawText("P. IVA " + profile?.VatNumber, margin, y, PdfFont.Helvetica, 8.5);
|
||||
|
||||
// The address of the customer on the right, where the window of the envelope is.
|
||||
var x = width - margin - 220;
|
||||
var top = PdfWriter.A4Height - margin - 90;
|
||||
page.DrawText("Spett.le", x, top, PdfFont.Helvetica, 9);
|
||||
page.DrawText(party?.Name ?? proposal.PartyName, x, top - 13, PdfFont.HelveticaBold, 10);
|
||||
page.DrawText(string.Join(" ", new[] { party?.Address, party?.StreetNumber }.Where(s => !string.IsNullOrWhiteSpace(s))), x, top - 26, PdfFont.Helvetica, 9);
|
||||
page.DrawText(string.Join(" ", new[] { party?.PostalCode, party?.City, party?.Province is null ? null : "(" + party.Province + ")" }.Where(s => !string.IsNullOrWhiteSpace(s))), x, top - 38, PdfFont.Helvetica, 9);
|
||||
if (!string.IsNullOrWhiteSpace(party?.Pec))
|
||||
{
|
||||
page.DrawText("PEC " + party.Pec, x, top - 50, PdfFont.Helvetica, 8.5);
|
||||
}
|
||||
|
||||
var culture = CultureInfo.GetCultureInfo("it-IT");
|
||||
y = top - 90;
|
||||
page.DrawText((profile?.City ?? string.Empty) + ", " + today.ToString("d MMMM yyyy", culture), margin, y, PdfFont.Helvetica, 9.5);
|
||||
y -= 24;
|
||||
var (subject, body) = Texts(profile, level, proposal, rules);
|
||||
page.DrawText("Oggetto: " + subject, margin, y, PdfFont.HelveticaBold, 10);
|
||||
y -= 20;
|
||||
foreach (var paragraph in body.Replace("\r", string.Empty, StringComparison.Ordinal).Split("\n\n"))
|
||||
{
|
||||
if (paragraph.StartsWith("- ", StringComparison.Ordinal))
|
||||
{
|
||||
// The list of items as a table.
|
||||
page.DrawText("Documento", margin, y, PdfFont.HelveticaBold, 8.5);
|
||||
page.DrawText("Data", margin + 150, y, PdfFont.HelveticaBold, 8.5);
|
||||
page.DrawText("Scadenza", margin + 230, y, PdfFont.HelveticaBold, 8.5);
|
||||
page.DrawTextRight("Giorni", margin + 340, y, PdfFont.HelveticaBold, 8.5);
|
||||
page.DrawTextRight("Residuo", width - margin, y, PdfFont.HelveticaBold, 8.5);
|
||||
page.DrawLine(margin, y - 3, width - margin, y - 3, 0.5, PdfColor.Gray(170));
|
||||
y -= 14;
|
||||
foreach (var row in proposal.Items)
|
||||
{
|
||||
if (y < margin + 60)
|
||||
{
|
||||
page = await pdf.AddPageAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
y = PdfWriter.A4Height - margin;
|
||||
}
|
||||
|
||||
page.DrawText(row.Item.DocumentNumber ?? "-", margin, y, PdfFont.Helvetica, 8.5);
|
||||
page.DrawText(row.Item.DocumentDate.ToString("dd/MM/yyyy", culture), margin + 150, y, PdfFont.Helvetica, 8.5);
|
||||
page.DrawText(row.Item.DueDate.ToString("dd/MM/yyyy", culture), margin + 230, y, PdfFont.Helvetica, 8.5);
|
||||
page.DrawTextRight(row.DaysOverdue.ToString(culture), margin + 340, y, PdfFont.Helvetica, 8.5);
|
||||
page.DrawTextRight(row.Item.Residual.ToString("N2", culture), width - margin, y, PdfFont.Helvetica, 8.5);
|
||||
y -= 12;
|
||||
}
|
||||
|
||||
page.DrawLine(margin, y + 8, width - margin, y + 8, 0.5, PdfColor.Gray(170));
|
||||
page.DrawText("Totale scaduto", margin, y - 2, PdfFont.HelveticaBold, 9);
|
||||
page.DrawTextRight(proposal.Overdue.ToString("N2", culture), width - margin, y - 2, PdfFont.HelveticaBold, 9);
|
||||
y -= 22;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (y < margin + 60)
|
||||
{
|
||||
page = await pdf.AddPageAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
y = PdfWriter.A4Height - margin;
|
||||
}
|
||||
|
||||
y = page.DrawParagraph(paragraph, margin, y, width - (2 * margin), PdfFont.Helvetica, 9.5, 13) - 8;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Sends the automatic reminders of every company (job <c>finance.dunning</c>, SPEC §11.8).</summary>
|
||||
/// <param name="companies">The companies.</param>
|
||||
/// <param name="service">The reminders.</param>
|
||||
/// <param name="license">The licence.</param>
|
||||
public sealed class DunningJob(ICompanyRegistry companies, DunningService service, ILicenseGate license) : IScheduledJob
|
||||
{
|
||||
/// <summary>The job type.</summary>
|
||||
public const string JobType = "finance.dunning";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Type => JobType;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<string?> RunAsync(JobContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!license.IsModuleActive(ModuleCodes.Finance))
|
||||
{
|
||||
return "Modulo scadenzario e tesoreria non attivo.";
|
||||
}
|
||||
|
||||
int done = 0, sent = 0;
|
||||
foreach (var company in await companies.ListAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (company.Status is CompanyStatus.Disabled)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var run = await service.RunAutomaticAsync(company.Code, cancellationToken).ConfigureAwait(false);
|
||||
sent += run.Sent;
|
||||
done++;
|
||||
}
|
||||
|
||||
return string.Create(CultureInfo.InvariantCulture, $"{done} aziende, {sent} solleciti in coda di invio.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
using Khaemhat.Application.Audit;
|
||||
using Khaemhat.Application.Ledger;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Treasury;
|
||||
using Khaemhat.Core.Validation;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Treasury;
|
||||
|
||||
/// <summary>A mandate being written.</summary>
|
||||
/// <param name="Id">The mandate, or <see langword="null"/> for a new one.</param>
|
||||
/// <param name="PartyId">The debtor.</param>
|
||||
/// <param name="Reference">The unique mandate reference (UMR).</param>
|
||||
/// <param name="SignatureDate">The day it was signed.</param>
|
||||
/// <param name="Scheme">Core or B2B.</param>
|
||||
/// <param name="Iban">The account of the debtor.</param>
|
||||
/// <param name="Bic">The BIC.</param>
|
||||
/// <param name="OneOff">For one collection only.</param>
|
||||
/// <param name="Notes">Notes.</param>
|
||||
public sealed record MandateInput(long? Id, long PartyId, string Reference, DateOnly SignatureDate, SddScheme Scheme, string Iban, string? Bic, bool OneOff, string? Notes);
|
||||
|
||||
/// <summary>A mandate with the name of its debtor.</summary>
|
||||
/// <param name="Mandate">The mandate.</param>
|
||||
/// <param name="PartyCode">The code of the debtor.</param>
|
||||
/// <param name="PartyName">The name of the debtor.</param>
|
||||
public sealed record MandateRow(SddMandate Mandate, string? PartyCode, string PartyName);
|
||||
|
||||
/// <summary>The SEPA direct debit mandates of the customers (SPEC §11.8, mockup 055, ADR 0038).</summary>
|
||||
public sealed class MandateService
|
||||
{
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly AuditTrail _audit;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="audit">The history.</param>
|
||||
public MandateService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(audit);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
_audit = audit;
|
||||
}
|
||||
|
||||
/// <summary>The mandates, of a party or all.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="partyId">One party.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The mandates, by party and date.</returns>
|
||||
public async Task<IReadOnlyList<MandateRow>> ListAsync(Actor actor, string companyCode, long? partyId = null, 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 query = Query.For<SddMandate>();
|
||||
if (partyId is { } party)
|
||||
{
|
||||
query = query.Where(m => m.PartyId == party);
|
||||
}
|
||||
|
||||
var mandates = (await uow.Repository<SddMandate, long>().ListAsync(query.OrderByDescending(m => m.SignatureDate), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var parties = await TreasuryStore.PartiesAsync(uow, mandates.Select(m => m.PartyId), cancellationToken).ConfigureAwait(false);
|
||||
return [.. mandates.Select(m => new MandateRow(m, parties.GetValueOrDefault(m.PartyId)?.Code, parties.GetValueOrDefault(m.PartyId)?.Name ?? string.Empty))
|
||||
.OrderBy(r => r.PartyName, StringComparer.CurrentCultureIgnoreCase)];
|
||||
}
|
||||
|
||||
/// <summary>Writes a mandate.</summary>
|
||||
/// <param name="actor">Who writes.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="input">The mandate.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The mandate.</returns>
|
||||
public async Task<SddMandate> SaveAsync(Actor actor, string companyCode, MandateInput input, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
ArgumentNullException.ThrowIfNull(input);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleWrite, cancellationToken).ConfigureAwait(false);
|
||||
var reference = (input.Reference ?? string.Empty).Trim();
|
||||
var iban = IbanValidator.Normalize(input.Iban);
|
||||
var errors = new List<string>();
|
||||
if (input.PartyId <= 0)
|
||||
{
|
||||
errors.Add("PartyId:" + TreasuryErrors.PartyRequired);
|
||||
}
|
||||
|
||||
if (reference.Length == 0 || reference.Length > 35)
|
||||
{
|
||||
errors.Add("Reference:" + TreasuryErrors.MandateReference);
|
||||
}
|
||||
|
||||
if (!IbanValidator.IsValid(iban))
|
||||
{
|
||||
errors.Add("Iban:" + TreasuryErrors.IbanInvalid);
|
||||
}
|
||||
|
||||
if (errors.Count > 0)
|
||||
{
|
||||
throw new ValidationFailedException(errors);
|
||||
}
|
||||
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var repository = uow.Repository<SddMandate, long>();
|
||||
var same = await repository.FindAsync(Query.For<SddMandate>().Where(m => m.Reference == reference), cancellationToken).ConfigureAwait(false);
|
||||
if (same is not null && same.Id != input.Id)
|
||||
{
|
||||
throw new ValidationFailedException(["Reference:" + TreasuryErrors.MandateDuplicate]);
|
||||
}
|
||||
|
||||
var mandate = input.Id is { } id
|
||||
? await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound)
|
||||
: new SddMandate();
|
||||
var before = input.Id is null ? null : Copy(mandate);
|
||||
mandate.PartyId = input.PartyId;
|
||||
mandate.Reference = reference;
|
||||
mandate.SignatureDate = input.SignatureDate;
|
||||
mandate.Scheme = input.Scheme;
|
||||
mandate.Iban = iban;
|
||||
mandate.Bic = LedgerStore.Trim(string.IsNullOrWhiteSpace(input.Bic) ? null : input.Bic.Trim().ToUpperInvariant(), 11);
|
||||
mandate.OneOff = input.OneOff;
|
||||
mandate.Notes = LedgerStore.Trim(string.IsNullOrWhiteSpace(input.Notes) ? null : input.Notes.Trim(), 200);
|
||||
if (input.Id is null)
|
||||
{
|
||||
mandate.Id = await repository.InsertAsync(mandate, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync<SddMandate>(uow, AuditAction.Insert, mandate.Id, null, mandate, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await repository.UpdateAsync(mandate, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Update, mandate.Id, before, mandate, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return mandate;
|
||||
}
|
||||
|
||||
/// <summary>Revokes a mandate or takes the revocation back.</summary>
|
||||
/// <param name="actor">Who does it.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The mandate.</param>
|
||||
/// <param name="revoked">Revoked or not.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task RevokeAsync(Actor actor, string companyCode, long id, bool revoked, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
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 mandate = await uow.Repository<SddMandate, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound);
|
||||
var before = Copy(mandate);
|
||||
mandate.Revoked = revoked;
|
||||
await uow.Repository<SddMandate, long>().UpdateAsync(mandate, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Update, mandate.Id, before, mandate, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Deletes a mandate never used in a remittance.</summary>
|
||||
/// <param name="actor">Who does it.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The mandate.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
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 mandate = await uow.Repository<SddMandate, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound);
|
||||
if (await uow.Repository<RemittanceLine, long>().CountAsync(Query.For<RemittanceLine>().Where(l => l.MandateId == id), cancellationToken).ConfigureAwait(false) > 0)
|
||||
{
|
||||
throw new ValidationFailedException(["Id:" + TreasuryErrors.MandateUsed]);
|
||||
}
|
||||
|
||||
await uow.Repository<SddMandate, long>().DeleteAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync<SddMandate>(uow, AuditAction.Delete, id, mandate, null, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static SddMandate Copy(SddMandate m) => new()
|
||||
{
|
||||
Id = m.Id,
|
||||
PartyId = m.PartyId,
|
||||
Reference = m.Reference,
|
||||
SignatureDate = m.SignatureDate,
|
||||
Scheme = m.Scheme,
|
||||
Iban = m.Iban,
|
||||
Bic = m.Bic,
|
||||
OneOff = m.OneOff,
|
||||
Revoked = m.Revoked,
|
||||
Notes = m.Notes,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,841 @@
|
||||
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.Core.Validation;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Application.Treasury;
|
||||
|
||||
/// <summary>An item that can go in a remittance, with what is missing for the file.</summary>
|
||||
/// <param name="Row">The item.</param>
|
||||
/// <param name="Iban">The IBAN of the customer or supplier (of the mandate for direct debits).</param>
|
||||
/// <param name="Mandate">The mandate of a direct debit.</param>
|
||||
/// <param name="Problems">The error codes that keep it out of the file.</param>
|
||||
public sealed record RemittanceCandidate(ScheduleRow Row, string? Iban, SddMandate? Mandate, IReadOnlyList<string> Problems)
|
||||
{
|
||||
/// <summary>Ready for the file.</summary>
|
||||
public bool Ready => Problems.Count == 0;
|
||||
}
|
||||
|
||||
/// <summary>A new remittance.</summary>
|
||||
/// <param name="Kind">RiBa, direct debits or credit transfers.</param>
|
||||
/// <param name="BankAccountId">The bank of the company.</param>
|
||||
/// <param name="PresentationDate">The day it goes to the bank.</param>
|
||||
/// <param name="DueUntil">The last due date of its items.</param>
|
||||
/// <param name="Advance">Advanced subject to collection (salvo buon fine).</param>
|
||||
/// <param name="Notes">Notes.</param>
|
||||
/// <param name="OpenItemIds">The items.</param>
|
||||
public sealed record RemittanceInput(RemittanceKind Kind, long BankAccountId, DateOnly PresentationDate, DateOnly DueUntil, bool Advance, string? Notes, IReadOnlyList<long> OpenItemIds);
|
||||
|
||||
/// <summary>A remittance with its bank.</summary>
|
||||
/// <param name="Remittance">The remittance.</param>
|
||||
/// <param name="Bank">The bank (code and name).</param>
|
||||
public sealed record RemittanceRow(Remittance Remittance, string Bank);
|
||||
|
||||
/// <summary>A line of a remittance with its item and party.</summary>
|
||||
/// <param name="Line">The line.</param>
|
||||
/// <param name="Item">The item.</param>
|
||||
/// <param name="PartyName">The party.</param>
|
||||
/// <param name="Mandate">The reference of the mandate.</param>
|
||||
public sealed record RemittanceLineRow(RemittanceLine Line, OpenItem? Item, string PartyName, string? Mandate);
|
||||
|
||||
/// <summary>
|
||||
/// The remittances (distinte, SPEC §11.8, mockup 055, ADR 0038): RiBa in the CBI file of the pack, SEPA direct
|
||||
/// debits (<c>pain.008</c>) with their mandates, SEPA credit transfers to suppliers (<c>pain.001</c>). A remittance is
|
||||
/// drafted from the items due, its file generated, then presented (the effects move to the bills account, or the
|
||||
/// transfers pay the suppliers), credited at maturity, with the unpaid effects reopened with their fees.
|
||||
/// </summary>
|
||||
public sealed class RemittanceService
|
||||
{
|
||||
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 RemittanceService(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 direction of the items of a kind of remittance.</summary>
|
||||
/// <param name="kind">The kind.</param>
|
||||
/// <returns>Payables for credit transfers, receivables otherwise.</returns>
|
||||
public static OpenItemDirection DirectionOf(RemittanceKind kind) =>
|
||||
kind == RemittanceKind.SepaCreditTransfer ? OpenItemDirection.Payable : OpenItemDirection.Receivable;
|
||||
|
||||
/// <summary>The remittances of a year.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="year">The year.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The remittances, latest first.</returns>
|
||||
public async Task<IReadOnlyList<RemittanceRow>> ListAsync(Actor actor, string companyCode, int year, 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 list = (await uow.Repository<Remittance, long>().ListAsync(
|
||||
Query.For<Remittance>().Where(r => r.Year == year).OrderByDescending(r => r.Number), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var banks = (await uow.Repository<BankAccount, long>().ListAsync(Query.For<BankAccount>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(b => b.Id);
|
||||
return [.. list.Select(r => new RemittanceRow(r, banks.TryGetValue(r.BankAccountId, out var b) ? b.Code + " · " + (b.BankName ?? b.Description) : string.Empty))];
|
||||
}
|
||||
|
||||
/// <summary>A remittance with its lines.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The remittance.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The remittance and its lines, or <see langword="null"/>.</returns>
|
||||
public async Task<(RemittanceRow Row, IReadOnlyList<RemittanceLineRow> Lines)?> GetAsync(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<Remittance, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } remittance)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var bank = await uow.Repository<BankAccount, long>().GetAsync(remittance.BankAccountId, cancellationToken).ConfigureAwait(false);
|
||||
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 parties = await TreasuryStore.PartiesAsync(uow, lines.Select(l => l.PartyId), cancellationToken).ConfigureAwait(false);
|
||||
var mandates = (await uow.Repository<SddMandate, long>().ListAsync(Query.For<SddMandate>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(m => m.Id);
|
||||
return (
|
||||
new RemittanceRow(remittance, bank is null ? string.Empty : bank.Code + " · " + (bank.BankName ?? bank.Description)),
|
||||
[.. lines.Select(l => new RemittanceLineRow(
|
||||
l, items.GetValueOrDefault(l.OpenItemId), parties.GetValueOrDefault(l.PartyId)?.Name ?? string.Empty,
|
||||
l.MandateId is { } m ? mandates.GetValueOrDefault(m)?.Reference : null))]);
|
||||
}
|
||||
|
||||
/// <summary>The items that can go in a remittance of a kind, due up to a day.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="kind">The kind.</param>
|
||||
/// <param name="dueUntil">The last due date.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The candidates, by due date.</returns>
|
||||
public async Task<IReadOnlyList<RemittanceCandidate>> CandidatesAsync(
|
||||
Actor actor, string companyCode, RemittanceKind kind, DateOnly dueUntil, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleRead, 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);
|
||||
var direction = DirectionOf(kind);
|
||||
var items = (await uow.Repository<OpenItem, long>().ListAsync(
|
||||
Query.For<OpenItem>().Where(o => o.Direction == direction && !o.Closed && !o.Disputed && o.DueDate <= dueUntil
|
||||
&& (o.Status == OpenItemStatus.Open || o.Status == OpenItemStatus.Partial || o.Status == OpenItemStatus.Unpaid)).OrderBy(o => o.DueDate).OrderBy(o => o.Id),
|
||||
cancellationToken).ConfigureAwait(false)).Items;
|
||||
var methods = (await uow.Repository<PaymentMethod, long>().ListAsync(Query.For<PaymentMethod>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(m => m.Id);
|
||||
var kinds = pack.GetFeature<IRemittanceMethods>();
|
||||
var chosen = items.Where(i => i.Residual > 0m && Fits(kind, i.PaymentMethodId is { } m && methods.TryGetValue(m, out var method) ? kinds?.KindOf(method.EInvoiceCode) : null)).ToList();
|
||||
var rows = await ScheduleService.RowsAsync(uow, chosen, TreasuryStore.Today(_clock), cancellationToken).ConfigureAwait(false);
|
||||
var context = await PartyBanksAsync(uow, chosen.Select(i => i.PartyId), cancellationToken).ConfigureAwait(false);
|
||||
return [.. rows.Select(r => Candidate(kind, r, context))];
|
||||
}
|
||||
|
||||
/// <summary>Drafts a remittance with items; they are reserved for it.</summary>
|
||||
/// <param name="actor">Who drafts it.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="input">The remittance.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The remittance.</returns>
|
||||
public async Task<Remittance> CreateAsync(Actor actor, string companyCode, RemittanceInput input, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
ArgumentNullException.ThrowIfNull(input);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleWrite, cancellationToken).ConfigureAwait(false);
|
||||
if (input.OpenItemIds.Count == 0)
|
||||
{
|
||||
throw new ValidationFailedException(["OpenItemIds:" + TreasuryErrors.RemittanceEmpty]);
|
||||
}
|
||||
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
_ = await uow.Repository<BankAccount, long>().GetAsync(input.BankAccountId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ValidationFailedException(["BankAccountId:" + TreasuryErrors.NotFound]);
|
||||
var year = input.PresentationDate.Year;
|
||||
var number = (int)((await uow.QuerySingleAsync<long?>(SqlFragment.Of($"SELECT MAX(number) FROM remittances WHERE year = {year}"), cancellationToken).ConfigureAwait(false) ?? 0L) + 1L);
|
||||
var remittance = new Remittance
|
||||
{
|
||||
Year = year,
|
||||
Number = number,
|
||||
Kind = input.Kind,
|
||||
BankAccountId = input.BankAccountId,
|
||||
PresentationDate = input.PresentationDate,
|
||||
DueUntil = input.DueUntil,
|
||||
Advance = input.Advance && input.Kind != RemittanceKind.SepaCreditTransfer,
|
||||
Status = RemittanceStatus.Draft,
|
||||
Notes = LedgerStore.Trim(string.IsNullOrWhiteSpace(input.Notes) ? null : input.Notes.Trim(), 500),
|
||||
};
|
||||
remittance.Id = await uow.Repository<Remittance, long>().InsertAsync(remittance, cancellationToken).ConfigureAwait(false);
|
||||
var itemRepository = uow.Repository<OpenItem, long>();
|
||||
var direction = DirectionOf(input.Kind);
|
||||
var items = new List<OpenItem>();
|
||||
foreach (var id in input.OpenItemIds.Distinct())
|
||||
{
|
||||
var item = await itemRepository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new ValidationFailedException(["OpenItemIds:" + TreasuryErrors.NotFound]);
|
||||
if (item.Direction != direction || item.Closed || item.Residual <= 0m || item.Status == OpenItemStatus.InRemittance || item.Disputed)
|
||||
{
|
||||
throw new ValidationFailedException(["OpenItemIds:" + TreasuryErrors.RemittanceItem]);
|
||||
}
|
||||
|
||||
items.Add(item);
|
||||
}
|
||||
|
||||
var banks = await PartyBanksAsync(uow, items.Select(i => i.PartyId), cancellationToken).ConfigureAwait(false);
|
||||
var lines = uow.Repository<RemittanceLine, long>();
|
||||
foreach (var item in items)
|
||||
{
|
||||
var mandate = MandateOf(input.Kind, item.PartyId, banks);
|
||||
var line = new RemittanceLine
|
||||
{
|
||||
RemittanceId = remittance.Id,
|
||||
OpenItemId = item.Id,
|
||||
PartyId = item.PartyId,
|
||||
Amount = item.Residual,
|
||||
DueDate = item.DueDate,
|
||||
Iban = mandate?.Iban ?? banks.Accounts.GetValueOrDefault(item.PartyId)?.Iban,
|
||||
MandateId = mandate?.Id,
|
||||
Status = RemittanceLineStatus.Included,
|
||||
};
|
||||
line.Id = await lines.InsertAsync(line, cancellationToken).ConfigureAwait(false);
|
||||
line.EndToEndId = EndToEnd(remittance, line);
|
||||
await lines.UpdateAsync(line, cancellationToken).ConfigureAwait(false);
|
||||
item.RemittanceId = remittance.Id;
|
||||
item.Status = OpenItemStatus.InRemittance;
|
||||
await itemRepository.UpdateAsync(item, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
remittance.ItemCount = items.Count;
|
||||
remittance.TotalAmount = items.Sum(i => i.Residual);
|
||||
remittance.IsDemo = items.All(i => i.IsDemo);
|
||||
await uow.Repository<Remittance, long>().UpdateAsync(remittance, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync<Remittance>(uow, AuditAction.Insert, remittance.Id, null, remittance, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return remittance;
|
||||
}
|
||||
|
||||
/// <summary>Takes a line out of a remittance not presented.</summary>
|
||||
/// <param name="actor">Who does it.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="lineId">The line.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task RemoveLineAsync(Actor actor, string companyCode, long lineId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
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 line = await uow.Repository<RemittanceLine, long>().GetAsync(lineId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound);
|
||||
var remittance = await EditableAsync(uow, line.RemittanceId, cancellationToken).ConfigureAwait(false);
|
||||
await ReleaseAsync(uow, line, cancellationToken).ConfigureAwait(false);
|
||||
await uow.Repository<RemittanceLine, long>().DeleteAsync(line.Id, cancellationToken).ConfigureAwait(false);
|
||||
remittance.ItemCount--;
|
||||
remittance.TotalAmount -= line.Amount;
|
||||
remittance.Status = RemittanceStatus.Draft;
|
||||
await uow.Repository<Remittance, long>().UpdateAsync(remittance, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Deletes a remittance not presented; its items are free again.</summary>
|
||||
/// <param name="actor">Who does it.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The remittance.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
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 remittance = await EditableAsync(uow, id, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var line in await LinesAsync(uow, id, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await ReleaseAsync(uow, line, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await uow.Repository<Remittance, long>().DeleteAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync<Remittance>(uow, AuditAction.Delete, id, remittance, null, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Writes the file of a remittance for the bank (CBI for RiBa, XML for SEPA).</summary>
|
||||
/// <param name="actor">Who does it.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The remittance.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The file.</returns>
|
||||
public async Task<LedgerFile> FileAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleWrite, 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 remittance = await uow.Repository<Remittance, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound);
|
||||
var lines = (await LinesAsync(uow, id, cancellationToken).ConfigureAwait(false)).Where(l => l.Status != RemittanceLineStatus.Unpaid).ToList();
|
||||
if (lines.Count == 0)
|
||||
{
|
||||
throw new ValidationFailedException(["Lines:" + TreasuryErrors.RemittanceEmpty]);
|
||||
}
|
||||
|
||||
var bank = await uow.Repository<BankAccount, long>().GetAsync(remittance.BankAccountId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ValidationFailedException(["BankAccountId:" + TreasuryErrors.NotFound]);
|
||||
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
|
||||
var errors = new List<string>();
|
||||
if (!IbanValidator.IsValid(bank.Iban)
|
||||
|| (remittance.Kind == RemittanceKind.Riba && string.IsNullOrWhiteSpace(bank.SiaCode))
|
||||
|| (remittance.Kind is RemittanceKind.SddCore or RemittanceKind.SddB2b && string.IsNullOrWhiteSpace(bank.CreditorId)))
|
||||
{
|
||||
errors.Add("BankAccountId:" + TreasuryErrors.RemittanceBank);
|
||||
}
|
||||
|
||||
var parties = await TreasuryStore.PartiesAsync(uow, lines.Select(l => l.PartyId), cancellationToken).ConfigureAwait(false);
|
||||
var partyBanks = await PartyBanksAsync(uow, lines.Select(l => l.PartyId), 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 fileItems = new List<BankFileItem>();
|
||||
var number = 0;
|
||||
foreach (var line in lines)
|
||||
{
|
||||
var party = parties.GetValueOrDefault(line.PartyId);
|
||||
var mandate = line.MandateId is { } m ? partyBanks.Mandates.FirstOrDefault(x => x.Id == m) : null;
|
||||
if (remittance.Kind != RemittanceKind.Riba && !IbanValidator.IsValid(line.Iban))
|
||||
{
|
||||
errors.Add("Lines:" + TreasuryErrors.RemittanceIban);
|
||||
}
|
||||
|
||||
if (remittance.Kind == RemittanceKind.Riba && string.IsNullOrWhiteSpace(line.Iban) && partyBanks.Accounts.GetValueOrDefault(line.PartyId) is not { BankCode: not null, BranchCode: not null })
|
||||
{
|
||||
errors.Add("Lines:" + TreasuryErrors.RemittanceIban);
|
||||
}
|
||||
|
||||
if (remittance.Kind is RemittanceKind.SddCore or RemittanceKind.SddB2b && (mandate is null || mandate.Revoked))
|
||||
{
|
||||
errors.Add("Lines:" + TreasuryErrors.RemittanceMandate);
|
||||
}
|
||||
|
||||
var item = items.GetValueOrDefault(line.OpenItemId);
|
||||
var account = partyBanks.Accounts.GetValueOrDefault(line.PartyId);
|
||||
fileItems.Add(new BankFileItem(
|
||||
++number,
|
||||
party?.Code ?? line.PartyId.ToString(CultureInfo.InvariantCulture),
|
||||
party?.Name ?? string.Empty,
|
||||
party?.TaxCode ?? party?.VatNumber,
|
||||
party?.Address is null ? null : party.Address + (party.StreetNumber is null ? string.Empty : " " + party.StreetNumber),
|
||||
party?.PostalCode,
|
||||
party?.City,
|
||||
party?.Province,
|
||||
party?.CountryCode ?? "IT",
|
||||
line.Iban ?? account?.Iban,
|
||||
mandate?.Bic ?? account?.Bic,
|
||||
account?.BankName,
|
||||
line.Amount,
|
||||
line.DueDate,
|
||||
item is null ? remittance.DisplayNumber : TreasuryStore.ItemText(item),
|
||||
line.EndToEndId ?? EndToEnd(remittance, line),
|
||||
mandate?.Reference,
|
||||
mandate?.SignatureDate,
|
||||
mandate is null ? SddSequence.Recurrent : mandate.OneOff ? SddSequence.OneOff : mandate.LastCollectionDate is null ? SddSequence.First : SddSequence.Recurrent));
|
||||
}
|
||||
|
||||
if (errors.Count > 0)
|
||||
{
|
||||
throw new ValidationFailedException([.. errors.Distinct(StringComparer.Ordinal)]);
|
||||
}
|
||||
|
||||
var messageId = LedgerStore.Trim("KH" + remittance.Year.ToString(CultureInfo.InvariantCulture) + remittance.Number.ToString("000", CultureInfo.InvariantCulture)
|
||||
+ "T" + _clock.GetUtcNow().ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture), 35)!;
|
||||
var fileRemittance = new BankFileRemittance(
|
||||
remittance.Kind,
|
||||
messageId,
|
||||
_clock.GetLocalNow().DateTime,
|
||||
remittance.Kind == RemittanceKind.SepaCreditTransfer ? remittance.PresentationDate : lines.Min(l => l.DueDate),
|
||||
new BankFileCompany(
|
||||
profile?.LegalName ?? string.Empty, profile?.TaxCode ?? profile?.VatNumber, profile?.Address, profile?.PostalCode, profile?.City, profile?.ProvinceCode,
|
||||
profile?.AddressCountry ?? profile?.Country ?? "IT", bank.Iban ?? string.Empty, bank.Bic, bank.SiaCode, bank.CucCode, bank.CreditorId),
|
||||
fileItems);
|
||||
BankFile file;
|
||||
try
|
||||
{
|
||||
file = remittance.Kind switch
|
||||
{
|
||||
RemittanceKind.SepaCreditTransfer => SepaXmlWriter.CreditTransfer(fileRemittance),
|
||||
RemittanceKind.SddCore or RemittanceKind.SddB2b => SepaXmlWriter.DirectDebit(fileRemittance),
|
||||
_ => pack.GetFeature<IRemittanceFileWriter>() is { } writer && writer.Supports(remittance.Kind)
|
||||
? writer.Write(fileRemittance)
|
||||
: throw new ValidationFailedException(["Kind:" + TreasuryErrors.RemittanceFormat]),
|
||||
};
|
||||
}
|
||||
catch (BankFileException)
|
||||
{
|
||||
throw new ValidationFailedException(["Lines:" + TreasuryErrors.RemittanceFormat]);
|
||||
}
|
||||
|
||||
remittance.MessageId = messageId;
|
||||
remittance.FileName = LedgerStore.Trim(file.FileName, 100);
|
||||
if (remittance.Status == RemittanceStatus.Draft)
|
||||
{
|
||||
remittance.Status = RemittanceStatus.Generated;
|
||||
}
|
||||
|
||||
await uow.Repository<Remittance, long>().UpdateAsync(remittance, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return new LedgerFile(file.FileName, file.ContentType, file.Content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Presents a remittance to the bank: RiBa and direct debits move the receivables to the bills account (and the
|
||||
/// advance to the bank when advanced); credit transfers pay the suppliers and close the remittance.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who does it.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The remittance.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The remittance.</returns>
|
||||
public async Task<Remittance> PresentAsync(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);
|
||||
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 remittance = await EditableAsync(uow, id, cancellationToken).ConfigureAwait(false);
|
||||
var before = Copy(remittance);
|
||||
var lines = await LinesAsync(uow, id, cancellationToken).ConfigureAwait(false);
|
||||
if (lines.Count == 0)
|
||||
{
|
||||
throw new ValidationFailedException(["Lines:" + TreasuryErrors.RemittanceEmpty]);
|
||||
}
|
||||
|
||||
var itemRepository = uow.Repository<OpenItem, long>();
|
||||
var lineRepository = uow.Repository<RemittanceLine, long>();
|
||||
if (remittance.Kind == RemittanceKind.SepaCreditTransfer)
|
||||
{
|
||||
foreach (var group in lines.GroupBy(l => l.PartyId))
|
||||
{
|
||||
foreach (var line in group)
|
||||
{
|
||||
var item = await itemRepository.GetAsync(line.OpenItemId, cancellationToken).ConfigureAwait(false);
|
||||
if (item is not null)
|
||||
{
|
||||
// The transfer pays the item: it leaves the remittance state for the payment to settle it.
|
||||
item.Status = item.PaidAmount != 0m ? OpenItemStatus.Partial : OpenItemStatus.Open;
|
||||
await itemRepository.UpdateAsync(item, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
var payment = await PaymentService.RegisterAsync(
|
||||
uow,
|
||||
pack,
|
||||
new PaymentInput(PaymentDirection.Disbursement, group.Key, remittance.PresentationDate, null, remittance.BankAccountId, 0m, "Distinta " + remittance.DisplayNumber, null,
|
||||
[.. group.Select(l => new PaymentLineInput(l.OpenItemId, l.Amount))]),
|
||||
PaymentOrigin.Remittance,
|
||||
remittance.Id,
|
||||
null,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
foreach (var line in group)
|
||||
{
|
||||
line.Status = RemittanceLineStatus.Paid;
|
||||
line.PaymentId = payment.Id;
|
||||
await lineRepository.UpdateAsync(line, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
remittance.Status = RemittanceStatus.Closed;
|
||||
remittance.CreditedOn = remittance.PresentationDate;
|
||||
}
|
||||
else
|
||||
{
|
||||
var ledger = pack.GetFeature<ILedgerTemplate>();
|
||||
var template = await LedgerStore.TemplateAsync(uow, "DIST", cancellationToken).ConfigureAwait(false);
|
||||
var bills = await TreasuryStore.RoleAccountAsync(uow, template?.Lines, PostingRole.BillsForCollection, ledger, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ValidationFailedException(["Ledger:" + TreasuryErrors.AccountMissing]);
|
||||
var posted = new List<PaymentPostedLine>();
|
||||
foreach (var line in lines)
|
||||
{
|
||||
var item = await itemRepository.GetAsync(line.OpenItemId, cancellationToken).ConfigureAwait(false) ?? throw new ValidationFailedException(["Lines:" + TreasuryErrors.NotFound]);
|
||||
posted.Add(new PaymentPostedLine(item.AccountId, item.PartyId, item.Id, TreasuryStore.ItemText(item), 0m, line.Amount));
|
||||
item.PaidAmount += line.Amount;
|
||||
item.Status = OpenItemStatus.InRemittance;
|
||||
item.Closed = false;
|
||||
await itemRepository.UpdateAsync(item, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var total = lines.Sum(l => l.Amount);
|
||||
posted.Insert(0, new PaymentPostedLine(bills, null, null, "Effetti all'incasso distinta " + remittance.DisplayNumber, total, 0m));
|
||||
var entry = await TreasuryStore.PostAsync(uow, "DIST", remittance.PresentationDate, "Presentazione distinta " + remittance.DisplayNumber, null, posted, remittance.IsDemo, cancellationToken).ConfigureAwait(false);
|
||||
remittance.GlEntryId = entry.Id;
|
||||
if (remittance.Advance)
|
||||
{
|
||||
var advance = await LedgerStore.TemplateAsync(uow, "ANT", cancellationToken).ConfigureAwait(false);
|
||||
var bank = await TreasuryStore.BankAsync(uow, remittance.BankAccountId, cancellationToken).ConfigureAwait(false);
|
||||
var money = await TreasuryStore.MoneyAccountAsync(uow, bank, false, advance?.Lines, ledger, cancellationToken).ConfigureAwait(false);
|
||||
var advances = await TreasuryStore.RoleAccountAsync(uow, advance?.Lines, PostingRole.BankAdvances, ledger, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ValidationFailedException(["Ledger:" + TreasuryErrors.AccountMissing]);
|
||||
var text = "Anticipo s.b.f. distinta " + remittance.DisplayNumber;
|
||||
var credit = await TreasuryStore.PostAsync(
|
||||
uow, "ANT", remittance.PresentationDate, text, null,
|
||||
[new PaymentPostedLine(money, null, null, text, total, 0m), new PaymentPostedLine(advances, null, null, text, 0m, total)], remittance.IsDemo, cancellationToken).ConfigureAwait(false);
|
||||
remittance.CreditEntryId = credit.Id;
|
||||
}
|
||||
|
||||
remittance.Status = RemittanceStatus.Presented;
|
||||
await MarkMandatesAsync(uow, lines, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await uow.Repository<Remittance, long>().UpdateAsync(remittance, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Update, remittance.Id, before, remittance, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return remittance;
|
||||
}
|
||||
|
||||
/// <summary>Records the credit at maturity of a presented remittance: the effects not unpaid are collected.</summary>
|
||||
/// <param name="actor">Who does it.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The remittance.</param>
|
||||
/// <param name="creditedOn">The day of the credit.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The remittance.</returns>
|
||||
public async Task<Remittance> CreditAsync(Actor actor, string companyCode, long id, DateOnly creditedOn, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
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 remittance = await uow.Repository<Remittance, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound);
|
||||
if (remittance.Status != RemittanceStatus.Presented)
|
||||
{
|
||||
throw new ValidationFailedException(["Status:" + TreasuryErrors.RemittanceStatus]);
|
||||
}
|
||||
|
||||
var before = Copy(remittance);
|
||||
await CreditInsideAsync(uow, pack, remittance, creditedOn, cancellationToken).ConfigureAwait(false);
|
||||
await uow.Repository<Remittance, long>().UpdateAsync(remittance, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Update, remittance.Id, before, remittance, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return remittance;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records an unpaid effect or direct debit (insoluto): the receivable reopens as unpaid, the bank takes the money
|
||||
/// back (or the bills account is closed before the credit) and the fees become a new item of the customer.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who does it.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="lineId">The line of the remittance.</param>
|
||||
/// <param name="date">The day the bank returned it.</param>
|
||||
/// <param name="fees">The fees charged by the bank, debited to the customer.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The line.</returns>
|
||||
public async Task<RemittanceLine> UnpaidAsync(Actor actor, string companyCode, long lineId, DateOnly date, decimal fees, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
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 line = await uow.Repository<RemittanceLine, long>().GetAsync(lineId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound);
|
||||
var remittance = await uow.Repository<Remittance, long>().GetAsync(line.RemittanceId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound);
|
||||
if (remittance.Kind == RemittanceKind.SepaCreditTransfer || remittance.Status is not (RemittanceStatus.Presented or RemittanceStatus.Closed) || line.Status == RemittanceLineStatus.Unpaid)
|
||||
{
|
||||
throw new ValidationFailedException(["Status:" + TreasuryErrors.RemittanceStatus]);
|
||||
}
|
||||
|
||||
await UnpaidInsideAsync(uow, pack, line, date, fees, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Update, line.Id, null, line, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return line;
|
||||
}
|
||||
|
||||
/// <summary>Credits a presented remittance inside a transaction (also from the bank reconciliation).</summary>
|
||||
internal static async Task CreditInsideAsync(IUnitOfWork uow, IFiscalPack pack, Remittance remittance, DateOnly creditedOn, CancellationToken cancellationToken)
|
||||
{
|
||||
if (remittance.Status != RemittanceStatus.Presented)
|
||||
{
|
||||
throw new ValidationFailedException(["Status:" + TreasuryErrors.RemittanceStatus]);
|
||||
}
|
||||
|
||||
var lines = (await LinesAsync(uow, remittance.Id, cancellationToken).ConfigureAwait(false)).Where(l => l.Status == RemittanceLineStatus.Included).ToList();
|
||||
var total = lines.Sum(l => l.Amount);
|
||||
if (total != 0m)
|
||||
{
|
||||
var ledger = pack.GetFeature<ILedgerTemplate>();
|
||||
var template = await LedgerStore.TemplateAsync(uow, "ACCR", cancellationToken).ConfigureAwait(false);
|
||||
var bills = await TreasuryStore.RoleAccountAsync(uow, template?.Lines, PostingRole.BillsForCollection, ledger, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ValidationFailedException(["Ledger:" + TreasuryErrors.AccountMissing]);
|
||||
var debit = remittance.Advance
|
||||
? await TreasuryStore.RoleAccountAsync(uow, template?.Lines, PostingRole.BankAdvances, ledger, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ValidationFailedException(["Ledger:" + TreasuryErrors.AccountMissing])
|
||||
: await TreasuryStore.MoneyAccountAsync(
|
||||
uow, await TreasuryStore.BankAsync(uow, remittance.BankAccountId, cancellationToken).ConfigureAwait(false), false, template?.Lines, ledger, cancellationToken).ConfigureAwait(false);
|
||||
var text = "Accredito distinta " + remittance.DisplayNumber;
|
||||
var entry = await TreasuryStore.PostAsync(
|
||||
uow, "ACCR", creditedOn, text, null, [new PaymentPostedLine(debit, null, null, text, total, 0m), new PaymentPostedLine(bills, null, null, text, 0m, total)],
|
||||
remittance.IsDemo, cancellationToken).ConfigureAwait(false);
|
||||
remittance.CreditEntryId ??= entry.Id;
|
||||
if (remittance.Advance)
|
||||
{
|
||||
// The advance entry stays the credit entry; the closing of the bills is kept in the notes of the history.
|
||||
remittance.Notes = LedgerStore.Trim((remittance.Notes is null ? string.Empty : remittance.Notes + " · ") + "Chiusura effetti " + entry.EntryNumber, 500);
|
||||
}
|
||||
else
|
||||
{
|
||||
remittance.CreditEntryId = entry.Id;
|
||||
}
|
||||
}
|
||||
|
||||
var itemRepository = uow.Repository<OpenItem, long>();
|
||||
foreach (var line in lines)
|
||||
{
|
||||
if (await itemRepository.GetAsync(line.OpenItemId, cancellationToken).ConfigureAwait(false) is { } item)
|
||||
{
|
||||
item.Status = item.Residual == 0m ? OpenItemStatus.Closed : OpenItemStatus.Partial;
|
||||
item.Closed = item.Residual == 0m;
|
||||
await itemRepository.UpdateAsync(item, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
line.Status = RemittanceLineStatus.Paid;
|
||||
await uow.Repository<RemittanceLine, long>().UpdateAsync(line, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
remittance.Status = RemittanceStatus.Closed;
|
||||
remittance.CreditedOn = creditedOn;
|
||||
await uow.Repository<Remittance, long>().UpdateAsync(remittance, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Records an unpaid effect inside a transaction (also from the bank reconciliation).</summary>
|
||||
internal static async Task UnpaidInsideAsync(IUnitOfWork uow, IFiscalPack pack, RemittanceLine line, DateOnly date, decimal fees, CancellationToken cancellationToken)
|
||||
{
|
||||
if (fees < 0m)
|
||||
{
|
||||
throw new ValidationFailedException(["Fees:" + TreasuryErrors.AmountRequired]);
|
||||
}
|
||||
|
||||
var remittance = await uow.Repository<Remittance, long>().GetAsync(line.RemittanceId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound);
|
||||
if (remittance.Kind == RemittanceKind.SepaCreditTransfer || remittance.Status is not (RemittanceStatus.Presented or RemittanceStatus.Closed) || line.Status == RemittanceLineStatus.Unpaid)
|
||||
{
|
||||
throw new ValidationFailedException(["Status:" + TreasuryErrors.RemittanceStatus]);
|
||||
}
|
||||
|
||||
var item = await uow.Repository<OpenItem, long>().GetAsync(line.OpenItemId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound);
|
||||
var ledger = pack.GetFeature<ILedgerTemplate>();
|
||||
var template = await LedgerStore.TemplateAsync(uow, "INS", cancellationToken).ConfigureAwait(false);
|
||||
var bank = await TreasuryStore.BankAsync(uow, remittance.BankAccountId, cancellationToken).ConfigureAwait(false);
|
||||
var money = await TreasuryStore.MoneyAccountAsync(uow, bank, false, template?.Lines, ledger, cancellationToken).ConfigureAwait(false);
|
||||
var text = "Insoluto " + TreasuryStore.ItemText(item);
|
||||
var posted = new List<PaymentPostedLine> { new(item.AccountId, item.PartyId, item.Id, text, line.Amount, 0m) };
|
||||
if (line.Status == RemittanceLineStatus.Paid)
|
||||
{
|
||||
// Already credited: the bank takes the money back.
|
||||
posted.Add(new PaymentPostedLine(money, null, null, text, 0m, line.Amount));
|
||||
}
|
||||
else
|
||||
{
|
||||
var bills = await TreasuryStore.RoleAccountAsync(uow, template?.Lines, PostingRole.BillsForCollection, ledger, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ValidationFailedException(["Ledger:" + TreasuryErrors.AccountMissing]);
|
||||
posted.Add(new PaymentPostedLine(bills, null, null, text, 0m, line.Amount));
|
||||
if (remittance.Advance)
|
||||
{
|
||||
var advances = await TreasuryStore.RoleAccountAsync(uow, template?.Lines, PostingRole.BankAdvances, ledger, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ValidationFailedException(["Ledger:" + TreasuryErrors.AccountMissing]);
|
||||
posted.Add(new PaymentPostedLine(advances, null, null, "Rientro anticipo " + text, line.Amount, 0m));
|
||||
posted.Add(new PaymentPostedLine(money, null, null, "Rientro anticipo " + text, 0m, line.Amount));
|
||||
}
|
||||
}
|
||||
|
||||
if (fees > 0m)
|
||||
{
|
||||
posted.Add(new PaymentPostedLine(item.AccountId, item.PartyId, null, "Spese insoluto", fees, 0m));
|
||||
posted.Add(new PaymentPostedLine(money, null, null, "Spese insoluto", 0m, fees));
|
||||
}
|
||||
|
||||
var entry = await TreasuryStore.PostAsync(uow, "INS", date, text, item.PartyId, posted, item.IsDemo, cancellationToken).ConfigureAwait(false);
|
||||
item.PaidAmount -= line.Amount;
|
||||
item.RemittanceId = null;
|
||||
item.UnpaidCount++;
|
||||
item.Status = OpenItemStatus.Unpaid;
|
||||
item.Status = OpenItemStates.Of(item);
|
||||
item.Closed = false;
|
||||
await uow.Repository<OpenItem, long>().UpdateAsync(item, cancellationToken).ConfigureAwait(false);
|
||||
if (fees > 0m)
|
||||
{
|
||||
await uow.Repository<OpenItem, long>().InsertAsync(new OpenItem
|
||||
{
|
||||
Direction = item.Direction,
|
||||
PartyId = item.PartyId,
|
||||
AccountId = item.AccountId,
|
||||
EntryId = entry.Id,
|
||||
SourceFamily = item.SourceFamily,
|
||||
SourceDocumentId = item.SourceDocumentId,
|
||||
DocumentNumber = item.DocumentNumber,
|
||||
DocumentDate = item.DocumentDate,
|
||||
Installment = item.Installment,
|
||||
DueDate = date,
|
||||
Amount = fees,
|
||||
PaymentMethodId = item.PaymentMethodId,
|
||||
Status = OpenItemStatus.Open,
|
||||
ParentId = item.Id,
|
||||
Notes = "Spese insoluto",
|
||||
IsDemo = item.IsDemo,
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
line.Status = RemittanceLineStatus.Unpaid;
|
||||
line.UnpaidOn = date;
|
||||
line.UnpaidFees = fees;
|
||||
line.UnpaidEntryId = entry.Id;
|
||||
await uow.Repository<RemittanceLine, long>().UpdateAsync(line, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal static async Task<IReadOnlyList<RemittanceLine>> LinesAsync(IUnitOfWork uow, long remittanceId, CancellationToken cancellationToken) =>
|
||||
(await uow.Repository<RemittanceLine, long>().ListAsync(Query.For<RemittanceLine>().Where(l => l.RemittanceId == remittanceId).OrderBy(l => l.DueDate).OrderBy(l => l.Id), cancellationToken)
|
||||
.ConfigureAwait(false)).Items;
|
||||
|
||||
private static bool Fits(RemittanceKind kind, RemittanceKind? methodKind) => kind switch
|
||||
{
|
||||
RemittanceKind.SepaCreditTransfer => methodKind is null or RemittanceKind.SepaCreditTransfer,
|
||||
_ => methodKind == kind,
|
||||
};
|
||||
|
||||
private static RemittanceCandidate Candidate(RemittanceKind kind, ScheduleRow row, PartyBanks banks)
|
||||
{
|
||||
var problems = new List<string>();
|
||||
var mandate = MandateOf(kind, row.Item.PartyId, banks);
|
||||
var account = banks.Accounts.GetValueOrDefault(row.Item.PartyId);
|
||||
var iban = mandate?.Iban ?? account?.Iban;
|
||||
if (kind is RemittanceKind.SddCore or RemittanceKind.SddB2b)
|
||||
{
|
||||
if (mandate is null)
|
||||
{
|
||||
problems.Add(TreasuryErrors.RemittanceMandate);
|
||||
}
|
||||
}
|
||||
else if (kind == RemittanceKind.Riba)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(iban) && account is not { BankCode: not null, BranchCode: not null })
|
||||
{
|
||||
problems.Add(TreasuryErrors.RemittanceIban);
|
||||
}
|
||||
}
|
||||
else if (!IbanValidator.IsValid(iban))
|
||||
{
|
||||
problems.Add(TreasuryErrors.RemittanceIban);
|
||||
}
|
||||
|
||||
return new RemittanceCandidate(row, iban, mandate, problems);
|
||||
}
|
||||
|
||||
private static SddMandate? MandateOf(RemittanceKind kind, long partyId, PartyBanks banks)
|
||||
{
|
||||
if (kind is not (RemittanceKind.SddCore or RemittanceKind.SddB2b))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var scheme = kind == RemittanceKind.SddB2b ? SddScheme.B2b : SddScheme.Core;
|
||||
return banks.Mandates.Where(m => m.PartyId == partyId && !m.Revoked && m.Scheme == scheme && !(m.OneOff && m.LastCollectionDate is not null))
|
||||
.OrderByDescending(m => m.SignatureDate).FirstOrDefault();
|
||||
}
|
||||
|
||||
private static async Task<PartyBanks> PartyBanksAsync(IUnitOfWork uow, IEnumerable<long> partyIds, CancellationToken cancellationToken)
|
||||
{
|
||||
var ids = partyIds.Distinct().ToList();
|
||||
var accounts = new Dictionary<long, PartyBankAccount>();
|
||||
var mandates = new List<SddMandate>();
|
||||
foreach (var chunk in ids.Chunk(500))
|
||||
{
|
||||
var list = chunk.ToList();
|
||||
foreach (var account in (await uow.Repository<PartyBankAccount, long>().ListAsync(
|
||||
Query.For<PartyBankAccount>().Where(a => list.Contains(a.PartyId)).OrderByDescending(a => a.IsDefault).OrderBy(a => a.Id), cancellationToken).ConfigureAwait(false)).Items)
|
||||
{
|
||||
accounts.TryAdd(account.PartyId, account);
|
||||
}
|
||||
|
||||
mandates.AddRange((await uow.Repository<SddMandate, long>().ListAsync(Query.For<SddMandate>().Where(m => list.Contains(m.PartyId)), cancellationToken).ConfigureAwait(false)).Items);
|
||||
}
|
||||
|
||||
return new PartyBanks(accounts, mandates);
|
||||
}
|
||||
|
||||
private static async Task<Remittance> EditableAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
|
||||
{
|
||||
var remittance = await uow.Repository<Remittance, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound);
|
||||
if (remittance.Status is not (RemittanceStatus.Draft or RemittanceStatus.Generated))
|
||||
{
|
||||
throw new ValidationFailedException(["Status:" + TreasuryErrors.RemittanceStatus]);
|
||||
}
|
||||
|
||||
return remittance;
|
||||
}
|
||||
|
||||
private static async Task ReleaseAsync(IUnitOfWork uow, RemittanceLine line, CancellationToken cancellationToken)
|
||||
{
|
||||
if (await uow.Repository<OpenItem, long>().GetAsync(line.OpenItemId, cancellationToken).ConfigureAwait(false) is not { } item || item.RemittanceId != line.RemittanceId)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
item.RemittanceId = null;
|
||||
item.Status = OpenItemStatus.Open;
|
||||
item.Status = OpenItemStates.Of(item);
|
||||
item.Closed = item.Status == OpenItemStatus.Closed;
|
||||
await uow.Repository<OpenItem, long>().UpdateAsync(item, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static async Task MarkMandatesAsync(IUnitOfWork uow, IReadOnlyList<RemittanceLine> lines, CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var group in lines.Where(l => l.MandateId is not null).GroupBy(l => l.MandateId!.Value))
|
||||
{
|
||||
if (await uow.Repository<SddMandate, long>().GetAsync(group.Key, cancellationToken).ConfigureAwait(false) is { } mandate)
|
||||
{
|
||||
mandate.LastCollectionDate = group.Max(l => l.DueDate);
|
||||
await uow.Repository<SddMandate, long>().UpdateAsync(mandate, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static string EndToEnd(Remittance remittance, RemittanceLine line) =>
|
||||
"KH" + remittance.Year.ToString(CultureInfo.InvariantCulture) + remittance.Number.ToString("000", CultureInfo.InvariantCulture) + "-" + line.Id.ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
private static Remittance Copy(Remittance r) => new()
|
||||
{
|
||||
Id = r.Id,
|
||||
Year = r.Year,
|
||||
Number = r.Number,
|
||||
Kind = r.Kind,
|
||||
Status = r.Status,
|
||||
TotalAmount = r.TotalAmount,
|
||||
ItemCount = r.ItemCount,
|
||||
GlEntryId = r.GlEntryId,
|
||||
CreditedOn = r.CreditedOn,
|
||||
CreditEntryId = r.CreditEntryId,
|
||||
};
|
||||
|
||||
private sealed record PartyBanks(Dictionary<long, PartyBankAccount> Accounts, List<SddMandate> Mandates);
|
||||
}
|
||||
@@ -566,6 +566,9 @@ public sealed class DunningLevel : Entity<long>
|
||||
|
||||
/// <summary>What else happens.</summary>
|
||||
public DunningAction Action { get; set; }
|
||||
|
||||
/// <summary>Sent by the scheduled task without asking (e-mail and PEC only).</summary>
|
||||
public bool Automatic { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The state of a reminder.</summary>
|
||||
|
||||
@@ -222,6 +222,7 @@ public sealed class M20261113_003_CreateTreasury : IMigration
|
||||
t.String("channel", 60).NotNull();
|
||||
t.Bool("charge_interest").NotNull().Default(false);
|
||||
t.String("action", 40).NotNull();
|
||||
t.Bool("automatic").NotNull().Default(false);
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_dunning_levels_level", "level");
|
||||
});
|
||||
|
||||
@@ -56,3 +56,12 @@ public interface ILatePaymentRules
|
||||
/// <summary>The fixed compensation for recovery costs, per invoice (Italy: 40 euro, art. 6).</summary>
|
||||
decimal RecoveryCompensation { get; }
|
||||
}
|
||||
|
||||
/// <summary>Which remittance collects or pays the items of a payment method, by the code of the method in the pack.</summary>
|
||||
public interface IRemittanceMethods
|
||||
{
|
||||
/// <summary>The kind of remittance of a method.</summary>
|
||||
/// <param name="methodCode">The code of the method in the e-invoice (for Italy the <c>MPxx</c> codes).</param>
|
||||
/// <returns>The kind, or <see langword="null"/> when the method does not go in remittances.</returns>
|
||||
RemittanceKind? KindOf(string? methodCode);
|
||||
}
|
||||
@@ -16,6 +16,7 @@ public sealed class ItalyFiscalPack : FiscalPackBase
|
||||
{
|
||||
AddFeature<IEInvoiceFormat>(new FatturaPaFormat());
|
||||
AddFeature<ILatePaymentRules>(new LatePaymentRulesIt());
|
||||
AddFeature<IRemittanceMethods>(new RemittanceMethodsIt());
|
||||
AddFeature<IIncomingInvoiceReader>(new FatturaPaReader());
|
||||
AddFeature<IIncomingInvoiceRules>(new IncomingInvoiceRulesIt());
|
||||
AddFeature<ISelfInvoiceRules>(new SelfInvoiceRulesIt());
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
using Khaemhat.Core.Treasury;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy;
|
||||
|
||||
/// <summary>
|
||||
/// The Italian payment methods (codes <c>MPxx</c> of FatturaPA) that go in remittances: RiBa (MP12), SEPA direct
|
||||
/// debits core (MP19, MP20) and B2B (MP21), credit transfers for the payments to suppliers (MP05).
|
||||
/// </summary>
|
||||
public sealed class RemittanceMethodsIt : IRemittanceMethods
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public RemittanceKind? KindOf(string? methodCode) => methodCode switch
|
||||
{
|
||||
"MP12" => RemittanceKind.Riba,
|
||||
"MP19" or "MP20" => RemittanceKind.SddCore,
|
||||
"MP21" => RemittanceKind.SddB2b,
|
||||
"MP05" => RemittanceKind.SepaCreditTransfer,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
@@ -164,6 +164,16 @@ internal static class KhaemhatServices
|
||||
services.AddSingleton<Khaemhat.Application.Ledger.RecurringEntryService>();
|
||||
services.AddSingleton<IScheduledJob, Khaemhat.Application.Ledger.RecurringEntriesJob>();
|
||||
|
||||
// The schedule and the treasury (ADR 0038): collections, remittances, reconciliation, reminders, cash flow.
|
||||
services.AddSingleton<Khaemhat.Application.Treasury.ScheduleService>();
|
||||
services.AddSingleton<Khaemhat.Application.Treasury.PaymentService>();
|
||||
services.AddSingleton<Khaemhat.Application.Treasury.RemittanceService>();
|
||||
services.AddSingleton<Khaemhat.Application.Treasury.MandateService>();
|
||||
services.AddSingleton<Khaemhat.Application.Treasury.BankReconciliationService>();
|
||||
services.AddSingleton<Khaemhat.Application.Treasury.DunningService>();
|
||||
services.AddSingleton<Khaemhat.Application.Treasury.CashFlowService>();
|
||||
services.AddSingleton<IScheduledJob, Khaemhat.Application.Treasury.DunningJob>();
|
||||
|
||||
// The document engine (ADR 0032): one engine, the copies, a typed service per family.
|
||||
services.AddSingleton<Khaemhat.Application.Documents.DocumentEngine>();
|
||||
services.AddSingleton<Khaemhat.Application.Documents.DocumentCopyService>();
|
||||
|
||||
Reference in new issue
Block a user