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,124 @@
using System.Text;
namespace Khaemhat.Infrastructure.Files;
/// <summary>
/// Reads CSV files written by <see cref="CsvWriter"/> or by spreadsheets (RFC 4180): quoted fields with doubled quotes,
/// line breaks inside quotes, an optional UTF-8 byte order mark. The separator is guessed from the first line
/// (<c>;</c>, <c>,</c> or tab) unless given.
/// </summary>
public static class CsvReader
{
/// <summary>The separators tried, in order of preference.</summary>
private static readonly char[] Separators = [';', ',', '\t'];
/// <summary>Reads every row of a text.</summary>
/// <param name="text">The content.</param>
/// <param name="separator">The separator, or <see langword="null"/> to guess it.</param>
/// <returns>The rows; empty lines are skipped.</returns>
public static IReadOnlyList<IReadOnlyList<string>> Parse(string text, char? separator = null)
{
ArgumentNullException.ThrowIfNull(text);
if (text.Length > 0 && text[0] == '')
{
text = text[1..];
}
var sep = separator ?? Guess(text);
var rows = new List<IReadOnlyList<string>>();
var row = new List<string>();
var field = new StringBuilder();
var quoted = false;
var fieldStarted = false;
for (var i = 0; i < text.Length; i++)
{
var c = text[i];
if (quoted)
{
if (c == '"')
{
if (i + 1 < text.Length && text[i + 1] == '"')
{
field.Append('"');
i++;
}
else
{
quoted = false;
}
}
else
{
field.Append(c);
}
continue;
}
if (c == '"' && field.Length == 0)
{
quoted = true;
fieldStarted = true;
}
else if (c == sep)
{
row.Add(field.ToString());
field.Clear();
fieldStarted = true;
}
else if (c is '\r' or '\n')
{
if (c == '\r' && i + 1 < text.Length && text[i + 1] == '\n')
{
i++;
}
EndRow();
}
else
{
field.Append(c);
fieldStarted = true;
}
}
EndRow();
return rows;
void EndRow()
{
if (fieldStarted || field.Length > 0 || row.Count > 0)
{
row.Add(field.ToString());
if (row.Count > 1 || row[0].Length > 0)
{
rows.Add(row);
}
}
row = [];
field.Clear();
fieldStarted = false;
}
}
/// <summary>Reads a stream as UTF-8 (the byte order mark is optional).</summary>
/// <param name="content">The stream.</param>
/// <param name="separator">The separator, or <see langword="null"/> to guess it.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows.</returns>
public static async Task<IReadOnlyList<IReadOnlyList<string>>> ReadAsync(Stream content, char? separator = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(content);
using var reader = new StreamReader(content, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, leaveOpen: true);
return Parse(await reader.ReadToEndAsync(cancellationToken).ConfigureAwait(false), separator);
}
private static char Guess(string text)
{
var end = text.IndexOfAny(['\r', '\n']);
var first = end < 0 ? text : text[..end];
return Separators.OrderByDescending(s => first.Count(c => c == s)).First();
}
}
@@ -0,0 +1,99 @@
using System.Globalization;
using System.Xml;
using System.Xml.Linq;
namespace Khaemhat.Infrastructure.Http;
/// <summary>A reference rate of the European Central Bank: units of the currency for one euro.</summary>
/// <param name="Currency">The currency (ISO 4217).</param>
/// <param name="Date">The day of the rate.</param>
/// <param name="Rate">Units of the currency for one euro.</param>
public sealed record EcbRate(string Currency, DateOnly Date, decimal Rate);
/// <summary>
/// The euro foreign exchange reference rates of the European Central Bank (SPEC §11.1, §11.12), published on working
/// days around 16:00 CET as an XML file (<c>eurofxref-daily.xml</c>, or the last 90 days in <c>eurofxref-hist-90d.xml</c>).
/// </summary>
public sealed class EcbRatesClient
{
/// <summary>The address of the reference rates.</summary>
public static readonly Uri DefaultBaseAddress = new("https://www.ecb.europa.eu/stats/eurofxref/");
private const string Namespace = "http://www.ecb.int/vocabulary/2002-08-01/eurofxref";
private readonly HttpClient _http;
/// <summary>Creates the client.</summary>
/// <param name="http">The HTTP client (its base address defaults to <see cref="DefaultBaseAddress"/>).</param>
public EcbRatesClient(HttpClient http)
{
ArgumentNullException.ThrowIfNull(http);
_http = http;
_http.BaseAddress ??= DefaultBaseAddress;
}
/// <summary>Reads the rates of the last working day, or of the last 90 days.</summary>
/// <param name="last90Days">Whether to read the last 90 days (to fill gaps after a stop).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rates.</returns>
/// <exception cref="HttpRequestException">The service did not answer.</exception>
/// <exception cref="FormatException">The answer is not the expected XML.</exception>
public async Task<IReadOnlyList<EcbRate>> GetAsync(bool last90Days = false, CancellationToken cancellationToken = default)
{
var path = new Uri(last90Days ? "eurofxref-hist-90d.xml" : "eurofxref-daily.xml", UriKind.Relative);
using var response = await _http.GetAsync(path, cancellationToken).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
await using (content.ConfigureAwait(false))
{
return await ParseAsync(content, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>Reads the ECB XML.</summary>
/// <param name="xml">The XML.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rates.</returns>
/// <exception cref="FormatException">The XML is not the ECB format.</exception>
public static async Task<IReadOnlyList<EcbRate>> ParseAsync(Stream xml, CancellationToken cancellationToken = default)
{
XDocument document;
try
{
var settings = new XmlReaderSettings { Async = true, DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null };
using var reader = XmlReader.Create(xml, settings);
document = await XDocument.LoadAsync(reader, LoadOptions.None, cancellationToken).ConfigureAwait(false);
}
catch (XmlException ex)
{
throw new FormatException("The ECB answer is not XML.", ex);
}
XNamespace ns = Namespace;
var rates = new List<EcbRate>();
foreach (var day in document.Descendants(ns + "Cube").Where(c => c.Attribute("time") is not null))
{
if (!DateOnly.TryParseExact(day.Attribute("time")!.Value, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date))
{
throw new FormatException("The ECB answer has a date that cannot be read.");
}
foreach (var cube in day.Elements(ns + "Cube"))
{
var currency = cube.Attribute("currency")?.Value;
var text = cube.Attribute("rate")?.Value;
if (currency is { Length: 3 } && decimal.TryParse(text, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var rate) && rate > 0)
{
rates.Add(new EcbRate(currency, date, rate));
}
}
}
if (rates.Count == 0)
{
throw new FormatException("The ECB answer has no rates.");
}
return rates;
}
}