using Khaemhat.Application.Configuration;
using Khaemhat.Core.Caching;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.Tables;
///
/// The fiscal pack of each company: the one of company_profile.country, or of KHAEMHAT_COUNTRY while the
/// profile is missing (ADR 0025). The country is cached per company.
///
public sealed class CompanyFiscalContext
{
private static readonly TimeSpan CacheTime = TimeSpan.FromHours(1);
private readonly IUnitOfWorkFactory _factory;
private readonly FiscalPackCatalog _packs;
private readonly ICacheProvider _cache;
private readonly string _defaultCountry;
/// Creates the context.
/// Opens the company databases.
/// The fiscal packs.
/// The cache.
/// The instance options (KHAEMHAT_COUNTRY).
public CompanyFiscalContext(IUnitOfWorkFactory factory, FiscalPackCatalog packs, ICacheProvider cache, KhaemhatOptions options)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(packs);
ArgumentNullException.ThrowIfNull(cache);
ArgumentNullException.ThrowIfNull(options);
_factory = factory;
_packs = packs;
_cache = cache;
_defaultCountry = options.Country;
}
/// The country given to new companies.
public string DefaultCountry => _defaultCountry;
/// The pack of the instance's default country.
public IFiscalPack DefaultPack => _packs.ForCountry(_defaultCountry);
/// The fiscal pack of a company.
/// The company.
/// Cancellation.
/// The pack.
public async Task PackOfAsync(string companyCode, CancellationToken cancellationToken = default)
{
var company = CompanyCodes.Normalize(companyCode);
var country = await _cache.GetOrCreateAsync(
CacheKeys.For(company, "fiscal", "country"),
async ct =>
{
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), ct).ConfigureAwait(false);
var profile = await uow.Repository().FindAsync(Query.For(), ct).ConfigureAwait(false);
return profile?.Country ?? _defaultCountry;
},
CacheTime,
cancellationToken).ConfigureAwait(false);
return _packs.TryForCountry(country, out var pack) ? pack : DefaultPack;
}
/// Forgets the cached country of a company (after the profile changes).
/// The company.
/// Cancellation.
/// A task.
public ValueTask InvalidateAsync(string companyCode, CancellationToken cancellationToken = default) =>
_cache.PublishInvalidationAsync(CacheKeys.Prefix(CompanyCodes.Normalize(companyCode), "fiscal"), cancellationToken);
}