feat: company tables, profile, fiscal years and base data (#38, #39, #45)

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:
Alby96andClaude Opus 5.5 committed 2026-11-11 22:33:37 +01:00
1 parent 25f8a7ad30
commit 34e196424f
33 files changed
+6049 -3

No files matched your search

@@ -0,0 +1,72 @@
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;
/// <summary>
/// The fiscal pack of each company: the one of <c>company_profile.country</c>, or of <c>KHAEMHAT_COUNTRY</c> while the
/// profile is missing (ADR 0025). The country is cached per company.
/// </summary>
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;
/// <summary>Creates the context.</summary>
/// <param name="factory">Opens the company databases.</param>
/// <param name="packs">The fiscal packs.</param>
/// <param name="cache">The cache.</param>
/// <param name="options">The instance options (<c>KHAEMHAT_COUNTRY</c>).</param>
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;
}
/// <summary>The country given to new companies.</summary>
public string DefaultCountry => _defaultCountry;
/// <summary>The pack of the instance's default country.</summary>
public IFiscalPack DefaultPack => _packs.ForCountry(_defaultCountry);
/// <summary>The fiscal pack of a company.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The pack.</returns>
public async Task<IFiscalPack> 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<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), ct).ConfigureAwait(false);
return profile?.Country ?? _defaultCountry;
},
CacheTime,
cancellationToken).ConfigureAwait(false);
return _packs.TryForCountry(country, out var pack) ? pack : DefaultPack;
}
/// <summary>Forgets the cached country of a company (after the profile changes).</summary>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public ValueTask InvalidateAsync(string companyCode, CancellationToken cancellationToken = default) =>
_cache.PublishInvalidationAsync(CacheKeys.Prefix(CompanyCodes.Normalize(companyCode), "fiscal"), cancellationToken);
}
@@ -0,0 +1,273 @@
using System.Text.RegularExpressions;
using Khaemhat.Application.Audit;
using Khaemhat.Application.Security;
using Khaemhat.Core.Tables;
using Khaemhat.Core.Tax;
using Khaemhat.Core.Validation;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.Tables;
/// <summary>
/// The company profile (SPEC §11.1, mockup 075): one row per company, created on the first save. The country chooses
/// the fiscal pack; changing it is refused once documents exist (from M5).
/// </summary>
public sealed partial class CompanyProfileService
{
/// <summary>Error: the name is missing.</summary>
public const string NameRequired = "profile.name.required";
/// <summary>Error: no fiscal pack for the country.</summary>
public const string CountryUnknown = "profile.country.unknown";
/// <summary>Error: the month is outside 1-12.</summary>
public const string MonthRange = "profile.month.range";
/// <summary>Error: a code that must be two letters.</summary>
public const string TwoLettersRequired = "profile.two-letters";
/// <summary>Error: the tax code is not valid.</summary>
public const string TaxCodeInvalid = "profile.tax-code.invalid";
/// <summary>Error: the recipient code is not seven characters.</summary>
public const string RecipientCodeInvalid = "profile.recipient-code.invalid";
/// <summary>Error: a value outside the list (<c>SU/SM</c>, <c>LS/LN</c>).</summary>
public const string ValueInvalid = "profile.value.invalid";
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly AuditTrail _audit;
private readonly CompanyFiscalContext _fiscal;
private readonly FiscalPackCatalog _packs;
/// <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>
/// <param name="fiscal">The fiscal pack of each company.</param>
/// <param name="packs">The installed fiscal packs.</param>
public CompanyProfileService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, CompanyFiscalContext fiscal, FiscalPackCatalog packs)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(audit);
ArgumentNullException.ThrowIfNull(fiscal);
ArgumentNullException.ThrowIfNull(packs);
_factory = factory;
_permissions = permissions;
_audit = audit;
_fiscal = fiscal;
_packs = packs;
}
/// <summary>The profile, or a new one with the defaults of the instance when the company has none yet.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The profile (<see cref="Core.Entities.Entity{TKey}.Id"/> 0 when new).</returns>
public async Task<CompanyProfile> GetAsync(Actor actor, string companyCode, 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 LoadAsync(uow, cancellationToken).ConfigureAwait(false) ?? NewProfile(company);
}
/// <summary>Checks a profile without saving it.</summary>
/// <param name="profile">The profile (normalized in place).</param>
/// <returns>Errors and warnings by field.</returns>
public IReadOnlyList<TableProblem> Validate(CompanyProfile profile)
{
ArgumentNullException.ThrowIfNull(profile);
var problems = new List<TableProblem>();
profile.LegalName = profile.LegalName.Trim();
profile.Country = profile.Country.Trim().ToUpperInvariant();
if (profile.LegalName.Length == 0)
{
problems.Add(new(nameof(CompanyProfile.LegalName), NameRequired));
}
if (!_packs.TryForCountry(profile.Country, out var pack))
{
problems.Add(new(nameof(CompanyProfile.Country), CountryUnknown));
pack = _fiscal.DefaultPack;
}
if (pack.GetFeature<ITaxIdentifierRules>() is { } rules)
{
if (!string.IsNullOrWhiteSpace(profile.VatNumber))
{
profile.VatNumber = rules.NormalizeVatNumber(profile.VatNumber);
if (!rules.IsValidVatNumber(profile.VatNumber))
{
problems.Add(new(nameof(CompanyProfile.VatNumber), TableCatalog.VatNumberInvalid));
}
}
if (!string.IsNullOrWhiteSpace(profile.TaxCode))
{
profile.TaxCode = profile.TaxCode.Trim().ToUpperInvariant();
if (!rules.IsValidTaxCode(profile.TaxCode))
{
problems.Add(new(nameof(CompanyProfile.TaxCode), TaxCodeInvalid));
}
}
}
if (pack.GetFeature<IEInvoiceFormat>() is { } format && format.TaxRegimes.Find(profile.TaxRegime) is not { Obsolete: false })
{
problems.Add(new(nameof(CompanyProfile.TaxRegime), TableCatalog.NotInCodeList));
}
if (!string.IsNullOrWhiteSpace(profile.RecipientCode))
{
profile.RecipientCode = profile.RecipientCode.Trim().ToUpperInvariant();
if (!RecipientCode().IsMatch(profile.RecipientCode))
{
problems.Add(new(nameof(CompanyProfile.RecipientCode), RecipientCodeInvalid));
}
}
CheckTwoLetters(profile.ProvinceCode, nameof(CompanyProfile.ProvinceCode), problems, v => profile.ProvinceCode = v);
CheckTwoLetters(profile.ReaOffice, nameof(CompanyProfile.ReaOffice), problems, v => profile.ReaOffice = v);
CheckTwoLetters(profile.AddressCountry, nameof(CompanyProfile.AddressCountry), problems, v => profile.AddressCountry = v);
CheckTwoLetters(profile.TransmitterCountry, nameof(CompanyProfile.TransmitterCountry), problems, v => profile.TransmitterCountry = v);
if (profile.Shareholders is { Length: > 0 } shareholders && shareholders is not ("SU" or "SM"))
{
problems.Add(new(nameof(CompanyProfile.Shareholders), ValueInvalid));
}
if (profile.LiquidationStatus is { Length: > 0 } liquidation && liquidation is not ("LS" or "LN"))
{
problems.Add(new(nameof(CompanyProfile.LiquidationStatus), ValueInvalid));
}
foreach (var (value, field) in new[] { (profile.Email, nameof(CompanyProfile.Email)), (profile.Pec, nameof(CompanyProfile.Pec)) })
{
if (!string.IsNullOrWhiteSpace(value) && !EmailValidator.IsValid(value))
{
problems.Add(new(field, TableCatalog.EmailInvalid));
}
}
if (profile.ProRataPercent is < 0 or > 100)
{
problems.Add(new(nameof(CompanyProfile.ProRataPercent), TableCatalog.PercentRange));
}
if (profile.FiscalYearStartMonth is < 1 or > 12)
{
problems.Add(new(nameof(CompanyProfile.FiscalYearStartMonth), MonthRange));
}
profile.CurrencyCode = profile.CurrencyCode.Trim().ToUpperInvariant();
if (profile.CurrencyCode.Length != 3)
{
problems.Add(new(nameof(CompanyProfile.CurrencyCode), TableCatalog.CodePattern));
}
return problems;
}
/// <summary>Saves the profile (inserted the first time).</summary>
/// <param name="actor">Who saves.</param>
/// <param name="companyCode">The company.</param>
/// <param name="profile">The profile.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The saved profile.</returns>
/// <exception cref="ValidationFailedException">A rule failed (<c>Field:code</c>).</exception>
public async Task<CompanyProfile> SaveAsync(Actor actor, string companyCode, CompanyProfile profile, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(profile);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.WritePermission, cancellationToken).ConfigureAwait(false);
var errors = Validate(profile).Where(p => !p.IsWarning).Select(p => p.Field + ":" + p.Code).ToList();
if (errors.Count > 0)
{
throw new ValidationFailedException(errors);
}
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var repository = uow.Repository<CompanyProfile, long>();
var before = await LoadAsync(uow, cancellationToken).ConfigureAwait(false);
if (before is null)
{
profile.Id = await repository.InsertAsync(profile, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Insert, profile.Id, null, profile, actor.UserName, cancellationToken).ConfigureAwait(false);
}
else
{
profile.Id = before.Id;
await repository.UpdateAsync(profile, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, profile.Id, before, profile, actor.UserName, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
await _fiscal.InvalidateAsync(company, cancellationToken).ConfigureAwait(false);
return profile;
}
/// <summary>A new profile with the defaults of the instance (country from <c>KHAEMHAT_COUNTRY</c>).</summary>
/// <param name="companyName">The name proposed.</param>
/// <returns>The profile.</returns>
public CompanyProfile NewProfile(string companyName) => new()
{
LegalName = companyName,
Country = _fiscal.DefaultCountry.ToUpperInvariant(),
AddressCountry = _fiscal.DefaultCountry.ToUpperInvariant(),
CurrencyCode = "EUR",
VatPeriodicity = VatPeriodicity.Monthly,
LiquidationStatus = "LN",
};
internal static Task<CompanyProfile?> LoadAsync(IUnitOfWork uow, CancellationToken cancellationToken) =>
uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>().OrderBy(x => x.Id), cancellationToken);
private static void CheckTwoLetters(string? value, string field, List<TableProblem> problems, Action<string?> set)
{
if (string.IsNullOrWhiteSpace(value))
{
set(null);
return;
}
var upper = value.Trim().ToUpperInvariant();
set(upper);
if (upper.Length != 2 || !upper.All(char.IsAsciiLetterUpper))
{
problems.Add(new(field, TwoLettersRequired));
}
}
[GeneratedRegex("^[A-Z0-9]{6,7}$", RegexOptions.CultureInvariant)]
private static partial Regex RecipientCode();
}
/// <summary>The common access check of the company services.</summary>
internal static class CompanyGuard
{
/// <summary>Checks that the actor works in the company and has the permission.</summary>
/// <param name="permissions">The permission service.</param>
/// <param name="actor">Who acts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="permission">The permission.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The normalized company code.</returns>
public static async Task<string> DemandAsync(PermissionService permissions, Actor actor, string companyCode, string permission, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(actor);
var company = CompanyCodes.Normalize(companyCode);
if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, company, StringComparison.Ordinal))
{
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A company user works only in its own company.");
}
await permissions.DemandAsync(actor, permission, cancellationToken).ConfigureAwait(false);
return company;
}
}
@@ -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.");
}
}
@@ -0,0 +1,321 @@
using System.Globalization;
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;
/// <summary>A fiscal year with its months, as mockup 052 shows it.</summary>
/// <param name="Year">The year.</param>
/// <param name="Periods">The months, in order.</param>
public sealed record FiscalYearView(FiscalYear Year, IReadOnlyList<FiscalPeriod> Periods);
/// <summary>What a date may receive.</summary>
public enum PeriodUse
{
/// <summary>A document or entry without VAT (warehouse, quotations, orders).</summary>
NoVat = 0,
/// <summary>A document or entry with VAT: refused once the VAT of the period is settled.</summary>
Vat = 1,
}
/// <summary>Why a date is refused (or <see cref="Open"/>).</summary>
public enum PeriodState
{
/// <summary>The date is in an open period.</summary>
Open = 0,
/// <summary>No fiscal year contains the date.</summary>
NoYear = 1,
/// <summary>The year is closed or being closed.</summary>
YearClosed = 2,
/// <summary>The month is locked.</summary>
Locked = 3,
/// <summary>The VAT of the month was settled (only for <see cref="PeriodUse.Vat"/>).</summary>
Settled = 4,
}
/// <summary>
/// Fiscal years and their months (SPEC §11.1, mockup 052): creation of the next year with its twelve months, lock and
/// unlock of months, and the check that a date can receive documents and entries (<see cref="CheckAsync"/>), used by
/// every service that writes dated records. Years and months are cached per company.
/// </summary>
public sealed class FiscalYearService
{
/// <summary>Error: the date of the new year overlaps an existing year.</summary>
public const string Overlap = "fiscal.year.overlap";
/// <summary>Error: the year is closed: its months cannot change.</summary>
public const string YearClosedError = "fiscal.year.closed";
/// <summary>Error: the month cannot become open again because the VAT is settled (reopened with the settlement, M7).</summary>
public const string SettledError = "fiscal.period.settled";
/// <summary>The error code thrown by <see cref="DemandOpenAsync"/>, followed by the <see cref="PeriodState"/>.</summary>
public const string DateRefused = "fiscal.date.";
private static readonly TimeSpan CacheTime = TimeSpan.FromHours(1);
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly AuditTrail _audit;
private readonly ICacheProvider _cache;
/// <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>
/// <param name="cache">The cache.</param>
public FiscalYearService(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;
}
/// <summary>The years, newest first, with their months.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The years.</returns>
public async Task<IReadOnlyList<FiscalYearView>> ListAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.ReadPermission, cancellationToken).ConfigureAwait(false);
return [.. (await CalendarAsync(company, cancellationToken).ConfigureAwait(false)).OrderByDescending(y => y.Year.StartDate)];
}
/// <summary>
/// Creates a year with its months: after the last year, or the one containing <paramref name="day"/> when there are
/// none (starting in the month of the profile).
/// </summary>
/// <param name="actor">Who creates.</param>
/// <param name="companyCode">The company.</param>
/// <param name="day">A day of the first year, when the company has none.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new year.</returns>
public async Task<FiscalYearView> CreateNextAsync(Actor actor, string companyCode, DateOnly day, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.WritePermission, cancellationToken).ConfigureAwait(false);
FiscalYearView created;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
created = await CreateAsync(uow, day, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
await InvalidateAsync(company, cancellationToken).ConfigureAwait(false);
return created;
}
/// <summary>Locks or unlocks a month (unlocking a settled month is refused).</summary>
/// <param name="actor">Who changes it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="periodId">The month.</param>
/// <param name="locked">Lock or unlock.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The month.</returns>
/// <exception cref="ValidationFailedException">The year is closed, or the month is settled.</exception>
public async Task<FiscalPeriod> SetLockedAsync(Actor actor, string companyCode, long periodId, bool locked, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.WritePermission, cancellationToken).ConfigureAwait(false);
FiscalPeriod period;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var periods = uow.Repository<FiscalPeriod, long>();
period = await periods.GetAsync(periodId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TableService.NotFound);
var year = await uow.Repository<FiscalYear, long>().GetAsync(period.FiscalYearId, cancellationToken).ConfigureAwait(false)
?? throw new KeyNotFoundException(TableService.NotFound);
if (year.Status != FiscalYearStatus.Open)
{
throw new ValidationFailedException([YearClosedError]);
}
if (period.Status == FiscalPeriodStatus.Settled && !locked)
{
throw new ValidationFailedException([SettledError]);
}
var target = locked ? FiscalPeriodStatus.Locked : FiscalPeriodStatus.Open;
if (period.Status != target)
{
var before = Copy(period);
period.Status = target;
await periods.UpdateAsync(period, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, period.Id, before, period, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
}
await InvalidateAsync(company, cancellationToken).ConfigureAwait(false);
return period;
}
/// <summary>Whether a date can receive a document or entry.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="date">The date.</param>
/// <param name="use">With or without VAT.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The state of the date.</returns>
public async Task<PeriodState> CheckAsync(string companyCode, DateOnly date, PeriodUse use, CancellationToken cancellationToken = default)
{
var calendar = await CalendarAsync(CompanyCodes.Normalize(companyCode), cancellationToken).ConfigureAwait(false);
return StateOf(calendar, date, use);
}
/// <summary>Throws when a date cannot receive a document or entry.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="date">The date.</param>
/// <param name="use">With or without VAT.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
/// <exception cref="ValidationFailedException">The date is refused: <c>fiscal.date.locked</c> and similar.</exception>
public async Task DemandOpenAsync(string companyCode, DateOnly date, PeriodUse use, CancellationToken cancellationToken = default)
{
var state = await CheckAsync(companyCode, date, use, cancellationToken).ConfigureAwait(false);
if (state != PeriodState.Open)
{
throw new ValidationFailedException([ErrorOf(state)]);
}
}
/// <summary>The error code of a refused date, such as <c>fiscal.date.locked</c>.</summary>
/// <param name="state">The state.</param>
/// <returns>The code.</returns>
public static string ErrorOf(PeriodState state) => state switch
{
PeriodState.NoYear => DateRefused + "no-year",
PeriodState.YearClosed => DateRefused + "year-closed",
PeriodState.Locked => DateRefused + "locked",
PeriodState.Settled => DateRefused + "settled",
_ => DateRefused + "open",
};
/// <summary>The state of a date in a calendar.</summary>
/// <param name="calendar">The years with their months.</param>
/// <param name="date">The date.</param>
/// <param name="use">With or without VAT.</param>
/// <returns>The state.</returns>
public static PeriodState StateOf(IEnumerable<FiscalYearView> calendar, DateOnly date, PeriodUse use)
{
ArgumentNullException.ThrowIfNull(calendar);
var year = calendar.FirstOrDefault(y => y.Year.StartDate <= date && date <= y.Year.EndDate);
if (year is null)
{
return PeriodState.NoYear;
}
if (year.Year.Status != FiscalYearStatus.Open)
{
return PeriodState.YearClosed;
}
var period = year.Periods.FirstOrDefault(p => p.StartDate <= date && date <= p.EndDate);
return period?.Status switch
{
FiscalPeriodStatus.Locked => PeriodState.Locked,
FiscalPeriodStatus.Settled when use == PeriodUse.Vat => PeriodState.Settled,
_ => PeriodState.Open,
};
}
/// <summary>
/// Creates a year with its months inside a unit of work (the seeder uses it for the current year): after the last
/// year, or the one containing <paramref name="day"/> when there are none.
/// </summary>
/// <param name="uow">The company unit of work.</param>
/// <param name="day">A day of the first year.</param>
/// <param name="userName">Who creates.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new year.</returns>
internal async Task<FiscalYearView> CreateAsync(IUnitOfWork uow, DateOnly day, string userName, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(uow);
var years = uow.Repository<FiscalYear, long>();
var last = await years.FindAsync(Query.For<FiscalYear>().OrderByDescending(x => x.StartDate), cancellationToken).ConfigureAwait(false);
DateOnly start;
if (last is not null)
{
start = last.EndDate.AddDays(1);
}
else
{
var profile = await CompanyProfileService.LoadAsync(uow, cancellationToken).ConfigureAwait(false);
var month = profile?.FiscalYearStartMonth ?? 1;
start = new DateOnly(day.Month >= month ? day.Year : day.Year - 1, month, 1);
}
var end = start.AddYears(1).AddDays(-1);
if (await years.CountAsync(Query.For<FiscalYear>().Where(x => x.StartDate <= end && x.EndDate >= start), cancellationToken).ConfigureAwait(false) > 0)
{
throw new ValidationFailedException([Overlap]);
}
var year = new FiscalYear
{
Code = start.Year == end.Year
? start.Year.ToString(CultureInfo.InvariantCulture)
: string.Create(CultureInfo.InvariantCulture, $"{start.Year}/{end.Year % 100:00}"),
StartDate = start,
EndDate = end,
};
year.Id = await years.InsertAsync(year, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Insert, year.Id, null, year, userName, cancellationToken).ConfigureAwait(false);
var periods = new List<FiscalPeriod>();
var repository = uow.Repository<FiscalPeriod, long>();
for (var i = 0; i < 12; i++)
{
var first = start.AddMonths(i);
var period = new FiscalPeriod { FiscalYearId = year.Id, Number = i + 1, StartDate = first, EndDate = first.AddMonths(1).AddDays(-1) };
period.Id = await repository.InsertAsync(period, cancellationToken).ConfigureAwait(false);
periods.Add(period);
}
return new FiscalYearView(year, periods);
}
/// <summary>Forgets the cached calendar of a company.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public ValueTask InvalidateAsync(string companyCode, CancellationToken cancellationToken = default) =>
_cache.PublishInvalidationAsync(CacheKeys.For(CompanyCodes.Normalize(companyCode), "fiscal", "calendar"), cancellationToken);
private static FiscalPeriod Copy(FiscalPeriod period) => new()
{
Id = period.Id,
FiscalYearId = period.FiscalYearId,
Number = period.Number,
StartDate = period.StartDate,
EndDate = period.EndDate,
Status = period.Status,
RowVersion = period.RowVersion,
};
private async Task<IReadOnlyList<FiscalYearView>> CalendarAsync(string company, CancellationToken cancellationToken) =>
await _cache.GetOrCreateAsync<List<FiscalYearView>>(
CacheKeys.For(company, "fiscal", "calendar"),
async ct =>
{
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), ct).ConfigureAwait(false);
var years = (await uow.Repository<FiscalYear, long>().ListAsync(Query.For<FiscalYear>().OrderBy(x => x.StartDate), ct).ConfigureAwait(false)).Items;
var periods = (await uow.Repository<FiscalPeriod, long>().ListAsync(Query.For<FiscalPeriod>().OrderBy(x => x.StartDate), ct).ConfigureAwait(false)).Items;
return [.. years.Select(y => new FiscalYearView(y, [.. periods.Where(p => p.FiscalYearId == y.Id)]))];
},
CacheTime,
cancellationToken).ConfigureAwait(false);
}
@@ -0,0 +1,511 @@
using System.Globalization;
using System.Text.RegularExpressions;
using Khaemhat.Core.Tables;
using Khaemhat.Core.Validation;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.Tables;
/// <summary>
/// The company tables of SPEC §11.1 handled by <see cref="TableService"/>, each with its rules. Keys are in English
/// (<c>tax-codes</c>); the interface gives them Italian addresses and names through the resources.
/// </summary>
public sealed partial class TableCatalog
{
/// <summary>Error: a percentage outside 0-100.</summary>
public const string PercentRange = "tables.percent.range";
/// <summary>Error: the end of validity is before the start.</summary>
public const string ValidityOrder = "tables.validity.order";
/// <summary>Error: the code does not follow the pattern of the table.</summary>
public const string CodePattern = "tables.code.pattern";
/// <summary>Error: a value not in the fiscal pack's code list.</summary>
public const string NotInCodeList = "tables.code-list.unknown";
/// <summary>Warning: a value that the code list marks obsolete.</summary>
public const string ObsoleteInCodeList = "tables.code-list.obsolete";
/// <summary>Error: decimals outside the allowed range.</summary>
public const string DecimalsRange = "tables.decimals.range";
/// <summary>Error: the IBAN is not valid.</summary>
public const string IbanInvalid = "tables.iban.invalid";
/// <summary>Error: the BIC is not valid.</summary>
public const string BicInvalid = "tables.bic.invalid";
/// <summary>Error: the e-mail address is not valid.</summary>
public const string EmailInvalid = "tables.email.invalid";
/// <summary>Error: the VAT number is not valid.</summary>
public const string VatNumberInvalid = "tables.vat-number.invalid";
/// <summary>Error: the parent does not exist, is the row itself or is too deep.</summary>
public const string ParentInvalid = "tables.parent.invalid";
/// <summary>Error: a referenced row does not exist.</summary>
public const string ReferenceMissing = "tables.reference.missing";
/// <summary>Error: the discount formula cannot be read.</summary>
public const string FormulaInvalid = "tables.discount.formula";
/// <summary>Error: the numerator format has no <c>{number}</c>.</summary>
public const string FormatInvalid = "tables.numerator.format";
/// <summary>Error: the year is outside 2000-2100.</summary>
public const string YearRange = "tables.year.range";
/// <summary>Error: the last number is negative.</summary>
public const string NumberRange = "tables.number.range";
/// <summary>Error: a transfer reason must not change quantities by itself.</summary>
public const string TransferEffect = "tables.inventory-reason.transfer";
/// <summary>The maximum depth of item categories.</summary>
public const int MaxCategoryLevel = 3;
private readonly Dictionary<Type, TableDefinition> _byType = [];
private readonly Dictionary<string, TableDefinition> _byKey = new(StringComparer.Ordinal);
/// <summary>Creates the catalog.</summary>
public TableCatalog()
{
Add(new TableDefinition<Country>("countries", "countries") { CodeLength = 2 }
.Field("eu", x => x.EuMember)
.Rule((x, c) => Pattern(x.Code, TwoLetters(), c))
.Rule((x, c) =>
{
if (x.VatPrefix is { Length: > 0 } && !TwoLetters().IsMatch(x.VatPrefix))
{
c.Error(nameof(Country.VatPrefix), CodePattern);
}
}));
Add(new TableDefinition<Province>("provinces", "provinces") { CodeLength = 2 }
.Field("region", x => x.Region, searchable: true)
.Rule((x, c) => Pattern(x.Code, TwoLetters(), c)));
Add(new TableDefinition<Municipality>("municipalities", "municipalities") { CodeLength = 4 }
.Field("province", x => x.ProvinceCode, searchable: true)
.Field("postal-codes", x => x.PostalCodes, searchable: true)
.Rule((x, c) => Pattern(x.Code, CadastralCode(), c))
.Rule((x, c) =>
{
x.ProvinceCode = x.ProvinceCode.Trim().ToUpperInvariant();
if (!TwoLetters().IsMatch(x.ProvinceCode))
{
c.Error(nameof(Municipality.ProvinceCode), CodePattern);
}
}));
Add(new TableDefinition<Currency>("currencies", "currencies") { CodeLength = 3 }
.Rule((x, c) => Pattern(x.Code, ThreeLetters(), c))
.Rule((x, c) => Decimals(x.Decimals, 0, 4, nameof(Currency.Decimals), c)));
Add(new TableDefinition<UnitOfMeasure>("units", "units_of_measure")
.Rule((x, c) => Decimals(x.Decimals, 0, 6, nameof(UnitOfMeasure.Decimals), c)));
Add(new TableDefinition<TaxCode>("tax-codes", "tax_codes")
{
Complete = (x, pack) =>
{
x.Nature = string.IsNullOrWhiteSpace(x.Nature) ? null : x.Nature.Trim().ToUpperInvariant();
x.Kind = pack.TaxCodes.KindOf(x.Rate, x.Nature);
},
}
.Field("rate", x => x.Rate)
.Field("nature", x => x.Nature, searchable: true)
.Field("kind", x => x.Kind)
.Rule((x, c) =>
{
var definition = new TaxCodeDefinition(x.Code, x.Description, x.Rate, x.Nature, x.Exigibility, x.NonDeductiblePercent, x.LegalReference);
foreach (var problem in c.Pack.TaxCodes.Validate(definition))
{
if (problem.Severity == FiscalProblemSeverity.Error)
{
c.Error(problem.Field, problem.Code);
}
else
{
c.Warning(problem.Field, problem.Code);
}
}
Validity(x.ValidFrom, x.ValidTo, nameof(TaxCode.ValidTo), c);
}));
Add(new TableDefinition<PaymentMethod>("payment-methods", "payment_methods")
.Field("einvoice", x => x.EInvoiceCode)
.Rule((x, c) => InCodeList(x.EInvoiceCode, c.Pack.GetFeature<IEInvoiceFormat>()?.PaymentMethods, nameof(PaymentMethod.EInvoiceCode), c)));
Add(new TableDefinition<PaymentTerm>("payment-terms", "payment_terms")
.Field("condition", x => x.Condition)
.Rule((x, c) => InCodeList(x.Condition, c.Pack.GetFeature<IEInvoiceFormat>()?.PaymentConditions, nameof(PaymentTerm.Condition), c))
.Rule(async (x, c, ct) =>
{
if (x.PaymentMethodId is { } id && await c.GetAsync<PaymentMethod>(id, ct).ConfigureAwait(false) is null)
{
c.Error(nameof(PaymentTerm.PaymentMethodId), ReferenceMissing);
}
}));
Add(new TableDefinition<BankAccount>("bank-accounts", "bank_accounts") { SingleDefault = x => x.IsDefault }
.Field("iban", x => x.Iban, searchable: true)
.Field("default", x => x.IsDefault)
.Rule((x, c) =>
{
if (!string.IsNullOrWhiteSpace(x.Iban))
{
x.Iban = IbanValidator.Normalize(x.Iban);
if (!IbanValidator.IsValid(x.Iban))
{
c.Error(nameof(BankAccount.Iban), IbanInvalid);
}
}
else
{
x.Iban = null;
}
if (!string.IsNullOrWhiteSpace(x.Bic))
{
x.Bic = x.Bic.Trim().ToUpperInvariant();
if (!Bic().IsMatch(x.Bic))
{
c.Error(nameof(BankAccount.Bic), BicInvalid);
}
}
}));
Add(new TableDefinition<Salesperson>("salespeople", "salespeople")
.Field("commission", x => x.CommissionPercent)
.Rule((x, c) =>
{
Percent(x.CommissionPercent, nameof(Salesperson.CommissionPercent), c);
Email(x.Email, nameof(Salesperson.Email), c);
}));
Add(new TableDefinition<Carrier>("carriers", "carriers")
.Field("vat-number", x => x.VatNumber, searchable: true)
.Rule((x, c) =>
{
Email(x.Email, nameof(Carrier.Email), c);
if (!string.IsNullOrWhiteSpace(x.VatNumber) && c.Pack.GetFeature<ITaxIdentifierRules>() is { } rules)
{
x.VatNumber = rules.NormalizeVatNumber(x.VatNumber);
if (!rules.IsValidVatNumber(x.VatNumber))
{
c.Error(nameof(Carrier.VatNumber), VatNumberInvalid);
}
}
}));
Add(new TableDefinition<ShippingTerm>("shipping-terms", "shipping_terms"));
Add(new TableDefinition<TransportMean>("transport-means", "transport_means"));
Add(new TableDefinition<GoodsAppearance>("goods-appearances", "goods_appearances"));
Add(new TableDefinition<DeliveryTerm>("delivery-terms", "delivery_terms"));
Add(new TableDefinition<TransportReason>("transport-reasons", "transport_reasons"));
Add(new TableDefinition<InventoryReason>("inventory-reasons", "inventory_reasons")
.Field("effect", x => x.Effect)
.Rule((x, c) =>
{
if (x.IsTransfer && x.Effect != StockEffect.None)
{
c.Error(nameof(InventoryReason.Effect), TransferEffect);
}
}));
Add(new TableDefinition<Warehouse>("warehouses", "warehouses") { SingleDefault = x => x.IsDefault }
.Field("default", x => x.IsDefault));
Add(new TableDefinition<ItemCategory>("item-categories", "item_categories") { CodeLength = 20 }
.Field("level", x => x.Level)
.Rule(async (x, c, ct) =>
{
x.Level = 1;
if (x.ParentId is not { } parentId)
{
return;
}
var parent = parentId == x.Id ? null : await c.GetAsync<ItemCategory>(parentId, ct).ConfigureAwait(false);
if (parent is null || parent.Level >= MaxCategoryLevel)
{
c.Error(nameof(ItemCategory.ParentId), ParentInvalid);
return;
}
x.Level = parent.Level + 1;
}));
Add(new TableDefinition<PartyCategory>("party-categories", "party_categories"));
Add(new TableDefinition<PriceList>("price-lists", "price_lists")
.Field("currency", x => x.CurrencyCode)
.Rule(async (x, c, ct) =>
{
x.CurrencyCode = x.CurrencyCode.Trim().ToUpperInvariant();
if (!ThreeLetters().IsMatch(x.CurrencyCode))
{
c.Error(nameof(PriceList.CurrencyCode), CodePattern);
}
Validity(x.ValidFrom, x.ValidTo, nameof(PriceList.ValidTo), c);
if (x.RoundingStep < 0)
{
c.Error(nameof(PriceList.RoundingStep), NumberRange);
}
if (x.BasePriceListId is { } baseId && (baseId == x.Id || await c.GetAsync<PriceList>(baseId, ct).ConfigureAwait(false) is null))
{
c.Error(nameof(PriceList.BasePriceListId), ParentInvalid);
}
}));
Add(new TableDefinition<DiscountPolicy>("discount-policies", "discount_policies")
.Field("formula", x => x.Formula)
.Rule((x, c) =>
{
if (DiscountFormula.TryParse(x.Formula, out var steps))
{
x.Formula = DiscountFormula.Format(steps);
}
else
{
c.Error(nameof(DiscountPolicy.Formula), FormulaInvalid);
}
}));
Add(new TableDefinition<DocumentNumerator>("numerators", "document_numerators") { SameKey = row => x => x.Year == row.Year }
.Field("year", x => x.Year)
.Field("kind", x => x.Kind)
.Field("section", x => x.Section)
.Field("last", x => x.LastNumber)
.Rule((x, c) =>
{
if (x.Year is < 2000 or > 2100)
{
c.Error(nameof(DocumentNumerator.Year), YearRange);
}
if (x.LastNumber < 0)
{
c.Error(nameof(DocumentNumerator.LastNumber), NumberRange);
}
if (!DocumentNumberFormat.IsValid(x.Format))
{
c.Error(nameof(DocumentNumerator.Format), FormatInvalid);
}
// Invoices, credit notes and final entries are numbered without gaps (SPEC §11.1).
if (x.Kind is NumeratorKind.SalesInvoice or NumeratorKind.Journal)
{
x.GapsAllowed = false;
}
}));
Add(new TableDefinition<DocumentType>("document-types", "document_types")
.Field("kind", x => x.Kind)
.Field("einvoice", x => x.EInvoiceType)
.Rule(async (x, c, ct) =>
{
if (!string.IsNullOrWhiteSpace(x.EInvoiceType))
{
x.EInvoiceType = x.EInvoiceType.Trim().ToUpperInvariant();
InCodeList(x.EInvoiceType, c.Pack.GetFeature<IEInvoiceFormat>()?.DocumentTypes, nameof(DocumentType.EInvoiceType), c);
}
else
{
x.EInvoiceType = null;
}
if (x.NumeratorId is { } numeratorId && await c.GetAsync<DocumentNumerator>(numeratorId, ct).ConfigureAwait(false) is null)
{
c.Error(nameof(DocumentType.NumeratorId), ReferenceMissing);
}
if (x.InventoryReasonId is { } reasonId && await c.GetAsync<InventoryReason>(reasonId, ct).ConfigureAwait(false) is null)
{
c.Error(nameof(DocumentType.InventoryReasonId), ReferenceMissing);
}
}));
Add(new TableDefinition<CostCenter>("cost-centers", "cost_centers") { CodeLength = 20 }
.Rule(async (x, c, ct) =>
{
if (x.ParentId is { } parentId && (parentId == x.Id || await c.GetAsync<CostCenter>(parentId, ct).ConfigureAwait(false) is null))
{
c.Error(nameof(CostCenter.ParentId), ParentInvalid);
}
}));
Add(new TableDefinition<Job>("jobs", "jobs") { CodeLength = 20 }
.Field("status", x => x.Status)
.Rule((x, c) => Validity(x.StartDate, x.EndDate, nameof(Job.EndDate), c)));
}
/// <summary>Every table, in the order of SPEC §11.1.</summary>
public IEnumerable<TableDefinition> All => _byKey.Values;
/// <summary>The definition of an entity.</summary>
/// <typeparam name="T">The entity.</typeparam>
/// <returns>The definition.</returns>
public TableDefinition<T> Get<T>()
where T : CodedEntity, new() =>
(TableDefinition<T>)(_byType.GetValueOrDefault(typeof(T)) ?? throw new InvalidOperationException($"{typeof(T).Name} is not a company table."));
/// <summary>A definition by key.</summary>
/// <param name="key">The key, such as <c>tax-codes</c>.</param>
/// <returns>The definition, or <see langword="null"/>.</returns>
public TableDefinition? Find(string key) => _byKey.GetValueOrDefault(key);
private static void Pattern(string code, Regex pattern, TableRuleContext context)
{
if (code.Length > 0 && !pattern.IsMatch(code))
{
context.Error(nameof(CodedEntity.Code), CodePattern);
}
}
private static void Decimals(int value, int min, int max, string field, TableRuleContext context)
{
if (value < min || value > max)
{
context.Error(field, DecimalsRange);
}
}
private static void Percent(decimal value, string field, TableRuleContext context)
{
if (value is < 0 or > 100)
{
context.Error(field, PercentRange);
}
}
private static void Email(string? value, string field, TableRuleContext context)
{
if (!string.IsNullOrWhiteSpace(value) && !EmailValidator.IsValid(value))
{
context.Error(field, EmailInvalid);
}
}
private static void Validity(DateOnly? from, DateOnly? to, string field, TableRuleContext context)
{
if (from is { } start && to is { } end && end < start)
{
context.Error(field, ValidityOrder);
}
}
private static void InCodeList(string? value, CodeList? list, string field, TableRuleContext context)
{
if (list is null || string.IsNullOrEmpty(value))
{
return;
}
var entry = list.Find(value);
if (entry is null)
{
context.Error(field, NotInCodeList);
}
else if (entry.Obsolete)
{
context.Warning(field, ObsoleteInCodeList);
}
}
[GeneratedRegex("^[A-Z]{2}$", RegexOptions.CultureInvariant)]
private static partial Regex TwoLetters();
[GeneratedRegex("^[A-Z]{3}$", RegexOptions.CultureInvariant)]
private static partial Regex ThreeLetters();
[GeneratedRegex("^[A-Z][0-9]{3}$", RegexOptions.CultureInvariant)]
private static partial Regex CadastralCode();
[GeneratedRegex("^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$", RegexOptions.CultureInvariant)]
private static partial Regex Bic();
private void Add<T>(TableDefinition<T> definition)
where T : CodedEntity, new()
{
_byType.Add(typeof(T), definition);
_byKey.Add(definition.Key, definition);
}
}
/// <summary>A chain of discounts such as <c>10+5</c>: each step applies to what the previous left.</summary>
public static class DiscountFormula
{
/// <summary>Reads a formula: percentages 0-100 separated by <c>+</c>, decimal comma or point.</summary>
/// <param name="formula">The formula.</param>
/// <param name="steps">The percentages.</param>
/// <returns>Whether it could be read.</returns>
public static bool TryParse(string? formula, out IReadOnlyList<decimal> steps)
{
steps = [];
if (string.IsNullOrWhiteSpace(formula))
{
return false;
}
var result = new List<decimal>();
foreach (var part in formula.Split('+', StringSplitOptions.TrimEntries))
{
if (!decimal.TryParse(part.Replace(',', '.'), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var step) || step > 100)
{
return false;
}
result.Add(step);
}
steps = result;
return true;
}
/// <summary>Writes a formula in the Italian form, such as <c>10+5,5</c>.</summary>
/// <param name="steps">The percentages.</param>
/// <returns>The formula.</returns>
public static string Format(IEnumerable<decimal> steps) =>
string.Join('+', steps.Select(s => s.ToString("0.##", CultureInfo.GetCultureInfo("it-IT"))));
/// <summary>The single discount equal to the chain: 10+5 is 14.5%.</summary>
/// <param name="steps">The percentages.</param>
/// <returns>The equivalent percentage.</returns>
public static decimal Equivalent(IEnumerable<decimal> steps) =>
100m - (steps.Aggregate(1m, (left, step) => left * (1 - (step / 100m))) * 100m);
}
/// <summary>The format of document numbers: <c>{prefix}</c>, <c>{year}</c>, <c>{section}</c> and <c>{number}</c> (with <c>:D6</c> and similar).</summary>
public static partial class DocumentNumberFormat
{
/// <summary>Whether a format has the number and only known placeholders.</summary>
/// <param name="format">The format.</param>
/// <returns>Whether it is valid.</returns>
public static bool IsValid(string? format) =>
!string.IsNullOrWhiteSpace(format) && format.Length <= 60 && NumberPlaceholder().IsMatch(format) &&
Placeholder().Matches(format).All(m => Known().IsMatch(m.Value));
/// <summary>Writes a number with a format.</summary>
/// <param name="format">The format.</param>
/// <param name="number">The number.</param>
/// <param name="year">The year.</param>
/// <param name="prefix">The prefix.</param>
/// <param name="section">The section.</param>
/// <returns>The document number, such as <c>FV/2026/000123</c>.</returns>
public static string Apply(string format, long number, int year, string? prefix, string? section)
{
ArgumentNullException.ThrowIfNull(format);
return Placeholder().Replace(format, m =>
{
var token = m.Value[1..^1];
var colon = token.IndexOf(':', StringComparison.Ordinal);
var name = colon < 0 ? token : token[..colon];
var spec = colon < 0 ? null : token[(colon + 1)..];
return name switch
{
"number" => number.ToString(spec, CultureInfo.InvariantCulture),
"year" => year.ToString(CultureInfo.InvariantCulture),
"prefix" => prefix ?? string.Empty,
"section" => section ?? string.Empty,
_ => m.Value,
};
});
}
[GeneratedRegex(@"\{number(:D[1-9])?\}", RegexOptions.CultureInvariant)]
private static partial Regex NumberPlaceholder();
[GeneratedRegex(@"\{[^}]*\}", RegexOptions.CultureInvariant)]
private static partial Regex Placeholder();
[GeneratedRegex(@"^\{(number(:D[1-9])?|year|prefix|section)\}$", RegexOptions.CultureInvariant)]
private static partial Regex Known();
}
@@ -0,0 +1,205 @@
using System.Globalization;
using System.Linq.Expressions;
using System.Reflection;
using System.Text.RegularExpressions;
using Khaemhat.Application.Querying;
using Khaemhat.Core.Entities;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.Tables;
/// <summary>A problem found on a field of a table row: an error blocks the save, a warning does not.</summary>
/// <param name="Field">The property, such as <c>Code</c>.</param>
/// <param name="Code">The stable code, translated by the interface (<c>tables.code.required</c>).</param>
/// <param name="IsWarning">Whether it is only a warning.</param>
public sealed record TableProblem(string Field, string Code, bool IsWarning = false);
/// <summary>What the rules of a table can use: the fiscal pack of the company and the other rows.</summary>
public sealed class TableRuleContext
{
private readonly IUnitOfWork _unitOfWork;
private readonly List<TableProblem> _problems = [];
internal TableRuleContext(IUnitOfWork unitOfWork, IFiscalPack pack)
{
_unitOfWork = unitOfWork;
Pack = pack;
}
/// <summary>The fiscal pack of the company's country.</summary>
public IFiscalPack Pack { get; }
/// <summary>The problems found so far.</summary>
public IReadOnlyList<TableProblem> Problems => _problems;
/// <summary>Adds an error.</summary>
/// <param name="field">The property.</param>
/// <param name="code">The code.</param>
public void Error(string field, string code) => _problems.Add(new TableProblem(field, code));
/// <summary>Adds a warning.</summary>
/// <param name="field">The property.</param>
/// <param name="code">The code.</param>
public void Warning(string field, string code) => _problems.Add(new TableProblem(field, code, IsWarning: true));
/// <summary>Reads another row by id.</summary>
/// <typeparam name="TOther">The entity.</typeparam>
/// <param name="id">The id.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The row, or <see langword="null"/>.</returns>
public Task<TOther?> GetAsync<TOther>(long id, CancellationToken cancellationToken)
where TOther : class, IEntity<long>, new() =>
_unitOfWork.Repository<TOther, long>().GetAsync(id, cancellationToken);
/// <summary>Whether a coded row with a code exists.</summary>
/// <typeparam name="TOther">The entity.</typeparam>
/// <param name="code">The code.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Whether it exists.</returns>
public async Task<bool> ExistsAsync<TOther>(string? code, CancellationToken cancellationToken)
where TOther : CodedEntity, new() =>
!string.IsNullOrEmpty(code) &&
await _unitOfWork.Repository<TOther, long>().CountAsync(Query.For<TOther>().Where(x => x.Code == code), cancellationToken).ConfigureAwait(false) > 0;
}
/// <summary>A company table that the generic maschera and service handle (SPEC §11.1, mockup 076).</summary>
public abstract class TableDefinition
{
/// <summary>Creates the definition.</summary>
/// <param name="key">The key used in addresses and resources, such as <c>tax-codes</c>.</param>
/// <param name="table">The database table.</param>
protected TableDefinition(string key, string table)
{
ArgumentException.ThrowIfNullOrWhiteSpace(key);
ArgumentException.ThrowIfNullOrWhiteSpace(table);
Key = key;
Table = table;
}
/// <summary>The key, such as <c>tax-codes</c>.</summary>
public string Key { get; }
/// <summary>The database table, such as <c>tax_codes</c>.</summary>
public string Table { get; }
/// <summary>The entity type.</summary>
public abstract Type EntityType { get; }
/// <summary>The maximum length of the code.</summary>
public int CodeLength { get; init; } = 10;
/// <summary>Whether codes are kept as typed instead of upper case (municipality names are not codes).</summary>
public bool KeepCodeCase { get; init; }
/// <summary>The CSV columns: header and property.</summary>
public abstract IReadOnlyList<TableCsvColumn> CsvColumns { get; }
}
/// <summary>A CSV column of a table: the snake_case header and the property.</summary>
/// <param name="Header">The header.</param>
/// <param name="Property">The property.</param>
public sealed record TableCsvColumn(string Header, PropertyInfo Property);
/// <summary>A company table of <typeparamref name="T"/>.</summary>
/// <typeparam name="T">The entity.</typeparam>
public sealed partial class TableDefinition<T> : TableDefinition
where T : CodedEntity, new()
{
private static readonly HashSet<string> NotInCsv = new(StringComparer.Ordinal)
{
nameof(Entity<long>.Id), nameof(IAuditable.CreatedAt), nameof(IAuditable.CreatedBy), nameof(IAuditable.UpdatedAt), nameof(IAuditable.UpdatedBy),
nameof(IAuditable.RowVersion), nameof(CodedEntity.IsDemo),
};
private readonly List<Func<T, TableRuleContext, CancellationToken, Task>> _rules = [];
private IReadOnlyList<TableCsvColumn>? _csv;
/// <summary>Creates the definition with the list fields <c>code</c>, <c>description</c>, <c>disabled</c>.</summary>
/// <param name="key">The key, such as <c>tax-codes</c>.</param>
/// <param name="table">The database table.</param>
public TableDefinition(string key, string table)
: base(key, table)
{
Fields = new ListFields<T>()
.Add("code", x => x.Code, searchable: true)
.Add("description", x => x.Description, searchable: true)
.Add("disabled", x => x.Disabled)
.OrderByDefault(new ListSort("code"));
}
/// <inheritdoc />
public override Type EntityType => typeof(T);
/// <summary>The fields of the grid: filters, search and ordering.</summary>
public ListFields<T> Fields { get; }
/// <summary>The rules run before every save, after the common ones (code and description).</summary>
public IReadOnlyList<Func<T, TableRuleContext, CancellationToken, Task>> Rules => _rules;
/// <summary>The flag that only one row may have (the default bank account, the default warehouse).</summary>
public Expression<Func<T, bool>>? SingleDefault { get; init; }
/// <summary>The other fields that, with the code, make a row unique (the year of a numerator).</summary>
public Func<T, Expression<Func<T, bool>>>? SameKey { get; init; }
/// <summary>Called before the rules, to fill derived fields (the kind of a VAT code).</summary>
public Action<T, IFiscalPack>? Complete { get; init; }
/// <inheritdoc />
public override IReadOnlyList<TableCsvColumn> CsvColumns => _csv ??=
[
.. typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.CanWrite && !NotInCsv.Contains(p.Name) && !p.Name.EndsWith("Id", StringComparison.Ordinal))
.OrderBy(p => p.Name switch { nameof(CodedEntity.Code) => 0, nameof(CodedEntity.Description) => 1, _ => 2 })
.ThenBy(p => p.MetadataToken)
.Select(p => new TableCsvColumn(SnakeCase(p.Name), p)),
];
/// <summary>Adds a rule.</summary>
/// <param name="rule">The rule.</param>
/// <returns>This, to chain.</returns>
public TableDefinition<T> Rule(Func<T, TableRuleContext, CancellationToken, Task> rule)
{
ArgumentNullException.ThrowIfNull(rule);
_rules.Add(rule);
return this;
}
/// <summary>Adds a rule that needs no other rows.</summary>
/// <param name="rule">The rule.</param>
/// <returns>This, to chain.</returns>
public TableDefinition<T> Rule(Action<T, TableRuleContext> rule)
{
ArgumentNullException.ThrowIfNull(rule);
_rules.Add((row, context, _) =>
{
rule(row, context);
return Task.CompletedTask;
});
return this;
}
/// <summary>Adds a grid field.</summary>
/// <typeparam name="TValue">The type.</typeparam>
/// <param name="id">The id.</param>
/// <param name="selector">The property.</param>
/// <param name="searchable">Whether the search box looks in it.</param>
/// <returns>This, to chain.</returns>
public TableDefinition<T> Field<TValue>(string id, Expression<Func<T, TValue>> selector, bool searchable = false)
{
Fields.Add(id, selector, searchable);
return this;
}
internal static string SnakeCase(string name) =>
LowerUpper().Replace(UpperUpperLower().Replace(name, "$1_$2"), "$1_$2").ToLower(CultureInfo.InvariantCulture);
[GeneratedRegex("([A-Z])([A-Z][a-z])")]
private static partial Regex UpperUpperLower();
[GeneratedRegex("([a-z0-9])([A-Z])")]
private static partial Regex LowerUpper();
}
@@ -0,0 +1,622 @@
using System.Data.Common;
using System.Globalization;
using System.Reflection;
using Khaemhat.Application.Audit;
using Khaemhat.Application.Querying;
using Khaemhat.Application.Security;
using Khaemhat.Core.Caching;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
using Khaemhat.Infrastructure.Files;
namespace Khaemhat.Application.Tables;
/// <summary>What a delete did.</summary>
public enum TableDeleteOutcome
{
/// <summary>The row is gone.</summary>
Deleted = 0,
/// <summary>The row is used elsewhere: it was disabled instead.</summary>
Disabled = 1,
}
/// <summary>A row of a CSV import that could not be read or saved.</summary>
/// <param name="Row">The row number in the file, from 2 (1 is the header).</param>
/// <param name="Field">The column, or <see langword="null"/> for the whole row.</param>
/// <param name="Code">The problem.</param>
public sealed record TableImportError(int Row, string? Field, string Code);
/// <summary>The result of a CSV import: nothing is saved when there are errors.</summary>
/// <param name="Inserted">New rows.</param>
/// <param name="Updated">Rows changed (found by code).</param>
/// <param name="Errors">The errors.</param>
public sealed record TableImportResult(int Inserted, int Updated, IReadOnlyList<TableImportError> Errors)
{
/// <summary>Whether the import was saved.</summary>
public bool Succeeded => Errors.Count == 0;
}
/// <summary>
/// The company tables of SPEC §11.1 through one service (wiki <i>Tabelle azienda</i>): list, read, save with the common
/// rules (code and description required, unique code) and those of the table, delete (or disable when the row is used),
/// CSV export and import. The rows of each table are cached per company and invalidated on every change, also on the
/// other instances when Redis is configured.
/// </summary>
/// <remarks>Reading needs <c>company.settings.read</c>, changing <c>company.settings.write</c>.</remarks>
public sealed class TableService
{
/// <summary>Permission to see the tables.</summary>
public const string ReadPermission = "company.settings.read";
/// <summary>Permission to change the tables.</summary>
public const string WritePermission = "company.settings.write";
/// <summary>Error: the code is missing.</summary>
public const string CodeRequired = "tables.code.required";
/// <summary>Error: the code is too long.</summary>
public const string CodeTooLong = "tables.code.too-long";
/// <summary>Error: another row has the code.</summary>
public const string CodeDuplicate = "tables.code.duplicate";
/// <summary>Error: the description is missing.</summary>
public const string DescriptionRequired = "tables.description.required";
/// <summary>Error: the row changed or was deleted meanwhile.</summary>
public const string NotFound = "tables.not-found";
/// <summary>Import error: the header has no <c>code</c> column.</summary>
public const string CsvNoCode = "tables.csv.no-code";
/// <summary>Import error: a value cannot be read.</summary>
public const string CsvBadValue = "tables.csv.bad-value";
/// <summary>Import error: unknown column (a warning in the result: the column is ignored).</summary>
public const string CsvUnknownColumn = "tables.csv.unknown-column";
private static readonly TimeSpan CacheTime = TimeSpan.FromHours(1);
private static readonly NullabilityInfoContext Nullability = new();
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly AuditTrail _audit;
private readonly ICacheProvider _cache;
private readonly CompanyFiscalContext _fiscal;
private readonly TableCatalog _catalog;
/// <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>
/// <param name="cache">The cache of the rows.</param>
/// <param name="fiscal">The fiscal pack of each company.</param>
/// <param name="catalog">The tables.</param>
public TableService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, ICacheProvider cache, CompanyFiscalContext fiscal, TableCatalog catalog)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(audit);
ArgumentNullException.ThrowIfNull(cache);
ArgumentNullException.ThrowIfNull(fiscal);
ArgumentNullException.ThrowIfNull(catalog);
_factory = factory;
_permissions = permissions;
_audit = audit;
_cache = cache;
_fiscal = fiscal;
_catalog = catalog;
}
/// <summary>The tables.</summary>
public TableCatalog Catalog => _catalog;
/// <summary>Every row of a table, from the cache (disabled ones included), ordered by code.</summary>
/// <typeparam name="T">The entity.</typeparam>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows.</returns>
public async Task<IReadOnlyList<T>> AllAsync<T>(Actor actor, string companyCode, CancellationToken cancellationToken = default)
where T : CodedEntity, new()
{
var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
return await RowsAsync(company, _catalog.Get<T>(), cancellationToken).ConfigureAwait(false);
}
/// <summary>The rows still in use (not disabled), for the choices on other records.</summary>
/// <typeparam name="T">The entity.</typeparam>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows.</returns>
public async Task<IReadOnlyList<T>> ActiveAsync<T>(Actor actor, string companyCode, CancellationToken cancellationToken = default)
where T : CodedEntity, new() =>
[.. (await AllAsync<T>(actor, companyCode, cancellationToken).ConfigureAwait(false)).Where(r => !r.Disabled)];
/// <summary>A page of a table for the grid.</summary>
/// <typeparam name="T">The entity.</typeparam>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="query">Search, filters, ordering and page.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The page.</returns>
public async Task<ListPage<T>> ListAsync<T>(Actor actor, string companyCode, ListQuery query, CancellationToken cancellationToken = default)
where T : CodedEntity, new()
{
ArgumentNullException.ThrowIfNull(query);
var rows = await AllAsync<T>(actor, companyCode, cancellationToken).ConfigureAwait(false);
return _catalog.Get<T>().Fields.Apply(rows, query);
}
/// <summary>One row, read from the database.</summary>
/// <typeparam name="T">The entity.</typeparam>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The id.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The row, or <see langword="null"/>.</returns>
public async Task<T?> GetAsync<T>(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
where T : CodedEntity, new()
{
var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await uow.Repository<T, long>().GetAsync(id, cancellationToken).ConfigureAwait(false);
}
/// <summary>Checks a row without saving it: the messages next to the fields.</summary>
/// <typeparam name="T">The entity.</typeparam>
/// <param name="actor">Who checks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="row">The row (normalized in place: trimmed code in upper case, derived fields).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Errors and warnings.</returns>
public async Task<IReadOnlyList<TableProblem>> ValidateAsync<T>(Actor actor, string companyCode, T row, CancellationToken cancellationToken = default)
where T : CodedEntity, new()
{
ArgumentNullException.ThrowIfNull(row);
var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await CheckAsync(uow, pack, _catalog.Get<T>(), row, cancellationToken).ConfigureAwait(false);
}
/// <summary>Saves a row: inserts it when <see cref="Core.Entities.Entity{TKey}.Id"/> is 0, updates it otherwise.</summary>
/// <typeparam name="T">The entity.</typeparam>
/// <param name="actor">Who saves.</param>
/// <param name="companyCode">The company.</param>
/// <param name="row">The row.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The saved row, with its id and new row version.</returns>
/// <exception cref="ValidationFailedException">A rule failed; <see cref="ValidationFailedException.Errors"/> has <c>Field:code</c>.</exception>
/// <exception cref="Core.Common.ConcurrencyException">Someone else changed the row meanwhile.</exception>
public async Task<T> SaveAsync<T>(Actor actor, string companyCode, T row, CancellationToken cancellationToken = default)
where T : CodedEntity, new()
{
ArgumentNullException.ThrowIfNull(row);
var company = await DemandAsync(actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
var definition = _catalog.Get<T>();
var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
Throw(await CheckAsync(uow, pack, definition, row, cancellationToken).ConfigureAwait(false));
await WriteAsync(uow, definition, row, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
await InvalidateAsync(company, definition, cancellationToken).ConfigureAwait(false);
return row;
}
/// <summary>Deletes a row, or disables it when other records use it.</summary>
/// <typeparam name="T">The entity.</typeparam>
/// <param name="actor">Who deletes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The row.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What happened.</returns>
/// <exception cref="KeyNotFoundException">No such row.</exception>
public async Task<TableDeleteOutcome> DeleteAsync<T>(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
where T : CodedEntity, new()
{
var company = await DemandAsync(actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
var definition = _catalog.Get<T>();
var outcome = TableDeleteOutcome.Deleted;
try
{
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var repository = uow.Repository<T, long>();
var before = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
await repository.DeleteAsync(id, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Delete, id, before, null, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
catch (DbException)
{
// A foreign key refused the delete: the row is used, so it is only hidden from new choices.
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var repository = uow.Repository<T, long>();
var row = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
if (!row.Disabled)
{
var before = Clone(row);
row.Disabled = true;
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, id, before, row, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
outcome = TableDeleteOutcome.Disabled;
}
await InvalidateAsync(company, definition, cancellationToken).ConfigureAwait(false);
return outcome;
}
/// <summary>Writes a table as CSV (Italian format: <c>;</c>, decimal comma, byte order mark).</summary>
/// <typeparam name="T">The entity.</typeparam>
/// <param name="actor">Who exports.</param>
/// <param name="companyCode">The company.</param>
/// <param name="output">The stream; left open.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows written.</returns>
public async Task<int> ExportCsvAsync<T>(Actor actor, string companyCode, Stream output, CancellationToken cancellationToken = default)
where T : CodedEntity, new()
{
ArgumentNullException.ThrowIfNull(output);
var rows = await AllAsync<T>(actor, companyCode, cancellationToken).ConfigureAwait(false);
var columns = _catalog.Get<T>().CsvColumns;
await using var writer = new CsvWriter(output, CsvOptions.Italian, leaveOpen: true);
await writer.WriteRowAsync(columns.Select(c => (object?)c.Header), cancellationToken).ConfigureAwait(false);
foreach (var row in rows)
{
await writer.WriteRowAsync(columns.Select(c => Export(c.Property.GetValue(row))), cancellationToken).ConfigureAwait(false);
}
return rows.Count;
}
/// <summary>
/// Imports a CSV with the columns of the export (any order, missing columns keep their value): rows are matched by
/// code, new codes are inserted. Nothing is saved unless every row passes the rules.
/// </summary>
/// <typeparam name="T">The entity.</typeparam>
/// <param name="actor">Who imports.</param>
/// <param name="companyCode">The company.</param>
/// <param name="content">The CSV.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Counts and errors.</returns>
public async Task<TableImportResult> ImportCsvAsync<T>(Actor actor, string companyCode, Stream content, CancellationToken cancellationToken = default)
where T : CodedEntity, new()
{
ArgumentNullException.ThrowIfNull(content);
var company = await DemandAsync(actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
var definition = _catalog.Get<T>();
var lines = await CsvReader.ReadAsync(content, null, cancellationToken).ConfigureAwait(false);
if (lines.Count == 0)
{
return new TableImportResult(0, 0, [new TableImportError(1, null, CsvNoCode)]);
}
var byHeader = definition.CsvColumns.ToDictionary(c => c.Header, StringComparer.OrdinalIgnoreCase);
var header = lines[0].Select(h => byHeader.GetValueOrDefault(h.Trim())).ToArray();
if (!header.Any(c => c?.Property.Name == nameof(CodedEntity.Code)))
{
return new TableImportResult(0, 0, [new TableImportError(1, null, CsvNoCode)]);
}
var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var errors = new List<TableImportError>();
var inserted = 0;
var updated = 0;
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var existing = (await uow.Repository<T, long>().ListAsync(Query.For<T>(), cancellationToken).ConfigureAwait(false)).Items
.GroupBy(r => r.Code, StringComparer.OrdinalIgnoreCase)
.ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase);
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var pending = new List<T>();
for (var i = 1; i < lines.Count; i++)
{
var line = lines[i];
var rowNumber = i + 1;
var codeIndex = Array.FindIndex(header, c => c?.Property.Name == nameof(CodedEntity.Code));
var code = codeIndex < line.Count ? line[codeIndex].Trim() : string.Empty;
var row = existing.TryGetValue(code, out var found) ? found : new T();
var rowErrors = false;
for (var c = 0; c < header.Length && c < line.Count; c++)
{
if (header[c] is not { } column)
{
continue;
}
if (TryParse(line[c], column.Property, out var value))
{
column.Property.SetValue(row, value);
}
else
{
errors.Add(new TableImportError(rowNumber, column.Header, CsvBadValue));
rowErrors = true;
}
}
if (!seen.Add(row.Code.Trim()))
{
errors.Add(new TableImportError(rowNumber, "code", CodeDuplicate));
continue;
}
if (rowErrors)
{
continue;
}
var problems = await CheckAsync(uow, pack, definition, row, cancellationToken).ConfigureAwait(false);
errors.AddRange(problems.Where(p => !p.IsWarning).Select(p => new TableImportError(rowNumber, TableDefinition<T>.SnakeCase(p.Field), p.Code)));
pending.Add(row);
}
if (errors.Count > 0)
{
return new TableImportResult(0, 0, errors);
}
foreach (var row in pending)
{
if (row.Id == 0)
{
inserted++;
}
else
{
updated++;
}
await WriteAsync(uow, definition, row, actor.UserName, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
await InvalidateAsync(company, definition, cancellationToken).ConfigureAwait(false);
return new TableImportResult(inserted, updated, []);
}
/// <summary>Saves rows without permission checks or rules: the seeders (§14), inside their own unit of work.</summary>
/// <typeparam name="T">The entity.</typeparam>
/// <param name="unitOfWork">The company unit of work.</param>
/// <param name="row">The row.</param>
/// <param name="userName">Who writes, such as <c>system</c>.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
internal Task WriteAsync<T>(IUnitOfWork unitOfWork, T row, string userName, CancellationToken cancellationToken)
where T : CodedEntity, new() =>
WriteAsync(unitOfWork, _catalog.Get<T>(), row, userName, cancellationToken);
/// <summary>Forgets the cached rows of every table of a company (after the seeders).</summary>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public ValueTask InvalidateAllAsync(string companyCode, CancellationToken cancellationToken = default) =>
_cache.PublishInvalidationAsync(CacheKeys.Prefix(CompanyCodes.Normalize(companyCode), "tables"), cancellationToken);
private static async Task<IReadOnlyList<TableProblem>> CheckAsync<T>(
IUnitOfWork uow, IFiscalPack pack, TableDefinition<T> definition, T row, CancellationToken cancellationToken)
where T : CodedEntity, new()
{
row.Code = definition.KeepCodeCase ? row.Code.Trim() : row.Code.Trim().ToUpperInvariant();
row.Description = row.Description.Trim();
definition.Complete?.Invoke(row, pack);
var context = new TableRuleContext(uow, pack);
if (row.Code.Length == 0)
{
context.Error(nameof(CodedEntity.Code), CodeRequired);
}
else if (row.Code.Length > definition.CodeLength)
{
context.Error(nameof(CodedEntity.Code), CodeTooLong);
}
else
{
var code = row.Code;
var id = row.Id;
var query = Query.For<T>().Where(x => x.Code == code && x.Id != id);
if (definition.SameKey is { } sameKey)
{
query = query.Where(sameKey(row));
}
if (await uow.Repository<T, long>().CountAsync(query, cancellationToken).ConfigureAwait(false) > 0)
{
context.Error(nameof(CodedEntity.Code), CodeDuplicate);
}
}
if (row.Description.Length == 0)
{
context.Error(nameof(CodedEntity.Description), DescriptionRequired);
}
foreach (var rule in definition.Rules)
{
await rule(row, context, cancellationToken).ConfigureAwait(false);
}
return context.Problems;
}
private static void Throw(IReadOnlyList<TableProblem> problems)
{
var errors = problems.Where(p => !p.IsWarning).Select(p => p.Field + ":" + p.Code).ToList();
if (errors.Count > 0)
{
throw new ValidationFailedException(errors);
}
}
private static T Clone<T>(T row)
where T : class, new()
{
var copy = new T();
foreach (var property in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.CanRead && p.CanWrite))
{
property.SetValue(copy, property.GetValue(row));
}
return copy;
}
private static object? Export(object? value) => value switch
{
bool b => b ? "1" : "0",
DateOnly d => d.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
Enum e => e.ToString(),
_ => value,
};
private static bool TryParse(string text, PropertyInfo property, out object? value)
{
text = text.Trim();
var type = property.PropertyType;
var target = Nullable.GetUnderlyingType(type) ?? type;
value = null;
if (text.Length == 0)
{
if (target == typeof(string))
{
value = Nullability.Create(property).WriteState == NullabilityState.Nullable ? null : string.Empty;
return true;
}
if (Nullable.GetUnderlyingType(type) is null)
{
value = Activator.CreateInstance(target);
}
return true;
}
if (target == typeof(string))
{
value = text;
return true;
}
if (target == typeof(bool))
{
var lower = text.ToLowerInvariant();
value = lower is "1" or "true" or "si" or "sì" or "s" or "x" or "vero";
return value is true || lower is "0" or "false" or "no" or "n" or "falso";
}
if (target == typeof(int) || target == typeof(long) || target == typeof(decimal))
{
// Italian (1.234,5) or invariant (1234.5): a comma is always the decimal point.
var normalized = text.Contains(',', StringComparison.Ordinal) ? text.Replace(".", string.Empty, StringComparison.Ordinal).Replace(',', '.') : text;
if (!decimal.TryParse(normalized, NumberStyles.Number, CultureInfo.InvariantCulture, out var number))
{
return false;
}
if (target == typeof(decimal))
{
value = number;
return true;
}
if (decimal.Truncate(number) != number)
{
return false;
}
value = target == typeof(int) ? (object)(int)number : (long)number;
return true;
}
if (target == typeof(DateOnly))
{
var ok = DateOnly.TryParseExact(text, ["yyyy-MM-dd", "dd/MM/yyyy", "d/M/yyyy"], CultureInfo.InvariantCulture, DateTimeStyles.None, out var date);
value = date;
return ok;
}
if (target.IsEnum)
{
var ok = Enum.TryParse(target, text, ignoreCase: true, out var parsed) && Enum.IsDefined(target, parsed!);
value = parsed;
return ok;
}
return false;
}
private async Task WriteAsync<T>(IUnitOfWork uow, TableDefinition<T> definition, T row, string userName, CancellationToken cancellationToken)
where T : CodedEntity, new()
{
var repository = uow.Repository<T, long>();
if (definition.SingleDefault is { } flag && flag.Compile()(row))
{
await ClearOtherDefaultsAsync(repository, flag, row.Id, cancellationToken).ConfigureAwait(false);
}
if (row.Id == 0)
{
row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Insert, row.Id, null, row, userName, cancellationToken).ConfigureAwait(false);
return;
}
var before = await repository.GetAsync(row.Id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, row.Id, before, row, userName, cancellationToken).ConfigureAwait(false);
}
private static async Task ClearOtherDefaultsAsync<T>(IRepository<T, long> repository, System.Linq.Expressions.Expression<Func<T, bool>> flag, long id, CancellationToken cancellationToken)
where T : CodedEntity, new()
{
var others = await repository.ListAsync(Query.For<T>().Where(flag).Where(x => x.Id != id), cancellationToken).ConfigureAwait(false);
var property = (PropertyInfo)((System.Linq.Expressions.MemberExpression)flag.Body).Member;
foreach (var other in others.Items)
{
property.SetValue(other, false);
await repository.UpdateAsync(other, cancellationToken).ConfigureAwait(false);
}
}
private async Task<IReadOnlyList<T>> RowsAsync<T>(string company, TableDefinition<T> definition, CancellationToken cancellationToken)
where T : CodedEntity, new() =>
await _cache.GetOrCreateAsync<List<T>>(
CacheKeys.For(company, "tables", definition.Key),
async ct =>
{
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), ct).ConfigureAwait(false);
var page = await uow.Repository<T, long>().ListAsync(Query.For<T>().OrderBy(x => x.Code), ct).ConfigureAwait(false);
return [.. page.Items];
},
CacheTime,
cancellationToken).ConfigureAwait(false);
private ValueTask InvalidateAsync(string company, TableDefinition definition, CancellationToken cancellationToken) =>
_cache.PublishInvalidationAsync(CacheKeys.For(company, "tables", definition.Key), cancellationToken);
private async Task<string> DemandAsync(Actor actor, string companyCode, string permission, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(actor);
var company = CompanyCodes.Normalize(companyCode);
if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, company, StringComparison.Ordinal))
{
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A company user works only in its own company.");
}
await _permissions.DemandAsync(actor, permission, cancellationToken).ConfigureAwait(false);
return company;
}
}