One engine for sales, purchases and warehouse documents (ADR 0032). Each document type now carries a kind that decides its family of tables, life cycle, effects, accepted lines, the kinds it fulfils and its permissions, so company-defined types work without code. - Six families of header and line tables plus document_links; document_types gets document_kind (seeded types filled by the migration and the Italian template), document_numerators gets last_date. - DocumentStateMachine with the order, invoice and simple life cycles and the actions each state admits; issued invoices are immutable and are cancelled with a reason only before the file reaches the exchange system. - DocumentNumberingService numbers at confirmation inside the transaction under the numerator lock (advisory lock on PostgreSQL, write lock on SQLite): no duplicates, a rollback gives the number back, out-of-sequence dates refused on gap-free numerators, the new year's numerator created on first use, gap report. - DocumentEngine, the generic DocumentService<THeader, TLine> and DocumentCopyService: save, confirm or issue, cancel, close, reopen, delete, duplicate and transform; links are recorded at confirmation and removed at cancellation, and FulfillmentCalculator recomputes quantities and states. - Tests: rules in Core, concurrent numbering on SQLite and PostgreSQL (data tests, run on PostgreSQL 18 locally), order to delivery notes to deferred invoice on a real instance. Wiki (Vendite, Tabelle azienda), CHANGELOG, STATUS, DATA-MODEL. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
267 lines
16 KiB
C#
267 lines
16 KiB
C#
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, and the provinces and municipalities of the pack's <see cref="IPlaceDirectory"/> (ADR 0028). Banks
|
|
/// come from a dataset 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);
|
|
if (context.Pack.GetFeature<IPlaceDirectory>() is { } places)
|
|
{
|
|
await context.EnsureAsync("provinces", places.Provinces.Select(p => new Province { Code = p.Code, Description = p.Name, Region = p.Region }), cancellationToken)
|
|
.ConfigureAwait(false);
|
|
await context.EnsureAsync(
|
|
"municipalities",
|
|
places.Municipalities.Select(m => new Municipality
|
|
{
|
|
Code = m.Code,
|
|
Description = m.Name,
|
|
ProvinceCode = m.ProvinceCode,
|
|
Region = m.Region,
|
|
IstatCode = m.StatisticalCode,
|
|
PostalCodes = m.PostalCodes,
|
|
}),
|
|
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", IsBase = true }], 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,
|
|
DocumentKind = d.DocumentKind,
|
|
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 });
|
|
}
|