diff --git a/src/Khaemhat.Application/Jobs/JobScheduler.cs b/src/Khaemhat.Application/Jobs/JobScheduler.cs
index 2558e67..51c3d98 100644
--- a/src/Khaemhat.Application/Jobs/JobScheduler.cs
+++ b/src/Khaemhat.Application/Jobs/JobScheduler.cs
@@ -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;
diff --git a/src/Khaemhat.Application/Treasury/BankReconciliationService.cs b/src/Khaemhat.Application/Treasury/BankReconciliationService.cs
new file mode 100644
index 0000000..b356874
--- /dev/null
+++ b/src/Khaemhat.Application/Treasury/BankReconciliationService.cs
@@ -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;
+
+/// The result of an import of a bank statement.
+/// The statement.
+/// The new movements.
+/// The movements already imported and skipped.
+/// The movements with a proposal.
+public sealed record StatementImport(BankStatement Statement, int Added, int Duplicates, int Suggested);
+
+/// A movement with the name of its party.
+/// The movement.
+/// The customer or supplier of the match.
+public sealed record StatementLineRow(BankStatementLine Line, string? PartyName);
+
+/// The position of a bank account: the ledger against the bank.
+/// The bank account.
+/// The balance of its ledger account to the day.
+/// The closing balance of its last statement.
+/// The day of that balance.
+/// Movements still to reconcile.
+/// Their sum.
+public sealed record BankPosition(long BankAccountId, decimal BookBalance, decimal? BankBalance, DateOnly? BankBalanceDate, int ToMatch, decimal ToMatchAmount);
+
+/// A saved rule being written.
+/// The rule, or .
+/// The name.
+/// The text looked for in the description.
+/// Money in, out or both.
+/// The account posted against the bank.
+/// The description of the entry.
+/// Not used.
+public sealed record BankRuleInput(long? Id, string Name, string Pattern, BankRuleDirection Direction, long AccountId, string? EntryDescription, bool Disabled);
+
+///
+/// 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.
+///
+public sealed class BankReconciliationService
+{
+ /// The confidence from which the proposals are confirmed together.
+ 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;
+
+ /// Creates the service.
+ /// The units of work.
+ /// The permissions.
+ /// The fiscal pack of each company.
+ /// The history.
+ /// The clock.
+ 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;
+ }
+
+ /// The fingerprint of a movement: the same movement imported twice has the same one.
+ /// The bank account.
+ /// The movement.
+ /// How many equal movements came before it in the same file.
+ /// 64 hexadecimal characters.
+ 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();
+ }
+
+ /// Reads a bank file of any supported format.
+ /// The file.
+ /// The fiscal pack (its readers, such as CBI).
+ /// The statement.
+ /// The format is not recognized or the file cannot be read.
+ 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() 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]);
+ }
+
+ /// The statements imported for a bank account.
+ /// Who reads.
+ /// The company.
+ /// The bank account.
+ /// Cancellation.
+ /// The statements, latest first.
+ public async Task> 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().ListAsync(
+ Query.For().Where(s => s.BankAccountId == bankAccountId).OrderByDescending(s => s.ToDate).OrderByDescending(s => s.Id), cancellationToken).ConfigureAwait(false)).Items;
+ }
+
+ /// Imports a bank file: the movements already imported are skipped, the new ones get their proposals.
+ /// Who imports it.
+ /// The company.
+ /// The bank account.
+ /// The name of the file.
+ /// The file.
+ /// Cancellation.
+ /// What was imported.
+ public async Task 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().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().InsertAsync(statement, cancellationToken).ConfigureAwait(false);
+ var lines = uow.Repository();
+ var seen = new Dictionary(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().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().UpdateAsync(statement, cancellationToken).ConfigureAwait(false);
+ var suggested = await SuggestAsync(uow, bankAccountId, cancellationToken).ConfigureAwait(false);
+ await _audit.RecordAsync(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);
+ }
+
+ /// The movements of a bank account.
+ /// Who reads.
+ /// The company.
+ /// The bank account.
+ /// Only those to reconcile (to match or suggested).
+ /// From this day.
+ /// Up to this day.
+ /// Cancellation.
+ /// The movements, by date.
+ public async Task> 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().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().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))];
+ }
+
+ /// The position of a bank account.
+ /// Who reads.
+ /// The company.
+ /// The bank account.
+ /// Cancellation.
+ /// The position.
+ public async Task 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().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(
+ 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().FindAsync(
+ Query.For().Where(s => s.BankAccountId == bankAccountId && s.ClosingBalance != null).OrderByDescending(s => s.ToDate).OrderByDescending(s => s.Id), cancellationToken).ConfigureAwait(false);
+ var open = (await uow.Repository().ListAsync(
+ Query.For().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));
+ }
+
+ /// Computes the proposals again for the movements to reconcile.
+ /// Who does it.
+ /// The company.
+ /// The bank account.
+ /// Cancellation.
+ /// The movements with a proposal.
+ public async Task 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;
+ }
+
+ /// Confirms the proposal of a movement.
+ /// Who confirms.
+ /// The company.
+ /// The movement.
+ /// Cancellation.
+ /// The movement.
+ public async Task 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;
+ }
+
+ /// Confirms every proposal at or above the threshold.
+ /// Who confirms.
+ /// The company.
+ /// The bank account.
+ /// Cancellation.
+ /// How many movements were reconciled.
+ public async Task 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().ListAsync(
+ Query.For().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(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;
+ }
+
+ /// Reconciles a movement with open items chosen by hand: a collection or payment is recorded.
+ /// Who does it.
+ /// The company.
+ /// The movement.
+ /// The items, oldest first.
+ /// Cancellation.
+ /// The movement.
+ public async Task MatchItemsAsync(Actor actor, string companyCode, long lineId, IReadOnlyList 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;
+ }
+
+ /// Reconciles a movement with a collection or payment already recorded.
+ /// Who does it.
+ /// The company.
+ /// The movement.
+ /// The payment.
+ /// Cancellation.
+ /// The movement.
+ public async Task 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;
+ }
+
+ /// Posts a movement on an account against the bank, and may save a rule for the next ones.
+ /// Who does it.
+ /// The company.
+ /// The movement.
+ /// The account.
+ /// The description of the entry.
+ /// The text of a rule to save, or .
+ /// Cancellation.
+ /// The movement.
+ public async Task 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().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().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().UpdateAsync(line, cancellationToken).ConfigureAwait(false);
+ await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
+ return line;
+ }
+
+ /// Leaves a movement out of the reconciliation (a transfer between own accounts already posted).
+ /// Who does it.
+ /// The company.
+ /// The movement.
+ /// Cancellation.
+ /// A task.
+ 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().UpdateAsync(line, cancellationToken).ConfigureAwait(false);
+ await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// 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.
+ ///
+ /// Who does it.
+ /// The company.
+ /// The movement.
+ /// Cancellation.
+ /// A task.
+ 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().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().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().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().UpdateAsync(line, cancellationToken).ConfigureAwait(false);
+ await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
+ }
+
+ /// The saved rules.
+ /// Who reads.
+ /// The company.
+ /// Cancellation.
+ /// The rules, by name.
+ public async Task> 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().ListAsync(Query.For().OrderBy(r => r.Name), cancellationToken).ConfigureAwait(false)).Items;
+ }
+
+ /// Writes a rule.
+ /// Who writes.
+ /// The company.
+ /// The rule.
+ /// Cancellation.
+ /// The rule.
+ public async Task 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();
+ 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;
+ }
+
+ /// Deletes a rule.
+ /// Who does it.
+ /// The company.
+ /// The rule.
+ /// Cancellation.
+ /// A task.
+ 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().DeleteAsync(id, cancellationToken).ConfigureAwait(false);
+ await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
+ }
+
+ /// Gives the movements to reconcile of a bank account their best proposal.
+ internal static async Task SuggestAsync(IUnitOfWork uow, long bankAccountId, CancellationToken cancellationToken)
+ {
+ var lines = (await uow.Repository().ListAsync(
+ Query.For().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().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(a => a.Id);
+ var rules = (await uow.Repository().ListAsync(Query.For().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().UpdateAsync(line, cancellationToken).ConfigureAwait(false);
+ }
+
+ return count;
+ }
+
+ private static async Task> CandidatesAsync(IUnitOfWork uow, long bankAccountId, DateOnly since, CancellationToken cancellationToken)
+ {
+ var result = new List();
+ var items = (await uow.Repository().ListAsync(
+ Query.For().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().ListAsync(
+ Query.For().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>();
+ foreach (var chunk in partyIds.Chunk(500))
+ {
+ var list = chunk.ToList();
+ foreach (var account in (await uow.Repository().ListAsync(Query.For().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 Names(long partyId) => parties.GetValueOrDefault(partyId) is { } p ? [p.Name, .. p.FiscalName is { } f ? new[] { f } : []] : [];
+ IReadOnlyList 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(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().ListAsync(
+ Query.For().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().ListAsync(
+ Query.For().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();
+ var items = new List();
+ 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().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().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().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().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().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().UpdateAsync(rule, cancellationToken).ConfigureAwait(false);
+ break;
+ }
+
+ default:
+ throw new ValidationFailedException(["Targets:" + TreasuryErrors.MatchAmount]);
+ }
+
+ Matched(line, line.MatchKind, userName);
+ await uow.Repository().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(), cancellationToken).ConfigureAwait(false);
+ var amount = Math.Abs(line.Amount);
+ var text = LedgerStore.Trim(description, 200)!;
+ IReadOnlyList 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 OpenLineAsync(IUnitOfWork uow, long lineId, CancellationToken cancellationToken)
+ {
+ var line = await uow.Repository().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;
+ }
+}
diff --git a/src/Khaemhat.Application/Treasury/CashFlowService.cs b/src/Khaemhat.Application/Treasury/CashFlowService.cs
new file mode 100644
index 0000000..8c7545e
--- /dev/null
+++ b/src/Khaemhat.Application/Treasury/CashFlowService.cs
@@ -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;
+
+/// The balance of a bank or cash account in the ledger.
+/// The bank account, or for the cash.
+/// Its name.
+/// Its ledger balance today.
+public sealed record CashAccountBalance(long? BankAccountId, string Name, decimal Balance);
+
+/// The cash flow forecast.
+/// The first day.
+/// How many days.
+/// The banks and the cash with their balance.
+/// The money today.
+/// The periods with what comes in, goes out and the balance after.
+/// The movements forecast, by date.
+/// The sources included.
+public sealed record CashFlowForecast(
+ DateOnly From, int Days, IReadOnlyList Accounts, decimal Opening, IReadOnlyList Periods, IReadOnlyList Movements,
+ IReadOnlySet Sources);
+
+///
+/// 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.
+///
+public sealed class CashFlowService
+{
+ /// The days after the delivery when an order is expected to be paid.
+ public const int OrderPaymentDays = 30;
+
+ private readonly IUnitOfWorkFactory _factory;
+ private readonly PermissionService _permissions;
+ private readonly TimeProvider _clock;
+
+ /// Creates the service.
+ /// The units of work.
+ /// The permissions.
+ /// The clock.
+ public CashFlowService(IUnitOfWorkFactory factory, PermissionService permissions, TimeProvider clock)
+ {
+ ArgumentNullException.ThrowIfNull(factory);
+ ArgumentNullException.ThrowIfNull(permissions);
+ ArgumentNullException.ThrowIfNull(clock);
+ _factory = factory;
+ _permissions = permissions;
+ _clock = clock;
+ }
+
+ /// The forecast.
+ /// Who reads.
+ /// The company.
+ /// How many days ahead (30 to 365).
+ /// The sources to include, or for all.
+ /// The length of a period (7 for weeks, 30 for months).
+ /// Cancellation.
+ /// The forecast.
+ public async Task ForecastAsync(
+ Actor actor, string companyCode, int days = 90, IReadOnlySet? 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().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();
+ var parties = new Dictionary();
+
+ if (include.Contains(CashFlowSource.Receivables) || include.Contains(CashFlowSource.Payables))
+ {
+ var items = (await uow.Repository().ListAsync(
+ Query.For().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().ListAsync(
+ Query.For().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(uow, 1m, CashFlowSource.SaleOrders, until, cancellationToken).ConfigureAwait(false));
+ }
+
+ if (include.Contains(CashFlowSource.PurchaseOrders))
+ {
+ movements.AddRange(await OrdersAsync(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().ListAsync(
+ Query.For().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> BalancesAsync(IUnitOfWork uow, DateOnly today, CancellationToken cancellationToken)
+ {
+ var result = new List();
+ var draft = nameof(GlEntryStatus.Draft);
+ var banks = (await uow.Repository().ListAsync(Query.For().OrderBy(b => b.Code), cancellationToken).ConfigureAwait(false)).Items;
+ var seen = new HashSet();
+ 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(
+ 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(
+ 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> OrdersAsync(
+ IUnitOfWork uow, decimal sign, CashFlowSource source, DateOnly until, CancellationToken cancellationToken)
+ where THeader : DocumentHeader, new()
+ where TLine : DocumentLine, new()
+ {
+ var orders = (await uow.Repository().ListAsync(
+ Query.For().Where(o => o.Status == DocumentStatus.Confirmed || o.Status == DocumentStatus.PartiallyFulfilled), cancellationToken).ConfigureAwait(false)).Items;
+ var result = new List();
+ foreach (var chunk in orders.Chunk(200))
+ {
+ var ids = chunk.Select(o => o.Id).ToList();
+ var lines = (await uow.Repository().ListAsync(Query.For().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> RecurringAsync(IUnitOfWork uow, DateOnly today, DateOnly until, CancellationToken cancellationToken)
+ {
+ var recurring = (await uow.Repository().ListAsync(Query.For().Where(r => !r.Disabled), cancellationToken).ConfigureAwait(false)).Items;
+ if (recurring.Count == 0)
+ {
+ return [];
+ }
+
+ var moneyAccounts = new HashSet();
+ foreach (var bank in (await uow.Repository().ListAsync(Query.For(), 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().ListAsync(Query.For().Where(a => a.Type == AccountType.Cash || a.Type == AccountType.Bank), cancellationToken).ConfigureAwait(false)).Items)
+ {
+ moneyAccounts.Add(account.Id);
+ }
+
+ var result = new List();
+ 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;
+ }
+}
diff --git a/src/Khaemhat.Application/Treasury/DunningService.cs b/src/Khaemhat.Application/Treasury/DunningService.cs
new file mode 100644
index 0000000..c44d229
--- /dev/null
+++ b/src/Khaemhat.Application/Treasury/DunningService.cs
@@ -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;
+
+/// A customer to remind, with the level due and its overdue items.
+/// The customer.
+/// Its code.
+/// Its name.
+/// Its e-mail.
+/// Its PEC.
+/// The level due, or when none is due yet.
+/// The highest level already sent for its items.
+/// The overdue items.
+/// Their residual.
+/// The late payment interest to the day.
+/// The days past due of the oldest item.
+/// The last reminder.
+/// The customer is blocked.
+public sealed record DunningProposal(
+ long PartyId, string? PartyCode, string PartyName, string? Email, string? Pec, DunningLevel? Level, int CurrentLevel, IReadOnlyList Items,
+ decimal Overdue, decimal Interest, int MaxDays, DateOnly? LastSent, bool Blocked);
+
+/// A reminder sent, with the name of its customer.
+/// The reminder.
+/// The customer.
+public sealed record DunningLetterRow(DunningLetter Letter, string PartyName);
+
+/// What a run of reminders did.
+/// Reminders queued by e-mail or PEC.
+/// Reminders to print (letter channel).
+/// Customers left out, with the reason code.
+/// The letters to print, one file, when any.
+public sealed record DunningRun(int Sent, int Letters, IReadOnlyList<(string Party, string Reason)> Skipped, LedgerFile? Pdf);
+
+///
+/// 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.
+///
+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;
+
+ /// Creates the service.
+ /// The units of work.
+ /// The permissions.
+ /// The fiscal pack of each company.
+ /// The history.
+ /// The outgoing mail.
+ /// The clock.
+ 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;
+ }
+
+ /// The levels given to a company that has none (mockup 056).
+ /// Three levels: 7, 20 and 45 days after the due date.
+ public static IReadOnlyList 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}",
+ },
+ ];
+
+ /// The levels, created with the defaults when the company has none.
+ /// Who reads.
+ /// The company.
+ /// Cancellation.
+ /// The levels in order.
+ public async Task> 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);
+ }
+
+ /// Writes a level.
+ /// Who writes.
+ /// The company.
+ /// The level (its Level number identifies it).
+ /// Cancellation.
+ /// The level.
+ public async Task 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();
+ var number = level.Level;
+ var existing = await repository.FindAsync(Query.For().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;
+ }
+
+ /// The customers with overdue items and the level due for each.
+ /// Who reads.
+ /// The company.
+ /// Cancellation.
+ /// The proposals, the most overdue first.
+ public async Task> 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();
+ await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
+ return await ProposalsAsync(uow, rules, TreasuryStore.Today(_clock), cancellationToken).ConfigureAwait(false);
+ }
+
+ /// The reminders sent.
+ /// Who reads.
+ /// The company.
+ /// One customer.
+ /// Cancellation.
+ /// The reminders, latest first (at most 500).
+ public async Task> 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();
+ if (partyId is { } party)
+ {
+ query = query.Where(l => l.PartyId == party);
+ }
+
+ var letters = (await uow.Repository().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))];
+ }
+
+ /// The letter of the level due for a customer, as a PDF, without sending it.
+ /// Who reads.
+ /// The company.
+ /// The customer.
+ /// Cancellation.
+ /// The file.
+ public async Task 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();
+ 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().FindAsync(Query.For(), cancellationToken).ConfigureAwait(false);
+ var party = await uow.Repository().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);
+ }
+
+ /// Sends the reminders of the level due to customers.
+ /// Who sends them.
+ /// The company.
+ /// The customers.
+ /// Cancellation.
+ /// What was done.
+ public async Task SendAsync(Actor actor, string companyCode, IReadOnlyList 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);
+ }
+
+ /// Sends the automatic levels of a company (the scheduled task).
+ /// The company.
+ /// Cancellation.
+ /// What was done.
+ public Task 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> EnsureLevelsAsync(IUnitOfWork uow, CancellationToken cancellationToken)
+ {
+ var repository = uow.Repository();
+ var levels = (await repository.ListAsync(Query.For().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> 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().ListAsync(
+ Query.For().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().ListAsync(Query.For().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();
+ 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 RunAsync(string company, HashSet? partyIds, bool automaticOnly, string? userName, CancellationToken cancellationToken)
+ {
+ var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).GetFeature();
+ 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().FindAsync(Query.For(), cancellationToken).ConfigureAwait(false);
+ var skipped = new List<(string, string)>();
+ var printed = new List();
+ 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().GetAsync(proposal.PartyId, cancellationToken).ConfigureAwait(false);
+ var recipients = new List();
+ 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();
+ if (level.Action == DunningAction.NotifyAgent && party?.SalespersonId is { } agentId
+ && await uow.Repository().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().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().UpdateAsync(row.Item, cancellationToken).ConfigureAwait(false);
+ }
+
+ if (level.Action == DunningAction.BlockCustomer)
+ {
+ var terms = uow.Repository();
+ var partyId = proposal.PartyId;
+ var current = await terms.FindAsync(Query.For().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 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 LettersAsync(
+ IUnitOfWork uow, CompanyProfile? profile, IReadOnlyList 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().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;
+ }
+
+ }
+}
+
+/// Sends the automatic reminders of every company (job finance.dunning, SPEC §11.8).
+/// The companies.
+/// The reminders.
+/// The licence.
+public sealed class DunningJob(ICompanyRegistry companies, DunningService service, ILicenseGate license) : IScheduledJob
+{
+ /// The job type.
+ public const string JobType = "finance.dunning";
+
+ ///
+ public string Type => JobType;
+
+ ///
+ public async Task 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.");
+ }
+}
diff --git a/src/Khaemhat.Application/Treasury/MandateService.cs b/src/Khaemhat.Application/Treasury/MandateService.cs
new file mode 100644
index 0000000..b9e6780
--- /dev/null
+++ b/src/Khaemhat.Application/Treasury/MandateService.cs
@@ -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;
+
+/// A mandate being written.
+/// The mandate, or for a new one.
+/// The debtor.
+/// The unique mandate reference (UMR).
+/// The day it was signed.
+/// Core or B2B.
+/// The account of the debtor.
+/// The BIC.
+/// For one collection only.
+/// Notes.
+public sealed record MandateInput(long? Id, long PartyId, string Reference, DateOnly SignatureDate, SddScheme Scheme, string Iban, string? Bic, bool OneOff, string? Notes);
+
+/// A mandate with the name of its debtor.
+/// The mandate.
+/// The code of the debtor.
+/// The name of the debtor.
+public sealed record MandateRow(SddMandate Mandate, string? PartyCode, string PartyName);
+
+/// The SEPA direct debit mandates of the customers (SPEC §11.8, mockup 055, ADR 0038).
+public sealed class MandateService
+{
+ private readonly IUnitOfWorkFactory _factory;
+ private readonly PermissionService _permissions;
+ private readonly AuditTrail _audit;
+
+ /// Creates the service.
+ /// The units of work.
+ /// The permissions.
+ /// The history.
+ public MandateService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit)
+ {
+ ArgumentNullException.ThrowIfNull(factory);
+ ArgumentNullException.ThrowIfNull(permissions);
+ ArgumentNullException.ThrowIfNull(audit);
+ _factory = factory;
+ _permissions = permissions;
+ _audit = audit;
+ }
+
+ /// The mandates, of a party or all.
+ /// Who reads.
+ /// The company.
+ /// One party.
+ /// Cancellation.
+ /// The mandates, by party and date.
+ public async Task> 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();
+ if (partyId is { } party)
+ {
+ query = query.Where(m => m.PartyId == party);
+ }
+
+ var mandates = (await uow.Repository().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)];
+ }
+
+ /// Writes a mandate.
+ /// Who writes.
+ /// The company.
+ /// The mandate.
+ /// Cancellation.
+ /// The mandate.
+ public async Task 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();
+ 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();
+ var same = await repository.FindAsync(Query.For().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(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;
+ }
+
+ /// Revokes a mandate or takes the revocation back.
+ /// Who does it.
+ /// The company.
+ /// The mandate.
+ /// Revoked or not.
+ /// Cancellation.
+ /// A task.
+ 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().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound);
+ var before = Copy(mandate);
+ mandate.Revoked = revoked;
+ await uow.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);
+ }
+
+ /// Deletes a mandate never used in a remittance.
+ /// Who does it.
+ /// The company.
+ /// The mandate.
+ /// Cancellation.
+ /// A task.
+ 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().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound);
+ if (await uow.Repository().CountAsync(Query.For().Where(l => l.MandateId == id), cancellationToken).ConfigureAwait(false) > 0)
+ {
+ throw new ValidationFailedException(["Id:" + TreasuryErrors.MandateUsed]);
+ }
+
+ await uow.Repository().DeleteAsync(id, cancellationToken).ConfigureAwait(false);
+ await _audit.RecordAsync(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,
+ };
+}
diff --git a/src/Khaemhat.Application/Treasury/RemittanceService.cs b/src/Khaemhat.Application/Treasury/RemittanceService.cs
new file mode 100644
index 0000000..64cfe14
--- /dev/null
+++ b/src/Khaemhat.Application/Treasury/RemittanceService.cs
@@ -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;
+
+/// An item that can go in a remittance, with what is missing for the file.
+/// The item.
+/// The IBAN of the customer or supplier (of the mandate for direct debits).
+/// The mandate of a direct debit.
+/// The error codes that keep it out of the file.
+public sealed record RemittanceCandidate(ScheduleRow Row, string? Iban, SddMandate? Mandate, IReadOnlyList Problems)
+{
+ /// Ready for the file.
+ public bool Ready => Problems.Count == 0;
+}
+
+/// A new remittance.
+/// RiBa, direct debits or credit transfers.
+/// The bank of the company.
+/// The day it goes to the bank.
+/// The last due date of its items.
+/// Advanced subject to collection (salvo buon fine).
+/// Notes.
+/// The items.
+public sealed record RemittanceInput(RemittanceKind Kind, long BankAccountId, DateOnly PresentationDate, DateOnly DueUntil, bool Advance, string? Notes, IReadOnlyList OpenItemIds);
+
+/// A remittance with its bank.
+/// The remittance.
+/// The bank (code and name).
+public sealed record RemittanceRow(Remittance Remittance, string Bank);
+
+/// A line of a remittance with its item and party.
+/// The line.
+/// The item.
+/// The party.
+/// The reference of the mandate.
+public sealed record RemittanceLineRow(RemittanceLine Line, OpenItem? Item, string PartyName, string? Mandate);
+
+///
+/// The remittances (distinte, SPEC §11.8, mockup 055, ADR 0038): RiBa in the CBI file of the pack, SEPA direct
+/// debits (pain.008) with their mandates, SEPA credit transfers to suppliers (pain.001). 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.
+///
+public sealed class RemittanceService
+{
+ private readonly IUnitOfWorkFactory _factory;
+ private readonly PermissionService _permissions;
+ private readonly CompanyFiscalContext _packs;
+ private readonly AuditTrail _audit;
+ private readonly TimeProvider _clock;
+
+ /// Creates the service.
+ /// The units of work.
+ /// The permissions.
+ /// The fiscal pack of each company.
+ /// The history.
+ /// The clock.
+ public 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;
+ }
+
+ /// The direction of the items of a kind of remittance.
+ /// The kind.
+ /// Payables for credit transfers, receivables otherwise.
+ public static OpenItemDirection DirectionOf(RemittanceKind kind) =>
+ kind == RemittanceKind.SepaCreditTransfer ? OpenItemDirection.Payable : OpenItemDirection.Receivable;
+
+ /// The remittances of a year.
+ /// Who reads.
+ /// The company.
+ /// The year.
+ /// Cancellation.
+ /// The remittances, latest first.
+ public async Task> 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().ListAsync(
+ Query.For().Where(r => r.Year == year).OrderByDescending(r => r.Number), cancellationToken).ConfigureAwait(false)).Items;
+ var banks = (await uow.Repository().ListAsync(Query.For(), 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))];
+ }
+
+ /// A remittance with its lines.
+ /// Who reads.
+ /// The company.
+ /// The remittance.
+ /// Cancellation.
+ /// The remittance and its lines, or .
+ public async Task<(RemittanceRow Row, IReadOnlyList 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().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } remittance)
+ {
+ return null;
+ }
+
+ var bank = await uow.Repository().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().ListAsync(Query.For().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().ListAsync(Query.For(), 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))]);
+ }
+
+ /// The items that can go in a remittance of a kind, due up to a day.
+ /// Who reads.
+ /// The company.
+ /// The kind.
+ /// The last due date.
+ /// Cancellation.
+ /// The candidates, by due date.
+ public async Task> 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().ListAsync(
+ Query.For().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().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(m => m.Id);
+ var kinds = pack.GetFeature();
+ 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))];
+ }
+
+ /// Drafts a remittance with items; they are reserved for it.
+ /// Who drafts it.
+ /// The company.
+ /// The remittance.
+ /// Cancellation.
+ /// The remittance.
+ public async Task 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().GetAsync(input.BankAccountId, cancellationToken).ConfigureAwait(false)
+ ?? throw new ValidationFailedException(["BankAccountId:" + TreasuryErrors.NotFound]);
+ var year = input.PresentationDate.Year;
+ var number = (int)((await uow.QuerySingleAsync(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().InsertAsync(remittance, cancellationToken).ConfigureAwait(false);
+ var itemRepository = uow.Repository();
+ var direction = DirectionOf(input.Kind);
+ var items = new List();
+ 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();
+ 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().UpdateAsync(remittance, cancellationToken).ConfigureAwait(false);
+ await _audit.RecordAsync(uow, AuditAction.Insert, remittance.Id, null, remittance, actor.UserName, cancellationToken).ConfigureAwait(false);
+ await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
+ return remittance;
+ }
+
+ /// Takes a line out of a remittance not presented.
+ /// Who does it.
+ /// The company.
+ /// The line.
+ /// Cancellation.
+ /// A task.
+ 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().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().DeleteAsync(line.Id, cancellationToken).ConfigureAwait(false);
+ remittance.ItemCount--;
+ remittance.TotalAmount -= line.Amount;
+ remittance.Status = RemittanceStatus.Draft;
+ await uow.Repository().UpdateAsync(remittance, cancellationToken).ConfigureAwait(false);
+ await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
+ }
+
+ /// Deletes a remittance not presented; its items are free again.
+ /// Who does it.
+ /// The company.
+ /// The remittance.
+ /// Cancellation.
+ /// A task.
+ 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().DeleteAsync(id, cancellationToken).ConfigureAwait(false);
+ await _audit.RecordAsync(uow, AuditAction.Delete, id, remittance, null, actor.UserName, cancellationToken).ConfigureAwait(false);
+ await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
+ }
+
+ /// Writes the file of a remittance for the bank (CBI for RiBa, XML for SEPA).
+ /// Who does it.
+ /// The company.
+ /// The remittance.
+ /// Cancellation.
+ /// The file.
+ public async Task 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().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().GetAsync(remittance.BankAccountId, cancellationToken).ConfigureAwait(false)
+ ?? throw new ValidationFailedException(["BankAccountId:" + TreasuryErrors.NotFound]);
+ var profile = await uow.Repository().FindAsync(Query.For(), cancellationToken).ConfigureAwait(false);
+ var errors = new List();
+ 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().ListAsync(Query.For().Where(o => itemIds.Contains(o.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(o => o.Id);
+ var fileItems = new List();
+ 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() 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().UpdateAsync(remittance, cancellationToken).ConfigureAwait(false);
+ await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
+ return new LedgerFile(file.FileName, file.ContentType, file.Content);
+ }
+
+ ///
+ /// 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.
+ ///
+ /// Who does it.
+ /// The company.
+ /// The remittance.
+ /// Cancellation.
+ /// The remittance.
+ public async Task 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();
+ var lineRepository = uow.Repository();
+ 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();
+ 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();
+ 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().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;
+ }
+
+ /// Records the credit at maturity of a presented remittance: the effects not unpaid are collected.
+ /// Who does it.
+ /// The company.
+ /// The remittance.
+ /// The day of the credit.
+ /// Cancellation.
+ /// The remittance.
+ public async Task 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().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().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;
+ }
+
+ ///
+ /// 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.
+ ///
+ /// Who does it.
+ /// The company.
+ /// The line of the remittance.
+ /// The day the bank returned it.
+ /// The fees charged by the bank, debited to the customer.
+ /// Cancellation.
+ /// The line.
+ public async Task 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().GetAsync(lineId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound);
+ var remittance = await uow.Repository().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;
+ }
+
+ /// Credits a presented remittance inside a transaction (also from the bank reconciliation).
+ 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();
+ 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();
+ 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().UpdateAsync(line, cancellationToken).ConfigureAwait(false);
+ }
+
+ remittance.Status = RemittanceStatus.Closed;
+ remittance.CreditedOn = creditedOn;
+ await uow.Repository().UpdateAsync(remittance, cancellationToken).ConfigureAwait(false);
+ }
+
+ /// Records an unpaid effect inside a transaction (also from the bank reconciliation).
+ 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().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().GetAsync(line.OpenItemId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound);
+ var ledger = pack.GetFeature();
+ 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 { 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().UpdateAsync(item, cancellationToken).ConfigureAwait(false);
+ if (fees > 0m)
+ {
+ await uow.Repository().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().UpdateAsync(line, cancellationToken).ConfigureAwait(false);
+ }
+
+ internal static async Task> LinesAsync(IUnitOfWork uow, long remittanceId, CancellationToken cancellationToken) =>
+ (await uow.Repository