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,
};
}