using Khaemhat.Application.Audit;
using Khaemhat.Application.Security;
using Khaemhat.Core.Caching;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Tables;
///
/// The installments of a payment term (SPEC ยง11.1): days from the document date, end of month, fixed day and share of
/// the amount. They are saved all together, because only the whole set has to add up to 100%.
///
public sealed class PaymentTermService
{
/// The installments do not add up to 100%.
public const string PercentTotal = "tables.payment-term.percent-total";
/// A payment term needs at least one installment.
public const string LinesRequired = "tables.payment-term.lines-required";
/// The days are negative or beyond a year and a half.
public const string DaysRange = "tables.payment-term.days";
/// The fixed day is not a day of the month.
public const string FixedDayRange = "tables.payment-term.fixed-day";
/// The field the errors of the installments are reported on.
public const string LinesField = "Lines";
private const int MaxDays = 540;
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly AuditTrail _audit;
private readonly ICacheProvider _cache;
/// Creates the service.
/// The units of work.
/// The permissions.
/// The audit trail.
/// The cache of the tables.
public PaymentTermService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, ICacheProvider cache)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(audit);
ArgumentNullException.ThrowIfNull(cache);
_factory = factory;
_permissions = permissions;
_audit = audit;
_cache = cache;
}
/// The installments of a payment term, in order.
/// Who reads.
/// The company.
/// The payment term.
/// Cancellation.
/// The installments.
public async Task> LinesAsync(Actor actor, string companyCode, long paymentTermId, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.ReadPermission, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await ReadAsync(uow, paymentTermId, cancellationToken).ConfigureAwait(false);
}
/// Checks a set of installments.
/// The installments.
/// The errors, on .
public static IReadOnlyList Validate(IReadOnlyList lines)
{
ArgumentNullException.ThrowIfNull(lines);
var problems = new List();
if (lines.Count == 0)
{
problems.Add(new(LinesField, LinesRequired));
return problems;
}
if (lines.Any(l => l.Days < 0 || l.Days > MaxDays))
{
problems.Add(new(LinesField, DaysRange));
}
if (lines.Any(l => l.FixedDay is < 1 or > 31))
{
problems.Add(new(LinesField, FixedDayRange));
}
if (lines.Any(l => l.Percent <= 0) || lines.Sum(l => l.Percent) != 100m)
{
problems.Add(new(LinesField, PercentTotal));
}
return problems;
}
/// Replaces the installments of a payment term, numbering them 1, 2, 3 in the given order.
/// Who saves.
/// The company.
/// The payment term.
/// The installments.
/// Cancellation.
/// The saved installments.
/// The installments are not valid (Lines:code).
public async Task> SaveLinesAsync(Actor actor, string companyCode, long paymentTermId, IReadOnlyList lines,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(lines);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.WritePermission, cancellationToken).ConfigureAwait(false);
var problems = Validate(lines);
if (problems.Count > 0)
{
throw new ValidationFailedException([.. problems.Select(p => p.Field + ":" + p.Code)]);
}
IReadOnlyList saved;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
_ = await uow.Repository().GetAsync(paymentTermId, cancellationToken).ConfigureAwait(false)
?? throw new KeyNotFoundException(TableService.NotFound);
var repository = uow.Repository();
foreach (var old in await ReadAsync(uow, paymentTermId, cancellationToken).ConfigureAwait(false))
{
await repository.DeleteAsync(old.Id, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Delete, old.Id, old, null, actor.UserName, cancellationToken).ConfigureAwait(false);
}
var number = 0;
foreach (var line in lines)
{
var row = new PaymentTermLine
{
PaymentTermId = paymentTermId,
Number = ++number,
Days = line.Days,
EndOfMonth = line.EndOfMonth,
FixedDay = line.FixedDay,
Percent = line.Percent,
};
var id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Insert, id, null, row, actor.UserName, cancellationToken).ConfigureAwait(false);
}
saved = await ReadAsync(uow, paymentTermId, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
await _cache.PublishInvalidationAsync(CacheKeys.Prefix(company, "tables"), cancellationToken).ConfigureAwait(false);
return saved;
}
private static async Task> ReadAsync(IUnitOfWork uow, long paymentTermId, CancellationToken cancellationToken) =>
(await uow.Repository()
.ListAsync(Query.For().Where(x => x.PaymentTermId == paymentTermId).OrderBy(x => x.Number), cancellationToken)
.ConfigureAwait(false)).Items;
}