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,246 @@
using Khaemhat.Application.Modules;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Tables;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
using Khaemhat.Infrastructure.Files;
namespace Khaemhat.Application.Seeding;
/// <summary>
/// The base tables of SPEC §14 available from M4: countries, currencies, units, VAT codes (from the fiscal pack),
/// payment methods and terms and document types (from the pack's <see cref="IBaseTablesTemplate"/>), transport tables,
/// warehouse reasons, the main warehouse, categories, the base price list, the numerators and the fiscal year of the
/// current year. Provinces, municipalities and banks come from datasets loaded separately (ADR 0026).
/// </summary>
/// <param name="years">Creates the current fiscal year.</param>
public sealed class BaseTablesSeeder(FiscalYearService years) : ISeeder
{
/// <summary>The currencies of the ECB reference rates, plus the euro: code, name, symbol, decimals.</summary>
public static readonly IReadOnlyList<(string Code, string Name, string Symbol, int Decimals)> Currencies =
[
("EUR", "Euro", "€", 2), ("USD", "Dollaro statunitense", "$", 2), ("GBP", "Sterlina britannica", "£", 2), ("CHF", "Franco svizzero", "CHF", 2),
("JPY", "Yen giapponese", "¥", 0), ("CZK", "Corona ceca", "Kč", 2), ("DKK", "Corona danese", "kr", 2), ("HUF", "Fiorino ungherese", "Ft", 2),
("PLN", "Zloty polacco", "zł", 2), ("RON", "Leu rumeno", "lei", 2), ("SEK", "Corona svedese", "kr", 2), ("ISK", "Corona islandese", "kr", 0),
("NOK", "Corona norvegese", "kr", 2), ("TRY", "Lira turca", "₺", 2), ("AUD", "Dollaro australiano", "A$", 2), ("BRL", "Real brasiliano", "R$", 2),
("CAD", "Dollaro canadese", "C$", 2), ("CNY", "Renminbi cinese", "¥", 2), ("HKD", "Dollaro di Hong Kong", "HK$", 2), ("IDR", "Rupia indonesiana", "Rp", 2),
("ILS", "Nuovo siclo israeliano", "₪", 2), ("INR", "Rupia indiana", "₹", 2), ("KRW", "Won sudcoreano", "₩", 0), ("MXN", "Peso messicano", "Mex$", 2),
("MYR", "Ringgit malese", "RM", 2), ("NZD", "Dollaro neozelandese", "NZ$", 2), ("PHP", "Peso filippino", "₱", 2), ("SGD", "Dollaro di Singapore", "S$", 2),
("THB", "Baht thailandese", "฿", 2), ("ZAR", "Rand sudafricano", "R", 2),
];
/// <summary>The numerators of the base data: code, description, family, section, format, gaps allowed.</summary>
public static readonly IReadOnlyList<(string Code, string Description, NumeratorKind Kind, string? Section, string Format, bool Gaps)> Numerators =
[
("PRE", "Preventivi", NumeratorKind.Quotation, null, "PRE-{year}-{number:D4}", true),
("ORD", "Ordini clienti", NumeratorKind.SalesOrder, null, "OC-{year}-{number:D4}", true),
("DDT", "Documenti di trasporto", NumeratorKind.DeliveryNote, null, "{number}/{year}", true),
("FAT", "Fatture e note di credito", NumeratorKind.SalesInvoice, null, "{number}/{year}", false),
("AUT", "Autofatture e integrazioni", NumeratorKind.SalesInvoice, "AF", "{number}/AF/{year}", false),
("PRF", "Pro forma", NumeratorKind.Other, null, "PF-{year}-{number:D4}", true),
("ORF", "Ordini fornitori", NumeratorKind.PurchaseOrder, null, "OF-{year}-{number:D4}", true),
("PRA", "Protocollo acquisti", NumeratorKind.PurchaseInvoice, null, "{number}", false),
("MAG", "Movimenti di magazzino", NumeratorKind.Inventory, null, "MM-{year}-{number:D5}", true),
("PN", "Registrazioni contabili", NumeratorKind.Journal, null, "{number}", false),
];
/// <inheritdoc />
public string ModuleCode => ModuleCodes.Core;
/// <inheritdoc />
public SeedKind Kind => SeedKind.Base;
/// <inheritdoc />
public int Order => 0;
/// <inheritdoc />
public async Task RunAsync(SeedContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
await context.EnsureAsync("countries", ReadCountries(), cancellationToken).ConfigureAwait(false);
await context.EnsureAsync("currencies", Currencies.Select(c => new Currency { Code = c.Code, Description = c.Name, Symbol = c.Symbol, Decimals = c.Decimals }), cancellationToken)
.ConfigureAwait(false);
await context.EnsureAsync("units_of_measure", Units(), cancellationToken).ConfigureAwait(false);
await context.EnsureAsync("tax_codes", TaxCodes(context.Pack), cancellationToken).ConfigureAwait(false);
var reasons = await context.EnsureAsync("inventory_reasons", InventoryReasons(), cancellationToken).ConfigureAwait(false);
await context.EnsureAsync("warehouses", [new Warehouse { Code = "SEDE", Description = "Magazzino sede", IsDefault = true }], cancellationToken).ConfigureAwait(false);
await context.EnsureAsync("shipping_terms", Coded<ShippingTerm>(("FRANCO", "Porto franco"), ("ASSEGNATO", "Porto assegnato"), ("ADDEBITO", "Franco con addebito in fattura")), cancellationToken)
.ConfigureAwait(false);
await context.EnsureAsync("transport_means", Coded<TransportMean>(("MITT", "Mittente"), ("DEST", "Destinatario"), ("VETT", "Vettore")), cancellationToken).ConfigureAwait(false);
await context.EnsureAsync(
"goods_appearances",
Coded<GoodsAppearance>(("CARTONI", "Cartoni"), ("SCATOLE", "Scatole"), ("BANCALI", "Bancali"), ("COLLI", "Colli"), ("BUSTE", "Buste"), ("SFUSO", "Sfuso"), ("VISTA", "A vista")),
cancellationToken).ConfigureAwait(false);
await context.EnsureAsync("delivery_terms", Incoterms(), cancellationToken).ConfigureAwait(false);
await context.EnsureAsync(
"transport_reasons",
Coded<TransportReason>(
("VEN", "Vendita"), ("CV", "Conto visione"), ("CD", "Conto deposito"), ("CL", "Conto lavorazione"), ("RES", "Reso"), ("RIP", "Riparazione"),
("OMA", "Omaggio"), ("TRA", "Trasferimento tra depositi")),
cancellationToken).ConfigureAwait(false);
await context.EnsureAsync("item_categories", [new ItemCategory { Code = "GEN", Description = "Generica" }], cancellationToken).ConfigureAwait(false);
await context.EnsureAsync("party_categories", Coded<PartyCategory>(("GEN", "Generica")), cancellationToken).ConfigureAwait(false);
await context.EnsureAsync("price_lists", [new PriceList { Code = "BASE", Description = "Listino base" }], cancellationToken).ConfigureAwait(false);
var year = context.Today.Year;
var numerators = new Dictionary<string, DocumentNumerator>(StringComparer.Ordinal);
foreach (var n in Numerators)
{
numerators[n.Code] = await context.EnsureOneAsync(
"document_numerators",
x => x.Code == n.Code && x.Year == year,
new DocumentNumerator { Code = n.Code, Description = n.Description, Kind = n.Kind, Section = n.Section, Year = year, Format = n.Format, GapsAllowed = n.Gaps },
cancellationToken).ConfigureAwait(false);
}
if (context.Pack.GetFeature<IBaseTablesTemplate>() is { } template)
{
await SeedPaymentsAsync(context, template, cancellationToken).ConfigureAwait(false);
await context.EnsureAsync(
"document_types",
template.DocumentTypes.Select(d => new DocumentType
{
Code = d.Code,
Description = d.Description,
Kind = d.Kind,
NumeratorId = d.NumeratorCode is { } n && numerators.TryGetValue(n, out var numerator) ? numerator.Id : null,
InventoryReasonId = d.InventoryReasonCode is { } r && reasons.TryGetValue(r, out var reason) ? reason.Id : null,
EInvoiceType = d.EInvoiceType,
}),
cancellationToken).ConfigureAwait(false);
}
var calendar = await context.UnitOfWork.Repository<FiscalYear, long>()
.CountAsync(Query.For<FiscalYear>().Where(y => y.StartDate <= context.Today && y.EndDate >= context.Today), cancellationToken).ConfigureAwait(false);
if (calendar == 0 && await context.UnitOfWork.Repository<FiscalYear, long>().CountAsync(Query.For<FiscalYear>(), cancellationToken).ConfigureAwait(false) == 0)
{
await years.CreateAsync(context.UnitOfWork, context.Today, "system", cancellationToken).ConfigureAwait(false);
context.Count("fiscal_years");
}
}
/// <summary>The countries of the embedded list (ISO 3166-1, Italian names, EU members, currency).</summary>
/// <returns>The rows.</returns>
public static IReadOnlyList<Country> ReadCountries()
{
using var stream = typeof(BaseTablesSeeder).Assembly.GetManifestResourceStream("Khaemhat.Application.Seeding.Data.countries.csv")
?? throw new InvalidOperationException("The country list is missing from the assembly.");
using var reader = new StreamReader(stream);
var lines = CsvReader.Parse(reader.ReadToEnd(), ';');
return
[
.. lines.Skip(1).Select(l => new Country
{
Code = l[0],
Iso3 = l[1].Length == 0 ? null : l[1],
Description = l[2],
EuMember = l[3] == "1",
CurrencyCode = l[4].Length == 0 ? null : l[4],
// Greece uses EL in VAT numbers and VIES.
VatPrefix = l[0] == "GR" ? "EL" : null,
}),
];
}
private static async Task SeedPaymentsAsync(SeedContext context, IBaseTablesTemplate template, CancellationToken cancellationToken)
{
var methods = await context.EnsureAsync(
"payment_methods",
template.PaymentMethods.Select(m => new PaymentMethod { Code = m.Code, Description = m.Description, EInvoiceCode = m.EInvoiceCode, NeedsBank = m.NeedsBank }),
cancellationToken).ConfigureAwait(false);
var existing = (await context.UnitOfWork.Repository<PaymentTerm, long>().ListAsync(Query.For<PaymentTerm>(), cancellationToken).ConfigureAwait(false)).Items
.Select(t => t.Code)
.ToHashSet(StringComparer.OrdinalIgnoreCase);
var lines = context.UnitOfWork.Repository<PaymentTermLine, long>();
foreach (var t in template.PaymentTerms.Where(t => !existing.Contains(t.Code)))
{
var terms = await context.EnsureOneAsync(
"payment_terms",
x => x.Code == t.Code,
new PaymentTerm
{
Code = t.Code,
Description = t.Description,
Condition = t.Condition,
PaymentMethodId = methods.TryGetValue(t.PaymentMethodCode, out var method) ? method.Id : null,
},
cancellationToken).ConfigureAwait(false);
var number = 1;
foreach (var i in t.Installments)
{
await lines.InsertAsync(new PaymentTermLine { PaymentTermId = terms.Id, Number = number++, Days = i.Days, EndOfMonth = i.EndOfMonth, Percent = i.Percent }, cancellationToken)
.ConfigureAwait(false);
}
}
}
private static IEnumerable<TaxCode> TaxCodes(IFiscalPack pack) =>
pack.TaxCodes.BaseCodes.Select(c => new TaxCode
{
Code = c.Code,
Description = c.Description,
Rate = c.Rate,
Nature = c.Nature,
Exigibility = c.Exigibility,
NonDeductiblePercent = c.NonDeductiblePercent,
LegalReference = c.LegalReference,
Kind = pack.TaxCodes.KindOf(c.Rate, c.Nature),
});
private static IEnumerable<UnitOfMeasure> Units() =>
[
new() { Code = "NR", Description = "Numero", Decimals = 0 },
new() { Code = "PZ", Description = "Pezzi", Decimals = 0 },
new() { Code = "CF", Description = "Confezioni", Decimals = 0 },
new() { Code = "CT", Description = "Cartoni", Decimals = 0 },
new() { Code = "PAL", Description = "Pallet", Decimals = 0 },
new() { Code = "KG", Description = "Chilogrammi", Decimals = 3 },
new() { Code = "G", Description = "Grammi", Decimals = 0 },
new() { Code = "T", Description = "Tonnellate", Decimals = 3 },
new() { Code = "L", Description = "Litri", Decimals = 3 },
new() { Code = "M", Description = "Metri", Decimals = 3 },
new() { Code = "M2", Description = "Metri quadrati", Decimals = 3 },
new() { Code = "M3", Description = "Metri cubi", Decimals = 3 },
new() { Code = "KM", Description = "Chilometri", Decimals = 2 },
new() { Code = "KWH", Description = "Kilowattora", Decimals = 3 },
new() { Code = "ORE", Description = "Ore", Decimals = 2 },
new() { Code = "GG", Description = "Giorni", Decimals = 2 },
new() { Code = "MESI", Description = "Mesi", Decimals = 0 },
new() { Code = "SERV", Description = "Servizio", Decimals = 0 },
];
private static IEnumerable<InventoryReason> InventoryReasons() =>
[
new() { Code = "CAR", Description = "Carico da acquisto", Effect = StockEffect.Load },
new() { Code = "SCA", Description = "Scarico per vendita", Effect = StockEffect.Unload },
new() { Code = "RESC", Description = "Reso da cliente", Effect = StockEffect.Load },
new() { Code = "RESF", Description = "Reso a fornitore", Effect = StockEffect.Unload },
new() { Code = "TRA", Description = "Trasferimento tra depositi", Effect = StockEffect.None, AffectsValue = false, IsTransfer = true },
new() { Code = "INVP", Description = "Rettifica inventariale in aumento", Effect = StockEffect.Load },
new() { Code = "INVN", Description = "Rettifica inventariale in diminuzione", Effect = StockEffect.Unload },
new() { Code = "CVU", Description = "Uscita in conto visione", Effect = StockEffect.Unload, AffectsValue = false },
new() { Code = "CVR", Description = "Rientro da conto visione", Effect = StockEffect.Load, AffectsValue = false },
new() { Code = "OMA", Description = "Omaggio", Effect = StockEffect.Unload },
new() { Code = "AUTO", Description = "Autoconsumo", Effect = StockEffect.Unload },
new() { Code = "APE", Description = "Esistenza iniziale", Effect = StockEffect.Load },
];
private static IEnumerable<DeliveryTerm> Incoterms() => Coded<DeliveryTerm>(
("EXW", "Franco fabbrica (Ex Works)"),
("FCA", "Franco vettore (Free Carrier)"),
("CPT", "Trasporto pagato fino a (Carriage Paid To)"),
("CIP", "Trasporto e assicurazione pagati fino a (Carriage and Insurance Paid To)"),
("DAP", "Reso al luogo di destinazione (Delivered at Place)"),
("DPU", "Reso al luogo di destinazione scaricato (Delivered at Place Unloaded)"),
("DDP", "Reso sdoganato (Delivered Duty Paid)"),
("FAS", "Franco lungo bordo (Free Alongside Ship)"),
("FOB", "Franco a bordo (Free On Board)"),
("CFR", "Costo e nolo (Cost and Freight)"),
("CIF", "Costo, assicurazione e nolo (Cost, Insurance and Freight)"));
private static IEnumerable<T> Coded<T>(params (string Code, string Description)[] rows)
where T : CodedEntity, new() =>
rows.Select(r => new T { Code = r.Code, Description = r.Description });
}