Remittances draft the items due, write the RiBa CBI or SEPA pain.001/pain.008 file, present them (bills account and advance, or supplier payments), credit them and record unpaid effects with their fees. The reconciliation imports CSV, CBI and CAMT.053 statements without duplicates and proposes matches with open items, payments, F24, remittances and saved rules. Reminders follow three levels with late interest, e-mail/PEC/letter and customer block, also from a scheduled task; the cash flow forecasts 90 days by week. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
201 lines
10 KiB
C#
201 lines
10 KiB
C#
using Khaemhat.Application.Audit;
|
|
using Khaemhat.Application.Ledger;
|
|
using Khaemhat.Application.Security;
|
|
using Khaemhat.Application.Tables;
|
|
using Khaemhat.Core.Treasury;
|
|
using Khaemhat.Core.Validation;
|
|
using Khaemhat.Data;
|
|
using Khaemhat.Data.Querying;
|
|
|
|
namespace Khaemhat.Application.Treasury;
|
|
|
|
/// <summary>A mandate being written.</summary>
|
|
/// <param name="Id">The mandate, or <see langword="null"/> for a new one.</param>
|
|
/// <param name="PartyId">The debtor.</param>
|
|
/// <param name="Reference">The unique mandate reference (UMR).</param>
|
|
/// <param name="SignatureDate">The day it was signed.</param>
|
|
/// <param name="Scheme">Core or B2B.</param>
|
|
/// <param name="Iban">The account of the debtor.</param>
|
|
/// <param name="Bic">The BIC.</param>
|
|
/// <param name="OneOff">For one collection only.</param>
|
|
/// <param name="Notes">Notes.</param>
|
|
public sealed record MandateInput(long? Id, long PartyId, string Reference, DateOnly SignatureDate, SddScheme Scheme, string Iban, string? Bic, bool OneOff, string? Notes);
|
|
|
|
/// <summary>A mandate with the name of its debtor.</summary>
|
|
/// <param name="Mandate">The mandate.</param>
|
|
/// <param name="PartyCode">The code of the debtor.</param>
|
|
/// <param name="PartyName">The name of the debtor.</param>
|
|
public sealed record MandateRow(SddMandate Mandate, string? PartyCode, string PartyName);
|
|
|
|
/// <summary>The SEPA direct debit mandates of the customers (SPEC §11.8, mockup 055, ADR 0038).</summary>
|
|
public sealed class MandateService
|
|
{
|
|
private readonly IUnitOfWorkFactory _factory;
|
|
private readonly PermissionService _permissions;
|
|
private readonly AuditTrail _audit;
|
|
|
|
/// <summary>Creates the service.</summary>
|
|
/// <param name="factory">The units of work.</param>
|
|
/// <param name="permissions">The permissions.</param>
|
|
/// <param name="audit">The history.</param>
|
|
public MandateService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(factory);
|
|
ArgumentNullException.ThrowIfNull(permissions);
|
|
ArgumentNullException.ThrowIfNull(audit);
|
|
_factory = factory;
|
|
_permissions = permissions;
|
|
_audit = audit;
|
|
}
|
|
|
|
/// <summary>The mandates, of a party or all.</summary>
|
|
/// <param name="actor">Who reads.</param>
|
|
/// <param name="companyCode">The company.</param>
|
|
/// <param name="partyId">One party.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>The mandates, by party and date.</returns>
|
|
public async Task<IReadOnlyList<MandateRow>> ListAsync(Actor actor, string companyCode, long? partyId = null, CancellationToken cancellationToken = default)
|
|
{
|
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleRead, cancellationToken).ConfigureAwait(false);
|
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
|
var query = Query.For<SddMandate>();
|
|
if (partyId is { } party)
|
|
{
|
|
query = query.Where(m => m.PartyId == party);
|
|
}
|
|
|
|
var mandates = (await uow.Repository<SddMandate, long>().ListAsync(query.OrderByDescending(m => m.SignatureDate), cancellationToken).ConfigureAwait(false)).Items;
|
|
var parties = await TreasuryStore.PartiesAsync(uow, mandates.Select(m => m.PartyId), cancellationToken).ConfigureAwait(false);
|
|
return [.. mandates.Select(m => new MandateRow(m, parties.GetValueOrDefault(m.PartyId)?.Code, parties.GetValueOrDefault(m.PartyId)?.Name ?? string.Empty))
|
|
.OrderBy(r => r.PartyName, StringComparer.CurrentCultureIgnoreCase)];
|
|
}
|
|
|
|
/// <summary>Writes a mandate.</summary>
|
|
/// <param name="actor">Who writes.</param>
|
|
/// <param name="companyCode">The company.</param>
|
|
/// <param name="input">The mandate.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>The mandate.</returns>
|
|
public async Task<SddMandate> SaveAsync(Actor actor, string companyCode, MandateInput input, CancellationToken cancellationToken = default)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(actor);
|
|
ArgumentNullException.ThrowIfNull(input);
|
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleWrite, cancellationToken).ConfigureAwait(false);
|
|
var reference = (input.Reference ?? string.Empty).Trim();
|
|
var iban = IbanValidator.Normalize(input.Iban);
|
|
var errors = new List<string>();
|
|
if (input.PartyId <= 0)
|
|
{
|
|
errors.Add("PartyId:" + TreasuryErrors.PartyRequired);
|
|
}
|
|
|
|
if (reference.Length == 0 || reference.Length > 35)
|
|
{
|
|
errors.Add("Reference:" + TreasuryErrors.MandateReference);
|
|
}
|
|
|
|
if (!IbanValidator.IsValid(iban))
|
|
{
|
|
errors.Add("Iban:" + TreasuryErrors.IbanInvalid);
|
|
}
|
|
|
|
if (errors.Count > 0)
|
|
{
|
|
throw new ValidationFailedException(errors);
|
|
}
|
|
|
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
|
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
|
var repository = uow.Repository<SddMandate, long>();
|
|
var same = await repository.FindAsync(Query.For<SddMandate>().Where(m => m.Reference == reference), cancellationToken).ConfigureAwait(false);
|
|
if (same is not null && same.Id != input.Id)
|
|
{
|
|
throw new ValidationFailedException(["Reference:" + TreasuryErrors.MandateDuplicate]);
|
|
}
|
|
|
|
var mandate = input.Id is { } id
|
|
? await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound)
|
|
: new SddMandate();
|
|
var before = input.Id is null ? null : Copy(mandate);
|
|
mandate.PartyId = input.PartyId;
|
|
mandate.Reference = reference;
|
|
mandate.SignatureDate = input.SignatureDate;
|
|
mandate.Scheme = input.Scheme;
|
|
mandate.Iban = iban;
|
|
mandate.Bic = LedgerStore.Trim(string.IsNullOrWhiteSpace(input.Bic) ? null : input.Bic.Trim().ToUpperInvariant(), 11);
|
|
mandate.OneOff = input.OneOff;
|
|
mandate.Notes = LedgerStore.Trim(string.IsNullOrWhiteSpace(input.Notes) ? null : input.Notes.Trim(), 200);
|
|
if (input.Id is null)
|
|
{
|
|
mandate.Id = await repository.InsertAsync(mandate, cancellationToken).ConfigureAwait(false);
|
|
await _audit.RecordAsync<SddMandate>(uow, AuditAction.Insert, mandate.Id, null, mandate, actor.UserName, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
else
|
|
{
|
|
await repository.UpdateAsync(mandate, cancellationToken).ConfigureAwait(false);
|
|
await _audit.RecordAsync(uow, AuditAction.Update, mandate.Id, before, mandate, actor.UserName, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
|
return mandate;
|
|
}
|
|
|
|
/// <summary>Revokes a mandate or takes the revocation back.</summary>
|
|
/// <param name="actor">Who does it.</param>
|
|
/// <param name="companyCode">The company.</param>
|
|
/// <param name="id">The mandate.</param>
|
|
/// <param name="revoked">Revoked or not.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>A task.</returns>
|
|
public async Task RevokeAsync(Actor actor, string companyCode, long id, bool revoked, CancellationToken cancellationToken = default)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(actor);
|
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleWrite, cancellationToken).ConfigureAwait(false);
|
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
|
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
|
var mandate = await uow.Repository<SddMandate, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound);
|
|
var before = Copy(mandate);
|
|
mandate.Revoked = revoked;
|
|
await uow.Repository<SddMandate, long>().UpdateAsync(mandate, cancellationToken).ConfigureAwait(false);
|
|
await _audit.RecordAsync(uow, AuditAction.Update, mandate.Id, before, mandate, actor.UserName, cancellationToken).ConfigureAwait(false);
|
|
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
/// <summary>Deletes a mandate never used in a remittance.</summary>
|
|
/// <param name="actor">Who does it.</param>
|
|
/// <param name="companyCode">The company.</param>
|
|
/// <param name="id">The mandate.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>A task.</returns>
|
|
public async Task DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(actor);
|
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleWrite, cancellationToken).ConfigureAwait(false);
|
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
|
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
|
var mandate = await uow.Repository<SddMandate, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound);
|
|
if (await uow.Repository<RemittanceLine, long>().CountAsync(Query.For<RemittanceLine>().Where(l => l.MandateId == id), cancellationToken).ConfigureAwait(false) > 0)
|
|
{
|
|
throw new ValidationFailedException(["Id:" + TreasuryErrors.MandateUsed]);
|
|
}
|
|
|
|
await uow.Repository<SddMandate, long>().DeleteAsync(id, cancellationToken).ConfigureAwait(false);
|
|
await _audit.RecordAsync<SddMandate>(uow, AuditAction.Delete, id, mandate, null, actor.UserName, cancellationToken).ConfigureAwait(false);
|
|
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
private static SddMandate Copy(SddMandate m) => new()
|
|
{
|
|
Id = m.Id,
|
|
PartyId = m.PartyId,
|
|
Reference = m.Reference,
|
|
SignatureDate = m.SignatureDate,
|
|
Scheme = m.Scheme,
|
|
Iban = m.Iban,
|
|
Bic = m.Bic,
|
|
OneOff = m.OneOff,
|
|
Revoked = m.Revoked,
|
|
Notes = m.Notes,
|
|
};
|
|
}
|