Parties, items and the CRM archives need codes given by the system without
duplicates, and the address and bank fields should fill themselves; this adds
both before the party and item screens that use them.
- CodeMask ({seq:0000}, {anno}, {categoria}) and code_sequences (migration
015): one sequence per rule, year and category, taken under a lock in the
transaction that saves the record, skipping codes written by hand
- CodeRuleService: rules in company settings with the masks of SPEC 11.12,
validation, preview of the next code, manual code allowed or not
- AutoFillService: municipality from postal code and back, personal tax code,
VIES, bank and BIC from the IBAN, delivery date on working days, options
that can be switched off (the ECB job honours its option)
- IBankDirectory.ReadIban gives ABI and CAB even without the ABI list; the
Italian pack now registers the directory
- Company preferences page (mockup 074) at /tabelle/preferenze, in the menu
- aria-checked now renders true/false on switch rows and profile radios
- ADR 0027, wiki, CHANGELOG, STATUS, DATA-MODEL
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
213 lines
11 KiB
C#
213 lines
11 KiB
C#
using System.Globalization;
|
|
using Khaemhat.Application.Audit;
|
|
using Khaemhat.Application.Jobs;
|
|
using Khaemhat.Application.Querying;
|
|
using Khaemhat.Application.Security;
|
|
using Khaemhat.Core.Instance;
|
|
using Khaemhat.Core.Tables;
|
|
using Khaemhat.Data;
|
|
using Khaemhat.Data.Companies;
|
|
using Khaemhat.Data.Querying;
|
|
using Khaemhat.Infrastructure.Http;
|
|
|
|
namespace Khaemhat.Application.Tables;
|
|
|
|
/// <summary>
|
|
/// The exchange rates of a company (SPEC §11.1): the ECB reference rates loaded by <see cref="EcbRatesJob"/> for the
|
|
/// currencies of the table, and rates typed by hand. The rate of a day is the last one on or before it.
|
|
/// </summary>
|
|
public sealed class ExchangeRateService
|
|
{
|
|
/// <summary>The source of the ECB rates.</summary>
|
|
public const string EcbSource = "ECB";
|
|
|
|
/// <summary>The source of the rates typed by hand.</summary>
|
|
public const string ManualSource = "MANUAL";
|
|
|
|
/// <summary>Error: the rate is not positive.</summary>
|
|
public const string RateInvalid = "tables.exchange-rate.invalid";
|
|
|
|
/// <summary>The fields of the grid.</summary>
|
|
public static readonly ListFields<ExchangeRate> Fields = new ListFields<ExchangeRate>()
|
|
.Add("currency", x => x.CurrencyCode, searchable: true)
|
|
.Add("date", x => x.RateDate)
|
|
.Add("rate", x => x.Rate)
|
|
.Add("source", x => x.Source)
|
|
.OrderByDefault(new ListSort("date", Descending: true), new ListSort("currency"));
|
|
|
|
private readonly IUnitOfWorkFactory _factory;
|
|
private readonly PermissionService _permissions;
|
|
private readonly AuditTrail _audit;
|
|
|
|
/// <summary>Creates the service.</summary>
|
|
/// <param name="factory">Opens the company databases.</param>
|
|
/// <param name="permissions">Checks permissions.</param>
|
|
/// <param name="audit">Writes the history.</param>
|
|
public ExchangeRateService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(factory);
|
|
ArgumentNullException.ThrowIfNull(permissions);
|
|
ArgumentNullException.ThrowIfNull(audit);
|
|
_factory = factory;
|
|
_permissions = permissions;
|
|
_audit = audit;
|
|
}
|
|
|
|
/// <summary>A page of rates.</summary>
|
|
/// <param name="actor">Who reads.</param>
|
|
/// <param name="companyCode">The company.</param>
|
|
/// <param name="query">The request.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>The page.</returns>
|
|
public async Task<ListPage<ExchangeRate>> ListAsync(Actor actor, string companyCode, ListQuery query, CancellationToken cancellationToken = default)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(query);
|
|
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);
|
|
var repository = uow.Repository<ExchangeRate, long>();
|
|
var filtered = Fields.Apply(Query.For<ExchangeRate>(), query);
|
|
var page = await repository.ListAsync(filtered, cancellationToken).ConfigureAwait(false);
|
|
return new ListPage<ExchangeRate>(page.Items, page.TotalCount, new Dictionary<string, decimal>());
|
|
}
|
|
|
|
/// <summary>The rate of a currency on a day: the last one on or before it; 1 for the euro.</summary>
|
|
/// <param name="companyCode">The company.</param>
|
|
/// <param name="currency">The currency.</param>
|
|
/// <param name="date">The day.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>The rate, or <see langword="null"/> when none is known.</returns>
|
|
public async Task<ExchangeRate?> RateOnAsync(string companyCode, string currency, DateOnly date, CancellationToken cancellationToken = default)
|
|
{
|
|
ArgumentException.ThrowIfNullOrWhiteSpace(currency);
|
|
var code = currency.Trim().ToUpperInvariant();
|
|
if (code == "EUR")
|
|
{
|
|
return new ExchangeRate { CurrencyCode = code, RateDate = date, Rate = 1m, Source = EcbSource };
|
|
}
|
|
|
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(CompanyCodes.Normalize(companyCode)), cancellationToken).ConfigureAwait(false);
|
|
return await uow.Repository<ExchangeRate, long>()
|
|
.FindAsync(Query.For<ExchangeRate>().Where(x => x.CurrencyCode == code && x.RateDate <= date).OrderByDescending(x => x.RateDate), cancellationToken)
|
|
.ConfigureAwait(false);
|
|
}
|
|
|
|
/// <summary>Saves a rate typed by hand (replacing the one of the same day).</summary>
|
|
/// <param name="actor">Who saves.</param>
|
|
/// <param name="companyCode">The company.</param>
|
|
/// <param name="currency">The currency.</param>
|
|
/// <param name="date">The day.</param>
|
|
/// <param name="rate">Units of the currency for one euro.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>The rate.</returns>
|
|
/// <exception cref="ValidationFailedException">The rate is not positive or the currency is not in the table.</exception>
|
|
public async Task<ExchangeRate> SetManualAsync(Actor actor, string companyCode, string currency, DateOnly date, decimal rate, CancellationToken cancellationToken = default)
|
|
{
|
|
ArgumentException.ThrowIfNullOrWhiteSpace(currency);
|
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.WritePermission, cancellationToken).ConfigureAwait(false);
|
|
var code = currency.Trim().ToUpperInvariant();
|
|
if (rate <= 0)
|
|
{
|
|
throw new ValidationFailedException([nameof(ExchangeRate.Rate) + ":" + RateInvalid]);
|
|
}
|
|
|
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
|
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
|
if (await uow.Repository<Currency, long>().CountAsync(Query.For<Currency>().Where(x => x.Code == code), cancellationToken).ConfigureAwait(false) == 0)
|
|
{
|
|
throw new ValidationFailedException([nameof(ExchangeRate.CurrencyCode) + ":" + TableCatalog.ReferenceMissing]);
|
|
}
|
|
|
|
var saved = await UpsertAsync(uow, new ExchangeRate { CurrencyCode = code, RateDate = date, Rate = rate, Source = ManualSource }, actor.UserName, cancellationToken).ConfigureAwait(false);
|
|
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
|
return saved;
|
|
}
|
|
|
|
/// <summary>Stores ECB rates for the currencies of a company's table (manual rates of the same day are kept).</summary>
|
|
/// <param name="companyCode">The company.</param>
|
|
/// <param name="rates">The ECB rates.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>How many rates were added or changed.</returns>
|
|
public async Task<int> StoreEcbAsync(string companyCode, IReadOnlyList<EcbRate> rates, CancellationToken cancellationToken = default)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(rates);
|
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(CompanyCodes.Normalize(companyCode)), cancellationToken).ConfigureAwait(false);
|
|
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
|
var currencies = (await uow.Repository<Currency, long>().ListAsync(Query.For<Currency>().Where(x => !x.Disabled), cancellationToken).ConfigureAwait(false)).Items
|
|
.Select(c => c.Code)
|
|
.ToHashSet(StringComparer.Ordinal);
|
|
var changed = 0;
|
|
foreach (var rate in rates.Where(r => currencies.Contains(r.Currency)))
|
|
{
|
|
var existing = await FindAsync(uow, rate.Currency, rate.Date, cancellationToken).ConfigureAwait(false);
|
|
if (existing is { Source: ManualSource } || existing?.Rate == rate.Rate)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
await UpsertAsync(uow, new ExchangeRate { CurrencyCode = rate.Currency, RateDate = rate.Date, Rate = rate.Rate, Source = EcbSource }, "system", cancellationToken)
|
|
.ConfigureAwait(false);
|
|
changed++;
|
|
}
|
|
|
|
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
|
return changed;
|
|
}
|
|
|
|
private static Task<ExchangeRate?> FindAsync(IUnitOfWork uow, string currency, DateOnly date, CancellationToken cancellationToken) =>
|
|
uow.Repository<ExchangeRate, long>().FindAsync(Query.For<ExchangeRate>().Where(x => x.CurrencyCode == currency && x.RateDate == date), cancellationToken);
|
|
|
|
private async Task<ExchangeRate> UpsertAsync(IUnitOfWork uow, ExchangeRate rate, string userName, CancellationToken cancellationToken)
|
|
{
|
|
var repository = uow.Repository<ExchangeRate, long>();
|
|
var existing = await FindAsync(uow, rate.CurrencyCode, rate.RateDate, cancellationToken).ConfigureAwait(false);
|
|
if (existing is null)
|
|
{
|
|
rate.Id = await repository.InsertAsync(rate, cancellationToken).ConfigureAwait(false);
|
|
await _audit.RecordAsync(uow, AuditAction.Insert, rate.Id, null, rate, userName, cancellationToken).ConfigureAwait(false);
|
|
return rate;
|
|
}
|
|
|
|
var before = new ExchangeRate { Id = existing.Id, CurrencyCode = existing.CurrencyCode, RateDate = existing.RateDate, Rate = existing.Rate, Source = existing.Source };
|
|
existing.Rate = rate.Rate;
|
|
existing.Source = rate.Source;
|
|
await repository.UpdateAsync(existing, cancellationToken).ConfigureAwait(false);
|
|
await _audit.RecordAsync(uow, AuditAction.Update, existing.Id, before, existing, userName, cancellationToken).ConfigureAwait(false);
|
|
return existing;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Loads the ECB reference rates into every active company (SPEC §11.12 "cambi BCE"), on working days; a company that
|
|
/// switched the option off in its preferences is skipped.
|
|
/// </summary>
|
|
/// <param name="client">The ECB client.</param>
|
|
/// <param name="rates">The exchange rates.</param>
|
|
/// <param name="companies">The companies.</param>
|
|
/// <param name="autoFill">The automatic filling options.</param>
|
|
public sealed class EcbRatesJob(EcbRatesClient client, ExchangeRateService rates, ICompanyRegistry companies, AutoFillService autoFill) : IScheduledJob
|
|
{
|
|
/// <summary>The job type.</summary>
|
|
public const string JobType = "tables.ecb-rates";
|
|
|
|
/// <inheritdoc />
|
|
public string Type => JobType;
|
|
|
|
/// <inheritdoc />
|
|
public async Task<string?> RunAsync(JobContext context, CancellationToken cancellationToken)
|
|
{
|
|
// The 90-day file also fills the days missed while the instance was stopped.
|
|
var downloaded = await client.GetAsync(last90Days: true, cancellationToken).ConfigureAwait(false);
|
|
var changed = 0;
|
|
foreach (var company in await companies.ListAsync(cancellationToken).ConfigureAwait(false))
|
|
{
|
|
if (company.Status is CompanyStatus.Active && await autoFill.IsOnAsync(company.Code, AutoFillService.EcbRates, cancellationToken).ConfigureAwait(false))
|
|
{
|
|
changed += await rates.StoreEcbAsync(company.Code, downloaded, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
}
|
|
|
|
var last = downloaded.Max(r => r.Date);
|
|
return string.Create(CultureInfo.InvariantCulture, $"Cambi BCE del {last:dd/MM/yyyy}: {changed} valori aggiornati.");
|
|
}
|
|
}
|