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; /// /// The exchange rates of a company (SPEC §11.1): the ECB reference rates loaded by for the /// currencies of the table, and rates typed by hand. The rate of a day is the last one on or before it. /// public sealed class ExchangeRateService { /// The source of the ECB rates. public const string EcbSource = "ECB"; /// The source of the rates typed by hand. public const string ManualSource = "MANUAL"; /// Error: the rate is not positive. public const string RateInvalid = "tables.exchange-rate.invalid"; /// The fields of the grid. public static readonly ListFields Fields = new ListFields() .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; /// Creates the service. /// Opens the company databases. /// Checks permissions. /// Writes the history. public ExchangeRateService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit) { ArgumentNullException.ThrowIfNull(factory); ArgumentNullException.ThrowIfNull(permissions); ArgumentNullException.ThrowIfNull(audit); _factory = factory; _permissions = permissions; _audit = audit; } /// A page of rates. /// Who reads. /// The company. /// The request. /// Cancellation. /// The page. public async Task> 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(); var filtered = Fields.Apply(Query.For(), query); var page = await repository.ListAsync(filtered, cancellationToken).ConfigureAwait(false); return new ListPage(page.Items, page.TotalCount, new Dictionary()); } /// The rate of a currency on a day: the last one on or before it; 1 for the euro. /// The company. /// The currency. /// The day. /// Cancellation. /// The rate, or when none is known. public async Task 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() .FindAsync(Query.For().Where(x => x.CurrencyCode == code && x.RateDate <= date).OrderByDescending(x => x.RateDate), cancellationToken) .ConfigureAwait(false); } /// Saves a rate typed by hand (replacing the one of the same day). /// Who saves. /// The company. /// The currency. /// The day. /// Units of the currency for one euro. /// Cancellation. /// The rate. /// The rate is not positive or the currency is not in the table. public async Task 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().CountAsync(Query.For().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; } /// Stores ECB rates for the currencies of a company's table (manual rates of the same day are kept). /// The company. /// The ECB rates. /// Cancellation. /// How many rates were added or changed. public async Task StoreEcbAsync(string companyCode, IReadOnlyList 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().ListAsync(Query.For().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 FindAsync(IUnitOfWork uow, string currency, DateOnly date, CancellationToken cancellationToken) => uow.Repository().FindAsync(Query.For().Where(x => x.CurrencyCode == currency && x.RateDate == date), cancellationToken); private async Task UpsertAsync(IUnitOfWork uow, ExchangeRate rate, string userName, CancellationToken cancellationToken) { var repository = uow.Repository(); 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; } } /// /// 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. /// /// The ECB client. /// The exchange rates. /// The companies. /// The automatic filling options. public sealed class EcbRatesJob(EcbRatesClient client, ExchangeRateService rates, ICompanyRegistry companies, AutoFillService autoFill) : IScheduledJob { /// The job type. public const string JobType = "tables.ecb-rates"; /// public string Type => JobType; /// public async Task 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."); } }