Adds the company tables of SPEC 11.1 behind one generic service so that every table gets the same rules, history, cache and CSV import/export, plus the company profile, fiscal years with monthly lock and the base-data seeder. - 26 coded tables, exchange rates, company profile, fiscal years and periods: entities, maps and migrations 010-014 - TableService + TableCatalog: unique codes, per-table rules (VAT codes are checked by the fiscal pack), delete or disable when in use, single default, CSV export/import all-or-nothing, cache with cross-instance invalidation - CompanyProfileService (Italian identifiers through the pack), FiscalYearService with the date check used by every dated record - EcbRatesClient and the ECB rates system task; CsvReader - ISeeder/SeedRunner with the data version in company settings; base tables from the pack (IBaseTablesTemplate) and an embedded ISO country list Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
25f8a7ad30
commit
34e196424f
33 files changed
+6049
-3
No files matched your search
@@ -0,0 +1,208 @@
|
||||
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.</summary>
|
||||
/// <param name="client">The ECB client.</param>
|
||||
/// <param name="rates">The exchange rates.</param>
|
||||
/// <param name="companies">The companies.</param>
|
||||
public sealed class EcbRatesJob(EcbRatesClient client, ExchangeRateService rates, ICompanyRegistry companies) : 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)
|
||||
{
|
||||
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.");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user