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; /// /// 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 ), 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 (ADR 0028). Banks /// come from a dataset loaded separately (ADR 0026). /// /// Creates the current fiscal year. public sealed class BaseTablesSeeder(FiscalYearService years) : ISeeder { /// The currencies of the ECB reference rates, plus the euro: code, name, symbol, decimals. 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), ]; /// The numerators of the base data: code, description, family, section, format, gaps allowed. 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), ]; /// public string ModuleCode => ModuleCodes.Core; /// public SeedKind Kind => SeedKind.Base; /// public int Order => 0; /// public async Task RunAsync(SeedContext context, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(context); await context.EnsureAsync("countries", ReadCountries(), cancellationToken).ConfigureAwait(false); if (context.Pack.GetFeature() 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(("FRANCO", "Porto franco"), ("ASSEGNATO", "Porto assegnato"), ("ADDEBITO", "Franco con addebito in fattura")), cancellationToken) .ConfigureAwait(false); await context.EnsureAsync("transport_means", Coded(("MITT", "Mittente"), ("DEST", "Destinatario"), ("VETT", "Vettore")), cancellationToken).ConfigureAwait(false); await context.EnsureAsync( "goods_appearances", Coded(("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( ("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(("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(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() 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() .CountAsync(Query.For().Where(y => y.StartDate <= context.Today && y.EndDate >= context.Today), cancellationToken).ConfigureAwait(false); if (calendar == 0 && await context.UnitOfWork.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) == 0) { await years.CreateAsync(context.UnitOfWork, context.Today, "system", cancellationToken).ConfigureAwait(false); context.Count("fiscal_years"); } } /// The countries of the embedded list (ISO 3166-1, Italian names, EU members, currency). /// The rows. public static IReadOnlyList 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().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items .Select(t => t.Code) .ToHashSet(StringComparer.OrdinalIgnoreCase); var lines = context.UnitOfWork.Repository(); 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 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 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 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 Incoterms() => Coded( ("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 Coded(params (string Code, string Description)[] rows) where T : CodedEntity, new() => rows.Select(r => new T { Code = r.Code, Description = r.Description }); }