using Khaemhat.Application.Modules; using Khaemhat.Application.Parties; using Khaemhat.Application.Tables; using Khaemhat.Core.Parties; using Khaemhat.Core.Tables; using Khaemhat.Data; using Khaemhat.Data.Querying; using Khaemhat.Fiscal.Abstractions; namespace Khaemhat.Application.Seeding; /// /// The parties of the demo company (SPEC §14, issue #41): customers of every kind of subject (companies, public /// administration with split payment, private persons, EU and non-EU companies, flat rate, a declaration of intent, a /// customer blocked over its credit, one that is also a supplier, one disabled), suppliers (a professional with /// withholding, an ENASARCO agent, an EU supplier), prospects and leads, and three salespeople. Every name, number and /// bank account is fictitious: the VAT numbers have a valid check digit, the IBANs a valid check, the ABI codes belong /// to no bank. Runs only on a company without parties; the rows are marked as demo. /// /// The automatic code rules. public sealed class DemoPartiesSeeder(CodeRuleService codes) : ISeeder { /// The fictitious VAT numbers, valid for the Italian check digit (tests check them with the pack). public static readonly IReadOnlyList VatNumbers = [ "04123456784", "05234567898", "06345678905", "07456789010", "08567890127", "09678901233", "10789012340", "11890123455", "12901234562", "13012345677", "14123456700", "15234567814", "16345678920", "17456789035", ]; /// The fictitious tax code of the public administration (numeric, valid check digit). public const string AdministrationTaxCode = "80012345676"; /// The fictitious IBANs, with a valid check and ABI codes of no bank. public static readonly IReadOnlyList Ibans = ["IT53X0123410100000012345678", "IT21X0567822000000000987654", "IT11X0987645600000101234567"]; /// public string ModuleCode => ModuleCodes.Core; /// public SeedKind Kind => SeedKind.Demo; /// public int Order => 10; /// public async Task RunAsync(SeedContext context, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(context); var uow = context.UnitOfWork; if (await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) > 0) { return; } var rules = new Dictionary(); foreach (var kind in Enum.GetValues()) { rules[kind] = await codes.RuleAsync(context.CompanyCode, PartyService.CodeRuleOf(kind), cancellationToken).ConfigureAwait(false); } var salespeople = await context.EnsureAsync( "salespeople", [ new Salesperson { Code = "VERDI", Description = "Marco Verdi", Email = "m.verdi@demo.example", CommissionPercent = 5m, Enasarco = true }, new Salesperson { Code = "NERI", Description = "Laura Neri", Email = "l.neri@demo.example", CommissionPercent = 4m, Enasarco = true }, new Salesperson { Code = "BIANCO", Description = "Paolo Bianco", Email = "p.bianco@demo.example", CommissionPercent = 3m }, ], cancellationToken).ConfigureAwait(false); var terms = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items .ToDictionary(t => t.Code, t => t.Id, StringComparer.OrdinalIgnoreCase); var priceList = (await uow.Repository().FindAsync(Query.For().Where(p => p.Code == "BASE"), cancellationToken).ConfigureAwait(false))?.Id; long? Term(string code) => terms.TryGetValue(code, out var id) ? id : null; long? Agent(string code) => salespeople.TryGetValue(code, out var s) ? s.Id : null; var identifiers = context.Pack.GetFeature(); var year = context.Today.Year; var seeds = new List { Customer("Rossi Impianti S.r.l.", SubjectType.Company, VatNumbers[0], "Via Nizza", "120", "10126", "Torino", "TO", Term("RB60FM"), Agent("VERDI"), r => { r.Fiscal.RecipientCode = "M5UXCR1"; r.Party.Phone = "011 5550101"; r.Party.Email = "amministrazione@rossi-impianti.example"; r.Contacts.Add(new PartyContact { Name = "Mario Rossi", Role = "Titolare", Mobile = "333 5550101", Email = "mario@rossi-impianti.example", IsDefault = true }); r.Contacts.Add(new PartyContact { Name = "Anna Ferri", Role = "Amministrazione", Phone = "011 5550102", Email = "amministrazione@rossi-impianti.example" }); r.Addresses.Add(new PartyAddress { Kind = PartyAddressKind.Site, Name = "Cantiere Lingotto", Address = "Via Ventimiglia", StreetNumber = "88", PostalCode = "10126", City = "Torino", Province = "TO", IsDefault = true }); r.BankAccounts.Add(new PartyBankAccount { Iban = Ibans[0], BankCode = "01234", BranchCode = "10100", IsDefault = true }); r.Sales.Discount1 = 5m; r.Sales.CreditLimit = 30000m; r.Sales.SendDocuments = DocumentDelivery.Email; r.Sales.DocumentsEmail = "amministrazione@rossi-impianti.example"; }), Customer("Bianchi & Figli S.n.c.", SubjectType.Company, VatNumbers[1], "Corso Langhe", "5", "12051", "Alba", "CN", Term("RB3060FM"), Agent("VERDI"), r => { r.Fiscal.RecipientCode = "0000000"; r.Fiscal.RecipientPec = "bianchiefigli@pec.demo.example"; r.Party.Pec = "bianchiefigli@pec.demo.example"; }), Customer("Comune di Valdora", SubjectType.PublicAdministration, null, "Piazza del Municipio", "1", "12060", "Valdora", "CN", Term("BB30"), null, r => { r.Party.TaxCode = AdministrationTaxCode; r.Fiscal.RecipientCode = "UFX9K2"; r.Fiscal.SplitPayment = true; r.Fiscal.Exigibility = "S"; r.Fiscal.AdministrationReference = "SETT-TECNICO"; }), Customer("Ferramenta Gallo", SubjectType.Company, VatNumbers[2], "Corso Alfieri", "210", "14100", "Asti", "AT", Term("RD"), Agent("NERI"), r => { r.Fiscal.RecipientCode = "KRRH6B9"; r.Sales.CreditLimit = 5000m; r.Sales.Blocked = true; r.Party.Notes = "Ordini bloccati: fido superato, rientro concordato entro fine mese."; }), Customer("Bergwerk Bau GmbH", SubjectType.EuCompany, "U12345678", "Museumstrasse", "12", "6020", "Innsbruck", null, Term("BB30"), Agent("NERI"), r => { r.Party.CountryCode = "AT"; r.Party.Language = "de"; r.Fiscal.RecipientCode = "XXXXXXX"; }), Customer("Esposito Mario", SubjectType.Person, null, "Via Po", "18", "10124", "Torino", "TO", Term("RD"), null, r => { r.Party.LastName = "Esposito"; r.Party.FirstName = "Mario"; r.Party.TaxCode = Personal(identifiers, "Esposito", "Mario", new DateOnly(1980, 1, 1), PersonSex.Male, "L219"); r.Party.Email = "mario.esposito@posta.example"; r.Fiscal.RecipientCode = "0000000"; r.Party.PrivacyAccepted = true; }), Customer("Idrotermica Piemonte S.r.l.", SubjectType.Company, VatNumbers[3], "Via Roma", "44", "12100", "Cuneo", "CN", Term("RB3060FM"), Agent("VERDI"), r => { r.Fiscal.RecipientCode = "T04ZHR3"; r.Fiscal.IntentActive = true; r.Fiscal.IntentNumber = "14/" + year; r.Fiscal.IntentDate = new DateOnly(year, 1, 15); r.Fiscal.IntentProtocol = "26011512345678901-000001"; r.Fiscal.IntentCeiling = 150000m; r.Fiscal.IntentFrom = new DateOnly(year, 1, 1); r.Fiscal.IntentTo = new DateOnly(year, 12, 31); }), Customer("Nordic Pipes AS", SubjectType.NonEuCompany, "987654321", "Storgata", "7", "0155", "Oslo", null, Term("RD"), Agent("NERI"), r => { r.Party.CountryCode = "NO"; r.Party.Language = "en"; r.Fiscal.RecipientCode = "XXXXXXX"; }), Customer("Studio Tecnico Ing. Ferrero", SubjectType.FlatRate, VatNumbers[4], "Via Vittorio Emanuele", "3", "12051", "Alba", "CN", Term("BB30"), null, r => { r.Fiscal.RecipientCode = "USAL8PV"; r.Fiscal.StampDutyCharged = true; }), Customer("Edilizia Moderna S.p.A.", SubjectType.Company, VatNumbers[5], "Viale Monza", "250", "20126", "Milano", "MI", Term("RB3060FM"), Agent("BIANCO"), r => { r.Party.IsAlsoSupplier = true; r.Fiscal.RecipientCode = "W7YVJK9"; r.Purchase.PaymentTermId = Term("BB30FM"); r.Sales.Discount1 = 10m; r.Sales.Discount2 = 3m; }), Customer("Termoidraulica Sacco", SubjectType.Company, VatNumbers[6], "Via Cavour", "9", "12042", "Bra", "CN", Term("RD"), Agent("NERI"), r => { r.Fiscal.RecipientCode = "SUBM70N"; r.Party.Disabled = true; r.Party.Notes = "Attività cessata."; }), Customer("Hotel Belvedere S.r.l.", SubjectType.Company, VatNumbers[7], "Passeggiata Cadorna", "15", "17021", "Alassio", "SV", Term("BB30FM"), Agent("BIANCO"), r => { r.Fiscal.RecipientCode = "5RUO82D"; r.Contacts.Add(new PartyContact { Name = "Giulia Marino", Role = "Direzione", Phone = "0182 555010", IsDefault = true }); }), Supplier("Metalli Nord S.p.A.", VatNumbers[8], "Via Industriale", "40", "25125", "Brescia", "BS", Term("RB60FM"), r => { r.Purchase.LeadTimeDays = 10; r.Purchase.MinimumOrder = 500m; r.Purchase.OrdersEmail = "ordini@metalli-nord.example"; r.BankAccounts.Add(new PartyBankAccount { Iban = Ibans[1], BankCode = "05678", BranchCode = "22000", IsDefault = true }); }), Supplier("Plastica Sud S.r.l.", VatNumbers[9], "Via Appia", "301", "81100", "Caserta", "CE", Term("BB30FM"), r => r.Purchase.LeadTimeDays = 15), Supplier("Studio Rag. Neri Paola", VatNumbers[10], "Via Vittorio Veneto", "21", "12100", "Cuneo", "CN", Term("RD"), r => { r.Fiscal.Withholding = true; r.Fiscal.WithholdingRate = 20m; r.Fiscal.WithholdingReason = "A"; r.Fiscal.PensionFund = "TC04"; r.Fiscal.PensionFundRate = 4m; r.BankAccounts.Add(new PartyBankAccount { Iban = Ibans[2], BankCode = "09876", BranchCode = "45600", IsDefault = true }); }), Supplier("Agenzia Commerciale Bruno", VatNumbers[11], "Corso Francia", "77", "10138", "Torino", "TO", Term("BB30FM"), r => { r.Fiscal.Withholding = true; r.Fiscal.WithholdingRate = 23m; r.Fiscal.WithholdingReason = "R"; r.Fiscal.Enasarco = true; }), Supplier("Elektro Werke Süd GmbH", "123456789", "Industriestrasse", "5", "80331", "München", null, Term("BB30"), r => { r.Party.SubjectType = SubjectType.EuCompany; r.Party.CountryCode = "DE"; r.Party.Language = "de"; }), Contact(PartyKind.Prospect, "Caseificio Valle Stura S.r.l.", VatNumbers[12], "12014", "Demonte", "CN", Agent("VERDI")), Contact(PartyKind.Prospect, "Agriturismo Le Vigne", VatNumbers[13], "12060", "Barolo", "CN", Agent("BIANCO")), Contact(PartyKind.Lead, "Fontana Marco (fiera di Bologna)", null, null, null, null, Agent("NERI")), Contact(PartyKind.Lead, "Cantina Sociale del Roero", null, "12043", "Canale", "CN", null), }; foreach (var record in seeds) { record.Sales.PriceListId ??= record.Party.IsCustomer ? priceList : null; await InsertAsync(uow, record, rules[record.Party.Kind], context.Today, cancellationToken).ConfigureAwait(false); context.Count("parties"); } } private static PartyRecord Customer(string name, SubjectType subject, string? vat, string address, string number, string postalCode, string city, string? province, long? paymentTermId, long? salespersonId, Action more) { var record = New(PartyKind.Customer, name, subject, vat, postalCode, city, province, salespersonId); record.Party.Address = address; record.Party.StreetNumber = number; record.Sales.PaymentTermId = paymentTermId; more(record); return record; } private static PartyRecord Supplier(string name, string vat, string address, string number, string postalCode, string city, string? province, long? paymentTermId, Action more) { var record = New(PartyKind.Supplier, name, SubjectType.Company, vat, postalCode, city, province, null); record.Party.Address = address; record.Party.StreetNumber = number; record.Purchase.PaymentTermId = paymentTermId; more(record); return record; } private static PartyRecord Contact(PartyKind kind, string name, string? vat, string? postalCode, string? city, string? province, long? salespersonId) => New(kind, name, SubjectType.Company, vat, postalCode, city, province, salespersonId); private static PartyRecord New(PartyKind kind, string name, SubjectType subject, string? vat, string? postalCode, string? city, string? province, long? salespersonId) => new() { Party = new Party { Kind = kind, Name = name, SubjectType = subject, VatNumber = vat, PostalCode = postalCode, City = city, Province = province, SalespersonId = salespersonId, CategoryId = null, PrivacyAccepted = kind is PartyKind.Customer or PartyKind.Supplier, IsDemo = true, }, }; private static string? Personal(ITaxIdentifierRules? rules, string surname, string name, DateOnly birth, PersonSex sex, string place) => rules?.ComputePersonalTaxCode(new PersonalTaxCodeData(surname, name, birth, sex, place)); private static async Task InsertAsync(IUnitOfWork uow, PartyRecord record, CodeRule rule, DateOnly today, CancellationToken cancellationToken) { var parties = uow.Repository(); var party = record.Party; party.Code = await CodeRuleService.AssignAsync( uow, rule, today, null, async (code, ct) => await parties.CountAsync(Query.For().Where(p => p.Code == code), ct).ConfigureAwait(false) > 0, cancellationToken).ConfigureAwait(false); party.Id = await parties.InsertAsync(party, cancellationToken).ConfigureAwait(false); if (party.IsCustomer) { record.Sales.PartyId = party.Id; await uow.Repository().InsertAsync(record.Sales, cancellationToken).ConfigureAwait(false); } if (party.IsSupplier) { record.Purchase.PartyId = party.Id; await uow.Repository().InsertAsync(record.Purchase, cancellationToken).ConfigureAwait(false); } record.Fiscal.PartyId = party.Id; await uow.Repository().InsertAsync(record.Fiscal, cancellationToken).ConfigureAwait(false); foreach (var address in record.Addresses) { address.PartyId = party.Id; address.CountryCode = address.CountryCode.Length == 0 ? party.CountryCode : address.CountryCode; await uow.Repository().InsertAsync(address, cancellationToken).ConfigureAwait(false); } foreach (var contact in record.Contacts) { contact.PartyId = party.Id; await uow.Repository().InsertAsync(contact, cancellationToken).ConfigureAwait(false); } foreach (var account in record.BankAccounts) { account.PartyId = party.Id; await uow.Repository().InsertAsync(account, cancellationToken).ConfigureAwait(false); } } }