From 07555de700855807dfee8103dfc8a7637528f2ff Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 11 Nov 2026 23:33:02 +0100 Subject: [PATCH] feat: automatic codes and automatic filling (#43) Parties, items and the CRM archives need codes given by the system without duplicates, and the address and bank fields should fill themselves; this adds both before the party and item screens that use them. - CodeMask ({seq:0000}, {anno}, {categoria}) and code_sequences (migration 015): one sequence per rule, year and category, taken under a lock in the transaction that saves the record, skipping codes written by hand - CodeRuleService: rules in company settings with the masks of SPEC 11.12, validation, preview of the next code, manual code allowed or not - AutoFillService: municipality from postal code and back, personal tax code, VIES, bank and BIC from the IBAN, delivery date on working days, options that can be switched off (the ECB job honours its option) - IBankDirectory.ReadIban gives ABI and CAB even without the ABI list; the Italian pack now registers the directory - Company preferences page (mockup 074) at /tabelle/preferenze, in the menu - aria-checked now renders true/false on switch rows and profile radios - ADR 0027, wiki, CHANGELOG, STATUS, DATA-MODEL Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 + docs/DATA-MODEL.md | 16 + docs/STATUS.md | 8 +- .../0027-codici-automatici-e-compilazione.md | 49 +++ docs/wiki/Tabelle-azienda.md | 66 ++-- .../Tables/AutoFillService.cs | 289 ++++++++++++++++++ .../Tables/CodeRuleService.cs | 286 +++++++++++++++++ .../Tables/ExchangeRates.cs | 10 +- src/Khaemhat.Core/Tables/CodeRules.cs | 268 ++++++++++++++++ .../M20261111_015_CreateCodeSequences.cs | 23 ++ .../CompanyDatabase/TableMaps.cs | 11 + .../Identifiers.cs | 9 +- .../ItalianIdentifiers.cs | 6 + src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs | 3 + .../Components/Pages/Profile.razor | 6 +- .../Pages/Tables/CompanyPreferencesPage.razor | 249 +++++++++++++++ .../Components/Pages/Tables/TablesIndex.razor | 1 + .../Components/Ui/KhSwitchRow.razor | 2 +- src/Khaemhat.Web/Hosting/KhaemhatServices.cs | 2 + .../Resources/it-IT/CompanyPreferences.json | 93 ++++++ src/Khaemhat.Web/Resources/it-IT/Shell.json | 1 + src/Khaemhat.Web/Shell/MenuCatalog.cs | 1 + .../Common/CodeMaskTests.cs | 69 +++++ tests/Khaemhat.Data.Tests/MappingTests.cs | 2 +- .../ItalianIdentifiersTests.cs | 14 + .../Tables/CodeRulesTests.cs | 171 +++++++++++ .../Tables/TableScreensTests.cs | 5 +- 27 files changed, 1627 insertions(+), 40 deletions(-) create mode 100644 docs/adr/0027-codici-automatici-e-compilazione.md create mode 100644 src/Khaemhat.Application/Tables/AutoFillService.cs create mode 100644 src/Khaemhat.Application/Tables/CodeRuleService.cs create mode 100644 src/Khaemhat.Core/Tables/CodeRules.cs create mode 100644 src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_015_CreateCodeSequences.cs create mode 100644 src/Khaemhat.Web/Components/Pages/Tables/CompanyPreferencesPage.razor create mode 100644 src/Khaemhat.Web/Resources/it-IT/CompanyPreferences.json create mode 100644 tests/Khaemhat.Core.Tests/Common/CodeMaskTests.cs create mode 100644 tests/Khaemhat.Web.Tests/Tables/CodeRulesTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 50e5096..a24b254 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,13 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`. di misura, codici IVA, pagamenti, tipi documento, numeratori, causali, trasporti, deposito, listino ed esercizio in corso. Versione salvata nelle impostazioni dell'azienda (`IT 2026.2`). - `scripts/seed.sh --base [--company CODICE]`, incluso nell'immagine in `/app/scripts/`. +- Codici automatici (ADR 0027): maschere per clienti, fornitori, lead, articoli, cespiti, opportunità, ticket, + contratti e interventi con `{seq:0000}`, `{anno}` e `{categoria}`, anteprima del prossimo codice, codice manuale + ammesso o no, progressivi in `code_sequences` assegnati nella transazione del salvataggio (nessun doppione, nessun + numero perso se il salvataggio fallisce, codici già presenti saltati). +- Compilazione automatica: comune, provincia e regione dal CAP e CAP dal comune, codice fiscale, verifica VIES, ABI, + CAB, banca e BIC dall'IBAN, data di consegna sul calendario lavorativo; ogni opzione si spegne nelle preferenze, e + il job dei cambi BCE salta le aziende che l'hanno spento. Pagina *Preferenze azienda* (`/tabelle/preferenze`). ## [0.3.0] - 2026-11-11 diff --git a/docs/DATA-MODEL.md b/docs/DATA-MODEL.md index b457e27..f0848b9 100644 --- a/docs/DATA-MODEL.md +++ b/docs/DATA-MODEL.md @@ -726,6 +726,7 @@ Migrazioni applicate in ordine: - `core` 20261111012 `create_tax_and_payment_tables` (M20261111_012_CreateTaxAndPaymentTables) - `core` 20261111013 `create_logistics_tables` (M20261111_013_CreateLogisticsTables) - `core` 20261111014 `create_catalog_tables` (M20261111_014_CreateCatalogTables) +- `core` 20261111015 `create_code_sequences` (M20261111_015_CreateCodeSequences) #### `attachments` @@ -819,6 +820,21 @@ Migrazioni applicate in ordine: - indice unico `ux_carriers_code` su `code` +#### `code_sequences` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `key` | String(100) | no | | | +| `last_value` | Int64 | no | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice unico `ux_code_sequences_key` su `key` + #### `company_profile` | Colonna | Tipo | Null | Default | Note | diff --git a/docs/STATUS.md b/docs/STATUS.md index 91386f6..fff6653 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -6,9 +6,9 @@ **Milestone corrente:** M4 — Tabelle, anagrafiche, articoli (issue #37-#46), ramo `feat/37-tabelle-anagrafiche`. Fatti: pacchetto fiscale (#37), validatori e VIES (#40), tabelle azienda, profilo, esercizi e cambi con le maschere (#38, #39), dati di base e `scripts/seed.sh --base` (#45, senza gli elenchi ISTAT e ABI/CAB: serve il via -dell'utente al download). ADR 0025-0026. -**Prossimo passo:** codici automatici e compilazione automatica (#43), poi anagrafiche (#41) e articoli e listini -(#42) con i dati di esempio, import/export guidato (#44), chiusura M4 (#46). #35 (PNG ad alta risoluzione) resta +dell'utente al download), codici automatici e compilazione automatica (#43). ADR 0025-0027. +**Prossimo passo:** anagrafiche (#41) e articoli e listini (#42) con i dati di esempio, import/export guidato (#44), +chiusura M4 (#46). #35 (PNG ad alta risoluzione) resta aperta e non blocca. Da recuperare: misure di riferimento su PostgreSQL in `docs/DATA-MODEL.md` §6.1; indicatore di robustezza della password (mockup 003); schede *Layout salvati* (M4) e *Notifiche* (con le e-mail, M5) del profilo; rinomina e @@ -17,7 +17,7 @@ filtro predefinito nei radar. ## Fatto - Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E6. -- ADR 0001-0026. +- ADR 0001-0027. - Mockup in `docs/mockups/` (22 in alta risoluzione + galleria, 88 miniature, `mockup.css`, indice). - Icone in `assets/`; deploy in `deploy/` (compose Unraid, `.env.example`, template Unraid). - Documentazione tecnica: `ARCHITECTURE.md`, `DATA-MODEL.md` (provvisorio, sarà generato), `MODULES.md`, `API.md`, diff --git a/docs/adr/0027-codici-automatici-e-compilazione.md b/docs/adr/0027-codici-automatici-e-compilazione.md new file mode 100644 index 0000000..2f3685b --- /dev/null +++ b/docs/adr/0027-codici-automatici-e-compilazione.md @@ -0,0 +1,49 @@ +# ADR 0027 - Codici automatici con sequenze per chiave e compilazione a opzioni + +- **Stato:** accettata +- **Data:** 2026-11-11 +- **Modifica:** SPEC §11.12 (codici automatici, compilazione automatica); ADR 0025, 0026; milestone M4, issue #43 + +## Contesto + +SPEC §11.12 chiede maschere di codice per archivio (`C{seq:000000}`, `{categoria}-{seq:0000}`, `L{anno}-{seq:0000}`…), +progressivo globale o per categoria/anno, codice manuale ammesso o no, anteprima del prossimo codice e sequenze in +`code_sequences` con assegnazione atomica. Non dice dove stanno le regole, come si chiamano le sequenze, cosa succede +se il codice successivo è già stato scritto a mano o se la maschera cambia. Per la compilazione automatica elenca le +opzioni senza dire chi le applica, e la banca dall'IBAN dipende da un elenco ABI che non è ancora nel repository +(ADR 0026). + +## Decisione + +1. **Regole nelle impostazioni dell'azienda.** La maschera e il codice manuale di ogni archivio stanno in + `company_settings` (`codes..mask`, `codes..manual`, `codes.items.unique-barcode`); un archivio + senza impostazioni usa la maschera di SPEC. Gli archivi sono un elenco fisso in `CodeRuleService.Definitions`, con + il modulo di licenza e la lunghezza massima del codice. +2. **Una sequenza per chiave.** `code_sequences` ha una riga per chiave: il nome dell'archivio, più l'anno se la + maschera contiene `{anno}`, più la categoria se contiene `{categoria}` (`customers`, `leads:2026`, `items:VALV`). + La maschera non fa parte della chiave: **cambiare maschera continua lo stesso progressivo** e non riscrive i codici + già assegnati. +3. **Assegnazione nella transazione del salvataggio.** `CodeRuleService.AssignAsync` prende un lock applicativo sulla + chiave (`AcquireLockAsync`, vuoto su SQLite dove le scritture sono già in fila), incrementa la sequenza e la scrive + nella stessa unità di lavoro del record: se il salvataggio fallisce il numero torna libero, e due salvataggi + contemporanei non ottengono mai lo stesso codice. Un codice già presente nella tabella (scritto a mano) viene + saltato; dopo 1.000 salti il salvataggio è rifiutato. +4. **Maschere controllate.** Letterali `A-Z 0-9 - _ / .` in maiuscolo, esattamente un `{seq}`, segnaposto + `{anno}`/`{year}` e `{categoria}`/`{category}`, lunghezza minima entro quella della tabella. Gli errori sono codici + (`codes.mask.*`) tradotti dall'interfaccia. +5. **Compilazione a opzioni.** `AutoFillService` raccoglie le funzioni (comune da CAP e viceversa, codice fiscale dal + pacchetto fiscale, VIES, banca da IBAN, data di consegna sul calendario del pacchetto) e le opzioni accese o spente + (`autofill.`); le maschere chiedono `IsOnAsync` prima di compilare. Il job dei cambi BCE salta le aziende + che hanno spento l'opzione. Le opzioni sulle righe dei documenti e sui conti si applicano con i documenti (M5). +6. **Banca da IBAN senza elenco ABI.** `IBankDirectory.ReadIban` restituisce sempre ABI e CAB di un IBAN italiano; + nome e BIC arrivano dall'elenco quando c'è, altrimenti da un conto dell'azienda presso la stessa banca. +7. **Modulo.** SPEC mette codici automatici e preferenze nel modulo AUTO, ma servono a ogni azienda (mockup 074, M4): + stanno nel modulo CORE come le tabelle; le maschere degli archivi di CRM, Servizi e Cespiti si preparano anche + senza il modulo. + +## Conseguenze + +- Le anagrafiche (#41) e gli articoli (#42) chiamano `AssignAsync` quando il codice è vuoto e `CheckManual` quando è + scritto; gli import li trattano allo stesso modo. +- Una sequenza per categoria nasce al primo articolo della categoria; rinominare il codice di una categoria fa + ripartire il suo progressivo, ma i codici già assegnati restano e quelli ripetuti vengono saltati. diff --git a/docs/wiki/Tabelle-azienda.md b/docs/wiki/Tabelle-azienda.md index f2e7635..c25dfc0 100644 --- a/docs/wiki/Tabelle-azienda.md +++ b/docs/wiki/Tabelle-azienda.md @@ -12,9 +12,9 @@ dati di base italiani (vedi [Dati di base e di esempio](Dati-di-base-e-esempio)) Menu **Tabelle azienda**: la voce principale apre l'indice di tutte le tabelle (`/tabelle`), raggruppate in *Azienda*, *Fisco, pagamenti e banche*, *Vendite e documenti*, *Magazzino e trasporto*, *Geografia* e *Classificazioni*. Sotto la voce -ci sono le scorciatoie per *Profilo azienda*, *Esercizi*, *Codici IVA*, *Pagamenti*, *Numeratori*, *Depositi*, +ci sono le scorciatoie per *Profilo azienda*, *Esercizi*, *Preferenze e codici automatici*, *Codici IVA*, *Pagamenti*, *Numeratori*, *Depositi*, *Valute* e *Cambi*. Ogni tabella ha un indirizzo proprio, ad esempio `/tabelle/codici-iva`, ed è raggiungibile anche -dalla ricerca globale (`Ctrl+K`). *Preferenze e codici automatici* arriva con il resto di M4. +dalla ricerca globale (`Ctrl+K`). *Preferenze e codici automatici* è a `/tabelle/preferenze`. ## Come si usa una tabella @@ -157,8 +157,9 @@ spenta). I numeratori sono per anno: il caricamento di base crea quelli dell'ann ![074 · Codici automatici e compilazione automatica](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/074-preferenze-codici-automatici.png) *Mockup 074 — Preferenze azienda: maschere dei codici automatici per anagrafiche, articoli e cespiti, CRM e servizi, documenti e contabilità; elenco delle compilazioni automatiche (anteprima ridotta).* -La maschera **Preferenze azienda** ha le schede *Codici automatici*, *Compilazione automatica*, *Arrotondamenti e -controlli*, *Default documenti*, *Modelli e-mail*, *Testi di stampa*. +La maschera **Preferenze azienda** (`/tabelle/preferenze`) ha le schede *Codici automatici* e *Compilazione +automatica*; le schede *Arrotondamenti e controlli*, *Default documenti*, *Modelli e-mail* e *Testi di stampa* +arrivano con i documenti e le e-mail. **Salva** registra le due schede insieme. ### Codici automatici @@ -176,28 +177,44 @@ Per ogni archivio si imposta una **maschera**; sotto il campo compare l'anteprim | Contratti di servizio | `SVC-{seq:0000}` | `SVC-0001` | | Interventi | `MAN-{anno}-{seq:0000}` | `MAN-2026-0001` | -Segnaposto: `{seq:0000}` progressivo con il numero di cifre indicato, `{anno}` anno corrente, `{categoria}` codice -della categoria. Il progressivo può essere **globale** o **per categoria / per anno**. Opzioni: *Consenti codice -manuale* (l'utente può scrivere un codice diverso), *Blocca duplicati per EAN* (articoli). I progressivi sono -assegnati in modo atomico: due salvataggi contemporanei non ottengono mai lo stesso codice. +Segnaposto: `{seq:0000}` progressivo con tante cifre quanti sono gli zeri (`{seq}` senza zeri davanti), `{anno}` +anno della registrazione, `{categoria}` codice della categoria (solo articoli). Il resto della maschera si scrive +così com'è: lettere, cifre e `- _ / .`. Il progressivo è **globale**, riparte **ogni anno** se la maschera +contiene `{anno}` e va **per categoria** se contiene `{categoria}`. Una maschera sbagliata (senza progressivo, con +segnaposto sconosciuti o con codici più lunghi della tabella) viene segnalata sotto il campo e non si salva. + +Opzioni: *Consenti codice manuale* per ogni riquadro (l'utente può scrivere un codice diverso; spento, il campo +codice resta vuoto e il codice arriva al salvataggio), *Blocca duplicati per EAN* (articoli). Le maschere dei moduli +non attivi (CRM, Servizi, Cespiti) si possono preparare: valgono quando il modulo viene attivato. + +I progressivi sono assegnati **al salvataggio** dentro la stessa transazione: due salvataggi contemporanei non +ottengono mai lo stesso codice, e un salvataggio non riuscito non consuma il numero. Se il codice successivo esiste +già (perché scritto a mano), Khaemhat passa al numero dopo. **Cambiare la maschera non riscrive i codici già +assegnati** e non azzera il progressivo: da `C{seq:000000}` a `CL{seq:0000}` dopo `C000123` il codice successivo è +`CL0124`. + +Il riquadro *Documenti e contabilità* rimanda ai [numeratori](#numeratori): fatture, protocollo e registrazioni non +usano maschere ma numeratori per anno e sezionale. ### Compilazione automatica -| Opzione | Effetto | -|---|---| -| Comune, provincia e regione dal CAP | compila l'indirizzo partendo dal CAP | -| Codice fiscale dai dati anagrafici | calcola il codice fiscale delle persone fisiche | -| Verifica P.IVA UE (VIES) al salvataggio | interroga il servizio VIES e salva l'esito | -| Banca e BIC dall'IBAN | ricava la banca dalla tabella ABI | -| Cambi BCE giornalieri | scarica i cambi ogni giorno | -| Descrizione articolo nelle righe | copia la descrizione dell'articolo nella riga del documento | -| Ultimo prezzo praticato al cliente | lo mostra come riferimento | -| Proponi ultimo documento simile | parte dal documento precedente dello stesso cliente | -| Date consegna = data + lead time | calcola la consegna prevista | -| Conti contabili da articolo, categoria, causale | propone conti di ricavo e costo | +Ogni opzione si accende o spegne con un interruttore; spenta, i campi restano da scrivere a mano. -Oltre a queste, i documenti ricevono sempre destinazione, listino, pagamento e agente dal cliente e causale e -deposito dal tipo documento. +| Opzione | Effetto | Predefinita | +|---|---|---| +| Comune, provincia e regione dal CAP | scrivendo il CAP propone il comune (o i comuni) con provincia e regione; scrivendo il comune propone CAP e provincia | accesa | +| Codice fiscale dai dati anagrafici | calcola il codice fiscale delle persone fisiche da cognome, nome, data, sesso e comune di nascita | accesa | +| Verifica P.IVA UE (VIES) al salvataggio | interroga il servizio VIES e salva l'esito (*valida*, *non valida*, *servizio non disponibile*) | accesa | +| Banca e BIC dall'IBAN | legge ABI e CAB dall'IBAN; banca e BIC vengono dall'elenco ABI o, finché l'elenco non è caricato, da un conto dell'azienda presso la stessa banca | accesa | +| Cambi BCE giornalieri | l'attività di sistema scarica i cambi nei giorni lavorativi; spenta, l'azienda usa solo cambi manuali | accesa | +| Descrizione articolo nelle righe | copia la descrizione dell'articolo nella riga del documento | accesa | +| Ultimo prezzo praticato al cliente | lo mostra come riferimento | accesa | +| Proponi ultimo documento simile | parte dal documento precedente dello stesso tipo e cliente | spenta | +| Data di consegna = data + lead time | aggiunge il tempo di approvvigionamento e sposta la data al primo giorno lavorativo | accesa | +| Conti contabili da articolo, categoria e causale | propone conti di ricavo e costo | accesa | + +Le opzioni sulle righe e sui conti agiscono con i documenti e la contabilità (da M5). Oltre a queste, i documenti +ricevono sempre destinazione, listino, pagamento e agente dal cliente e causale e deposito dal tipo documento. ### Altre preferenze aziendali @@ -222,8 +239,9 @@ con i rispettivi moduli attivi. La conferma della liquidazione e la chiusura del modificare i codici predefiniti usati in documenti già emessi. - **Non riesco a inserire un documento con data di agosto.** Il periodo è bloccato o liquidato: chiedi a chi gestisce la contabilità. -- **Posso cambiare la maschera dei codici clienti a metà anno?** I codici già assegnati non vengono riscritti: la - nuova maschera vale per i codici successivi (il comportamento in caso di conflitti sarà definito in sviluppo). +- **Posso cambiare la maschera dei codici clienti a metà anno?** Sì: i codici già assegnati non vengono riscritti, + la nuova maschera vale per i codici successivi e continua lo stesso progressivo; un codice che esiste già viene + saltato. ## Pagine correlate diff --git a/src/Khaemhat.Application/Tables/AutoFillService.cs b/src/Khaemhat.Application/Tables/AutoFillService.cs new file mode 100644 index 0000000..33b6229 --- /dev/null +++ b/src/Khaemhat.Application/Tables/AutoFillService.cs @@ -0,0 +1,289 @@ +using Khaemhat.Application.Instance; +using Khaemhat.Application.Security; +using Khaemhat.Core.Tables; +using Khaemhat.Fiscal.Abstractions; +using Khaemhat.Infrastructure.Http; + +namespace Khaemhat.Application.Tables; + +/// A municipality proposed for an address. +/// The code of the municipality (Italy: cadastral code). +/// The name. +/// The province. +/// The region. +/// The postal code: the one typed, or the only one of the municipality. +public sealed record PlaceSuggestion(string MunicipalityCode, string Name, string ProvinceCode, string? Region, string? PostalCode); + +/// An option of the automatic filling (mockup 074). +/// The key, also the setting autofill.<key>. +/// Whether it is on in a new company. +public sealed record AutoFillOption(string Key, bool Default = true); + +/// +/// The automatic filling of SPEC §11.12: municipality, province and region from the postal code, the personal tax code +/// from the personal data, the VIES check of EU VAT numbers, bank and BIC from the IBAN, delivery dates from the lead +/// time. Each option can be switched off in the company preferences; the forms ask before +/// filling. The defaults that documents take from the customer and the document type come with the documents (M5). +/// +/// The company tables. +/// The fiscal pack of the company. +/// The company settings. +/// The permissions. +/// The VIES client. +public sealed class AutoFillService(TableService tables, CompanyFiscalContext fiscal, CompanySettingsService settings, PermissionService permissions, ViesClient vies) +{ + /// The start of the setting keys. + public const string SettingPrefix = "autofill."; + + /// Municipality, province and region from the postal code. + public const string PostalCode = "postal-code"; + + /// Personal tax code from the personal data. + public const string TaxCode = "tax-code"; + + /// VIES check of EU VAT numbers when saving. + public const string Vies = "vies"; + + /// Bank and BIC from the IBAN. + public const string BankFromIban = "bank-from-iban"; + + /// Daily ECB exchange rates. + public const string EcbRates = "ecb-rates"; + + /// Item description copied into document lines. + public const string ItemDescription = "item-description"; + + /// Last price charged to the customer shown as reference. + public const string LastPrice = "last-price"; + + /// Start from the last similar document of the customer. + public const string LastDocument = "last-document"; + + /// Delivery date = document date + lead time. + public const string DeliveryDate = "delivery-date"; + + /// Revenue and cost accounts from item, category and reason. + public const string Accounts = "accounts"; + + private const int MaxSuggestions = 20; + + /// The options, in the order of the preferences page. + public static readonly IReadOnlyList Options = + [ + new(PostalCode), new(TaxCode), new(Vies), new(BankFromIban), new(EcbRates), + new(ItemDescription), new(LastPrice), new(LastDocument, Default: false), new(DeliveryDate), new(Accounts), + ]; + + /// The options of a company. + /// Who reads. + /// The company. + /// Cancellation. + /// Whether each option is on, by key. + public async Task> OptionsAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(permissions, actor, companyCode, TableService.ReadPermission, cancellationToken).ConfigureAwait(false); + return await ReadAsync(company, cancellationToken).ConfigureAwait(false); + } + + /// Whether an option is on, for the forms and services that fill fields (no permission check). + /// The company. + /// The option. + /// Cancellation. + /// when on. + public async Task IsOnAsync(string companyCode, string key, CancellationToken cancellationToken = default) => + (await ReadAsync(companyCode, cancellationToken).ConfigureAwait(false)).GetValueOrDefault(key); + + /// Saves the options of a company. + /// Who saves. + /// The company. + /// The options to change, by key. + /// Cancellation. + /// The options now in force. + public async Task> SaveOptionsAsync(Actor actor, string companyCode, IReadOnlyDictionary values, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(values); + var company = await CompanyGuard.DemandAsync(permissions, actor, companyCode, TableService.WritePermission, cancellationToken).ConfigureAwait(false); + var known = Options.Select(o => o.Key).ToHashSet(StringComparer.Ordinal); + await settings.SetManyAsync( + actor, + company, + values.Where(v => known.Contains(v.Key)).ToDictionary(v => SettingPrefix + v.Key, v => (string?)(v.Value ? "true" : "false"), StringComparer.Ordinal), + cancellationToken).ConfigureAwait(false); + return await ReadAsync(company, cancellationToken).ConfigureAwait(false); + } + + /// The municipalities with a postal code. + /// Who asks. + /// The company. + /// The postal code. + /// Cancellation. + /// The municipalities, by name; empty when none or when the code is not complete. + public async Task> PlacesByPostalCodeAsync(Actor actor, string companyCode, string? postalCode, CancellationToken cancellationToken = default) + { + var code = postalCode?.Trim() ?? string.Empty; + if (code.Length < 4 || !code.All(char.IsAsciiDigit)) + { + return []; + } + + return + [ + .. (await MunicipalitiesAsync(actor, companyCode, cancellationToken).ConfigureAwait(false)) + .Where(m => PostalCodeMatches(m.PostalCodes, code)) + .OrderBy(m => m.Description, StringComparer.CurrentCulture) + .Take(MaxSuggestions) + .Select(m => Suggest(m, code)), + ]; + } + + /// The municipalities whose name starts with some text. + /// Who asks. + /// The company. + /// The start of the name. + /// Cancellation. + /// The municipalities, exact name first. + public async Task> PlacesByNameAsync(Actor actor, string companyCode, string? name, CancellationToken cancellationToken = default) + { + var text = name?.Trim() ?? string.Empty; + if (text.Length < 2) + { + return []; + } + + return + [ + .. (await MunicipalitiesAsync(actor, companyCode, cancellationToken).ConfigureAwait(false)) + .Where(m => m.Description.StartsWith(text, StringComparison.CurrentCultureIgnoreCase)) + .OrderBy(m => m.Description.Length == text.Length ? 0 : 1) + .ThenBy(m => m.Description, StringComparer.CurrentCulture) + .Take(MaxSuggestions) + .Select(m => Suggest(m, null)), + ]; + } + + /// Whether a postal code is in a list such as 10121,10122 or 00118-00199. + /// The postal codes of a municipality. + /// The postal code. + /// when it is one of them. + public static bool PostalCodeMatches(string? list, string code) + { + ArgumentNullException.ThrowIfNull(code); + foreach (var item in (list ?? string.Empty).Split([',', ';', ' '], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + var dash = item.IndexOf('-', StringComparison.Ordinal); + if (dash < 0) + { + if (string.Equals(item, code, StringComparison.Ordinal)) + { + return true; + } + + continue; + } + + var from = item[..dash].Trim(); + var to = item[(dash + 1)..].Trim(); + if (from.Length == code.Length && to.Length == code.Length + && string.CompareOrdinal(code, from) >= 0 && string.CompareOrdinal(code, to) <= 0) + { + return true; + } + } + + return false; + } + + /// The personal tax code of a person, computed by the fiscal pack of the company. + /// The company. + /// The personal data. + /// Cancellation. + /// The code, or when the country has no such code or the data are incomplete. + public async Task PersonalTaxCodeAsync(string companyCode, PersonalTaxCodeData data, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(data); + var pack = await fiscal.PackOfAsync(companyCode, cancellationToken).ConfigureAwait(false); + if (pack.GetFeature() is not { } rules + || string.IsNullOrWhiteSpace(data.Surname) || string.IsNullOrWhiteSpace(data.GivenName) || string.IsNullOrWhiteSpace(data.BirthPlaceCode)) + { + return null; + } + + try + { + return rules.ComputePersonalTaxCode(data); + } + catch (ArgumentException) + { + return null; + } + } + + /// Checks an EU VAT number with VIES. + /// The ISO country code. + /// The number. + /// Cancellation. + /// The outcome; a service that does not answer gives . + public Task CheckVatAsync(string countryCode, string vatNumber, CancellationToken cancellationToken = default) => + vies.CheckAsync(countryCode, vatNumber, cancellationToken); + + /// + /// The bank of an IBAN: name and BIC from the directory of the fiscal pack or, when the directory does not know the + /// bank, from an account of the company at the same bank. + /// + /// Who asks. + /// The company. + /// The IBAN. + /// Cancellation. + /// The bank, or when the IBAN is not a domestic one. + public async Task BankFromIbanAsync(Actor actor, string companyCode, string? iban, CancellationToken cancellationToken = default) + { + var pack = await fiscal.PackOfAsync(companyCode, cancellationToken).ConfigureAwait(false); + if (pack.GetFeature() is not { } directory || directory.ReadIban(iban) is not { } bank) + { + return null; + } + + if (bank.Name is not null) + { + return bank; + } + + var known = (await tables.ActiveAsync(actor, companyCode, cancellationToken).ConfigureAwait(false)) + .Select(a => (Account: a, Bank: directory.ReadIban(a.Iban))) + .FirstOrDefault(a => a.Bank?.BankCode == bank.BankCode && !string.IsNullOrWhiteSpace(a.Account.BankName)); + return known.Account is { } account ? bank with { Name = account.BankName, Bic = account.Bic } : bank; + } + + /// The delivery date of a record: its date plus the lead time, moved to the next working day. + /// The company. + /// The date of the document. + /// The lead time in calendar days. + /// Cancellation. + /// The date. + public async Task DeliveryDateAsync(string companyCode, DateOnly date, int leadTimeDays, CancellationToken cancellationToken = default) + { + var pack = await fiscal.PackOfAsync(companyCode, cancellationToken).ConfigureAwait(false); + return pack.Calendar.NextWorkingDay(date.AddDays(Math.Max(0, leadTimeDays))); + } + + private async Task> MunicipalitiesAsync(Actor actor, string companyCode, CancellationToken cancellationToken) => + await tables.ActiveAsync(actor, companyCode, cancellationToken).ConfigureAwait(false); + + private static PlaceSuggestion Suggest(Municipality municipality, string? postalCode) + { + var single = municipality.PostalCodes is { } codes && !codes.Contains(',', StringComparison.Ordinal) && !codes.Contains('-', StringComparison.Ordinal) + ? codes.Trim() + : null; + return new PlaceSuggestion(municipality.Code, municipality.Description, municipality.ProvinceCode, municipality.Region, postalCode ?? single); + } + + private async Task> ReadAsync(string company, CancellationToken cancellationToken) + { + var values = await settings.GetAllAsync(company, SettingPrefix, cancellationToken).ConfigureAwait(false); + return Options.ToDictionary( + o => o.Key, + o => values.TryGetValue(SettingPrefix + o.Key, out var value) && bool.TryParse(value, out var on) ? on : o.Default, + StringComparer.Ordinal); + } +} diff --git a/src/Khaemhat.Application/Tables/CodeRuleService.cs b/src/Khaemhat.Application/Tables/CodeRuleService.cs new file mode 100644 index 0000000..37ea23c --- /dev/null +++ b/src/Khaemhat.Application/Tables/CodeRuleService.cs @@ -0,0 +1,286 @@ +using Khaemhat.Application.Instance; +using Khaemhat.Application.Modules; +using Khaemhat.Application.Security; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Tables; + +/// A table whose codes can be given automatically (SPEC §11.12, mockup 074). +/// The rule key, also the start of the sequence keys, such as customers. +/// The box of the preferences page: parties, items or crm. +/// The mask of a new company. +/// The licence module the table belongs to. +/// Whether the mask may use the category. +/// The longest code the table accepts. +public sealed record CodeRuleDefinition(string Key, string Group, string DefaultMask, string Module, bool CategoriesAllowed = false, int MaxLength = 20); + +/// The automatic code of a table as the company set it. +/// The rule key. +/// The mask. +/// Whether a user may write a code instead of the automatic one. +/// Items only: refuse two items with the same EAN. +public sealed record CodeRule(string Key, string Mask, bool AllowManual, bool UniqueBarcode = false); + +/// +/// The automatic codes of a company (SPEC §11.12): the mask of each table in the company settings +/// (codes.<table>.mask, codes.<table>.manual) and the numbers in code_sequences, given +/// under a lock inside the transaction that saves the record, so two saves at the same time never get the same code. A +/// number whose code is already taken (a code written by hand) is skipped. +/// +/// The units of work. +/// The permissions. +/// The company settings. +public sealed class CodeRuleService(IUnitOfWorkFactory factory, PermissionService permissions, CompanySettingsService settings) +{ + /// The start of the setting keys. + public const string SettingPrefix = "codes."; + + /// Error: the code was written by hand where only automatic codes are allowed. + public const string ManualNotAllowed = "codes.manual"; + + /// Error: the mask uses the category and the record has none. + public const string CategoryRequired = "codes.category-required"; + + /// Error: the code is longer than the table accepts. + public const string CodeTooLong = "codes.too-long"; + + /// Error: no free code was found (too many codes taken by hand). + public const string Exhausted = "codes.exhausted"; + + /// The field the errors of a record's code are reported on. + public const string CodeField = "Code"; + + /// The field the errors of a mask are reported on. + public const string MaskField = "Mask"; + + private const int MaxSkips = 1000; + + /// The tables with automatic codes and their masks of SPEC §11.12. + public static readonly IReadOnlyList Definitions = + [ + new("customers", "parties", "C{seq:000000}", ModuleCodes.Core), + new("suppliers", "parties", "F{seq:000000}", ModuleCodes.Core), + new("leads", "parties", "L{anno}-{seq:0000}", ModuleCodes.Crm), + new("items", "items", "{categoria}-{seq:0000}", ModuleCodes.Core, CategoriesAllowed: true, MaxLength: 30), + new("assets", "items", "CESP-{seq:0000}", ModuleCodes.Assets), + new("opportunities", "crm", "OPP-{anno}-{seq:0000}", ModuleCodes.Crm), + new("tickets", "crm", "TK-{anno}-{seq:0000}", ModuleCodes.Services), + new("service-contracts", "crm", "SVC-{seq:0000}", ModuleCodes.Services), + new("interventions", "crm", "MAN-{anno}-{seq:0000}", ModuleCodes.Services), + ]; + + /// The definition of a rule. + /// The rule key. + /// The definition. + /// The key is not a rule. + public static CodeRuleDefinition Definition(string key) => + Definitions.FirstOrDefault(d => d.Key == key) ?? throw new KeyNotFoundException("Unknown code rule " + key + "."); + + /// The rule of a new company. + /// The table. + /// The rule. + public static CodeRule DefaultRule(CodeRuleDefinition definition) + { + ArgumentNullException.ThrowIfNull(definition); + return new CodeRule(definition.Key, definition.DefaultMask, AllowManual: true, UniqueBarcode: definition.Key == "items"); + } + + /// Checks a set of rules. + /// The rules. + /// The errors, on <key>.Mask. + public static IReadOnlyList Validate(IEnumerable rules) + { + ArgumentNullException.ThrowIfNull(rules); + var problems = new List(); + foreach (var rule in rules) + { + var definition = Definition(rule.Key); + if (CodeMask.Check(rule.Mask, definition.MaxLength, definition.CategoriesAllowed) is { } error) + { + problems.Add(new(rule.Key + "." + MaskField, error)); + } + } + + return problems; + } + + /// The rules of a company, every table included (the default where the company set nothing). + /// Who reads. + /// The company. + /// Cancellation. + /// The rules, in the order of . + public async Task> RulesAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(permissions, actor, companyCode, TableService.ReadPermission, cancellationToken).ConfigureAwait(false); + return await ReadRulesAsync(company, cancellationToken).ConfigureAwait(false); + } + + /// The rule of one table, for the services that save its records (no permission check). + /// The company. + /// The rule key. + /// Cancellation. + /// The rule. + public async Task RuleAsync(string companyCode, string key, CancellationToken cancellationToken = default) + { + _ = Definition(key); + return (await ReadRulesAsync(CompanyCodes.Normalize(companyCode), cancellationToken).ConfigureAwait(false)).First(r => r.Key == key); + } + + /// Saves the rules of a company. + /// Who saves. + /// The company. + /// The rules (tables left out keep their rule). + /// Cancellation. + /// The rules now in force. + /// A mask is not valid (<key>.Mask:code). + public async Task> SaveAsync(Actor actor, string companyCode, IReadOnlyList rules, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(rules); + var company = await CompanyGuard.DemandAsync(permissions, actor, companyCode, TableService.WritePermission, cancellationToken).ConfigureAwait(false); + var problems = Validate(rules); + if (problems.Count > 0) + { + throw new ValidationFailedException([.. problems.Select(p => p.Field + ":" + p.Code)]); + } + + var values = new Dictionary(StringComparer.Ordinal); + foreach (var rule in rules) + { + values[SettingPrefix + rule.Key + ".mask"] = CodeMask.Parse(rule.Mask).Text; + values[SettingPrefix + rule.Key + ".manual"] = rule.AllowManual ? "true" : "false"; + if (rule.Key == "items") + { + values[SettingPrefix + "items.unique-barcode"] = rule.UniqueBarcode ? "true" : "false"; + } + } + + await settings.SetManyAsync(actor, company, values, cancellationToken).ConfigureAwait(false); + return await ReadRulesAsync(company, cancellationToken).ConfigureAwait(false); + } + + /// The code the next record would get, without taking it. + /// Who asks. + /// The company. + /// The rule, possibly not saved yet. + /// The date of the record (for masks with the year). + /// The category (for masks with the category). + /// Cancellation. + /// The code, or when the mask is not valid. + public async Task PreviewAsync(Actor actor, string companyCode, CodeRule rule, DateOnly date, string? category, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(rule); + var company = await CompanyGuard.DemandAsync(permissions, actor, companyCode, TableService.ReadPermission, cancellationToken).ConfigureAwait(false); + if (!CodeMask.TryParse(rule.Mask, out var mask, out _) || (mask!.UsesCategory && string.IsNullOrWhiteSpace(category))) + { + return null; + } + + await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var key = mask.SequenceKey(rule.Key, date.Year, category); + var last = await uow.Repository().FindAsync(Query.For().Where(s => s.Key == key), cancellationToken).ConfigureAwait(false); + return mask.Format((last?.LastValue ?? 0) + 1, date.Year, category); + } + + /// + /// Takes the next free code inside the caller's transaction; the number is used up only if the transaction commits. + /// + /// The unit of work of the save, with a transaction open. + /// The rule. + /// The date of the record. + /// The category, for masks with the category. + /// Whether a code is already used in the table. + /// Cancellation. + /// The code. + /// No category, code too long, or no free code (Code:code). + public static async Task AssignAsync(IUnitOfWork unitOfWork, CodeRule rule, DateOnly date, string? category, + Func> taken, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(unitOfWork); + ArgumentNullException.ThrowIfNull(rule); + ArgumentNullException.ThrowIfNull(taken); + var definition = Definition(rule.Key); + var mask = CodeMask.Parse(rule.Mask); + if (mask.UsesCategory && string.IsNullOrWhiteSpace(category)) + { + throw new ValidationFailedException([CodeField + ":" + CategoryRequired]); + } + + var key = mask.SequenceKey(rule.Key, date.Year, category); + await unitOfWork.AcquireLockAsync("code:" + key, cancellationToken).ConfigureAwait(false); + var repository = unitOfWork.Repository(); + var sequence = await repository.FindAsync(Query.For().Where(s => s.Key == key), cancellationToken).ConfigureAwait(false) + ?? new CodeSequence { Key = key }; + for (var skip = 0; skip < MaxSkips; skip++) + { + sequence.LastValue++; + var code = mask.Format(sequence.LastValue, date.Year, category); + if (code.Length > definition.MaxLength) + { + throw new ValidationFailedException([CodeField + ":" + CodeTooLong]); + } + + if (await taken(code, cancellationToken).ConfigureAwait(false)) + { + continue; + } + + if (sequence.Id == 0) + { + await repository.InsertAsync(sequence, cancellationToken).ConfigureAwait(false); + } + else + { + await repository.UpdateAsync(sequence, cancellationToken).ConfigureAwait(false); + } + + return code; + } + + throw new ValidationFailedException([CodeField + ":" + Exhausted]); + } + + /// Checks a code written by hand against the rule. + /// The rule. + /// The code, empty to get the automatic one. + /// The error code, or . + public static string? CheckManual(CodeRule rule, string? code) + { + ArgumentNullException.ThrowIfNull(rule); + if (string.IsNullOrWhiteSpace(code)) + { + return null; + } + + if (!rule.AllowManual) + { + return ManualNotAllowed; + } + + return code.Trim().Length > Definition(rule.Key).MaxLength ? CodeTooLong : null; + } + + private async Task> ReadRulesAsync(string company, CancellationToken cancellationToken) + { + var values = await settings.GetAllAsync(company, SettingPrefix, cancellationToken).ConfigureAwait(false); + return + [ + .. Definitions.Select(d => + { + var rule = DefaultRule(d); + var mask = values.GetValueOrDefault(SettingPrefix + d.Key + ".mask"); + return rule with + { + Mask = mask is { Length: > 0 } && CodeMask.Check(mask, d.MaxLength, d.CategoriesAllowed) is null ? mask : rule.Mask, + AllowManual = ReadFlag(values, SettingPrefix + d.Key + ".manual", rule.AllowManual), + UniqueBarcode = d.Key == "items" && ReadFlag(values, SettingPrefix + "items.unique-barcode", rule.UniqueBarcode), + }; + }), + ]; + } + + private static bool ReadFlag(IReadOnlyDictionary values, string key, bool fallback) => + values.TryGetValue(key, out var value) && bool.TryParse(value, out var flag) ? flag : fallback; +} + diff --git a/src/Khaemhat.Application/Tables/ExchangeRates.cs b/src/Khaemhat.Application/Tables/ExchangeRates.cs index cad1654..7955f52 100644 --- a/src/Khaemhat.Application/Tables/ExchangeRates.cs +++ b/src/Khaemhat.Application/Tables/ExchangeRates.cs @@ -176,11 +176,15 @@ public sealed class ExchangeRateService } } -/// Loads the ECB reference rates into every active company (SPEC §11.12 "cambi BCE"), on working days. +/// +/// Loads the ECB reference rates into every active company (SPEC §11.12 "cambi BCE"), on working days; a company that +/// switched the option off in its preferences is skipped. +/// /// The ECB client. /// The exchange rates. /// The companies. -public sealed class EcbRatesJob(EcbRatesClient client, ExchangeRateService rates, ICompanyRegistry companies) : IScheduledJob +/// The automatic filling options. +public sealed class EcbRatesJob(EcbRatesClient client, ExchangeRateService rates, ICompanyRegistry companies, AutoFillService autoFill) : IScheduledJob { /// The job type. public const string JobType = "tables.ecb-rates"; @@ -196,7 +200,7 @@ public sealed class EcbRatesJob(EcbRatesClient client, ExchangeRateService rates var changed = 0; foreach (var company in await companies.ListAsync(cancellationToken).ConfigureAwait(false)) { - if (company.Status is CompanyStatus.Active) + if (company.Status is CompanyStatus.Active && await autoFill.IsOnAsync(company.Code, AutoFillService.EcbRates, cancellationToken).ConfigureAwait(false)) { changed += await rates.StoreEcbAsync(company.Code, downloaded, cancellationToken).ConfigureAwait(false); } diff --git a/src/Khaemhat.Core/Tables/CodeRules.cs b/src/Khaemhat.Core/Tables/CodeRules.cs new file mode 100644 index 0000000..f0687ec --- /dev/null +++ b/src/Khaemhat.Core/Tables/CodeRules.cs @@ -0,0 +1,268 @@ +using System.Globalization; +using System.Text; +using Khaemhat.Core.Entities; + +namespace Khaemhat.Core.Tables; + +/// +/// The last number given by an automatic code sequence (code_sequences, SPEC §11.12). One row per rule and, +/// when the mask asks for it, per year and per category: the key is items:VALV or leads:2026. +/// +public sealed class CodeSequence : Entity +{ + /// The key of the sequence, see . + public string Key { get; set; } = string.Empty; + + /// The last number given; the next code uses this plus one. + public long LastValue { get; set; } +} + +/// +/// A mask of automatic codes (SPEC §11.12, mockup 074), such as C{seq:000000} or {categoria}-{seq:0000}: +/// letters, digits and - _ / . written as they are, plus the placeholders {seq:000} (the progressive +/// number with as many digits as zeros; {seq} without zeros in front), {anno} (the year, four digits; also +/// {year}) and {categoria} (the code of the category; also {category}). The number restarts every +/// year when the mask has the year, and runs separately per category when it has the category. +/// +public sealed record CodeMask +{ + /// Error: the mask needs exactly one {seq}. + public const string SequenceRequired = "codes.mask.sequence"; + + /// Error: a placeholder is not known. + public const string UnknownPlaceholder = "codes.mask.placeholder"; + + /// Error: the mask has characters not allowed in a code. + public const string InvalidCharacter = "codes.mask.character"; + + /// Error: the codes of the mask are longer than the code column. + public const string TooLong = "codes.mask.too-long"; + + /// Error: the mask uses the category for a table without categories. + public const string CategoryNotAllowed = "codes.mask.category"; + + private const string AllowedLiterals = "-_/."; + + private readonly IReadOnlyList _parts; + + private CodeMask(string text, IReadOnlyList parts) + { + Text = text; + _parts = parts; + Digits = parts.First(p => p.Kind == PartKind.Sequence).Digits; + UsesYear = parts.Any(p => p.Kind == PartKind.Year); + UsesCategory = parts.Any(p => p.Kind == PartKind.Category); + FixedLength = parts.Sum(p => p.Kind switch + { + PartKind.Literal => p.Text.Length, + PartKind.Year => 4, + PartKind.Sequence => Math.Max(1, p.Digits), + _ => 0, + }); + } + + private enum PartKind + { + Literal, + Sequence, + Year, + Category, + } + + /// The mask, with the written characters in upper case. + public string Text { get; } + + /// The digits of the number (0: as many as needed). + public int Digits { get; } + + /// Whether the number restarts every year. + public bool UsesYear { get; } + + /// Whether the code contains the category and the number runs per category. + public bool UsesCategory { get; } + + /// The length of a code without the category, with the number at its minimum width. + public int FixedLength { get; } + + /// Reads a mask. + /// The mask as typed. + /// The mask, when valid. + /// The error code, when not. + /// when valid. + public static bool TryParse(string? text, out CodeMask? mask, out string? error) + { + mask = null; + error = null; + var value = text?.Trim() ?? string.Empty; + var parts = new List(); + var literal = new StringBuilder(); + var i = 0; + while (i < value.Length) + { + var c = value[i]; + if (c == '{') + { + var end = value.IndexOf('}', i); + if (end < 0) + { + error = UnknownPlaceholder; + return false; + } + + if (literal.Length > 0) + { + parts.Add(new Part(PartKind.Literal, literal.ToString(), 0)); + literal.Clear(); + } + + if (!TryReadPlaceholder(value[(i + 1)..end], out var part)) + { + error = UnknownPlaceholder; + return false; + } + + parts.Add(part); + i = end + 1; + continue; + } + + var upper = char.ToUpperInvariant(c); + if (!(upper is >= 'A' and <= 'Z' or >= '0' and <= '9') && !AllowedLiterals.Contains(upper, StringComparison.Ordinal)) + { + error = InvalidCharacter; + return false; + } + + literal.Append(upper); + i++; + } + + if (literal.Length > 0) + { + parts.Add(new Part(PartKind.Literal, literal.ToString(), 0)); + } + + if (parts.Count(p => p.Kind == PartKind.Sequence) != 1) + { + error = SequenceRequired; + return false; + } + + mask = new CodeMask(string.Concat(parts.Select(p => p.ToMask())), parts); + return true; + } + + /// Reads a mask that is known to be valid. + /// The mask. + /// The mask. + /// The mask is not valid. + public static CodeMask Parse(string text) => + TryParse(text, out var mask, out var error) ? mask! : throw new FormatException(error); + + /// The checks of a mask for a table. + /// The mask as typed. + /// The longest code the table accepts. + /// Whether the table has categories. + /// The error code, or when the mask can be used. + public static string? Check(string? text, int maxLength, bool categoriesAllowed) + { + if (!TryParse(text, out var mask, out var error)) + { + return error; + } + + if (mask!.UsesCategory && !categoriesAllowed) + { + return CategoryNotAllowed; + } + + // A category adds at least one character. + return mask.FixedLength + (mask.UsesCategory ? 1 : 0) > maxLength ? TooLong : null; + } + + /// The key of the sequence a code of this mask takes its number from. + /// The rule, such as customers. + /// The year of the record. + /// The category code, for masks with the category. + /// The key, such as items:VALV or leads:2026. + public string SequenceKey(string rule, int year, string? category) + { + ArgumentException.ThrowIfNullOrWhiteSpace(rule); + var key = new StringBuilder(rule); + if (UsesYear) + { + key.Append(':').Append(year.ToString("D4", CultureInfo.InvariantCulture)); + } + + if (UsesCategory) + { + key.Append(':').Append(Normalize(category)); + } + + return key.ToString(); + } + + /// Writes a code. + /// The progressive number. + /// The year. + /// The category code, for masks with the category. + /// The code. + public string Format(long number, int year, string? category) + { + ArgumentOutOfRangeException.ThrowIfNegative(number); + var code = new StringBuilder(); + foreach (var part in _parts) + { + code.Append(part.Kind switch + { + PartKind.Sequence => number.ToString(part.Digits > 0 ? "D" + part.Digits.ToString(CultureInfo.InvariantCulture) : "D", CultureInfo.InvariantCulture), + PartKind.Year => year.ToString("D4", CultureInfo.InvariantCulture), + PartKind.Category => Normalize(category), + _ => part.Text, + }); + } + + return code.ToString(); + } + + /// + public override string ToString() => Text; + + private static string Normalize(string? category) => (category ?? string.Empty).Trim().ToUpperInvariant(); + + private static bool TryReadPlaceholder(string body, out Part part) + { + var colon = body.IndexOf(':', StringComparison.Ordinal); + var name = (colon < 0 ? body : body[..colon]).Trim().ToUpperInvariant(); + var format = colon < 0 ? null : body[(colon + 1)..].Trim(); + part = default; + switch (name) + { + case "SEQ" when format is null: + part = new Part(PartKind.Sequence, string.Empty, 0); + return true; + case "SEQ" when format.Length is > 0 and <= 12 && format.All(c => c == '0'): + part = new Part(PartKind.Sequence, string.Empty, format.Length); + return true; + case "ANNO" or "YEAR" when format is null: + part = new Part(PartKind.Year, string.Empty, 0); + return true; + case "CATEGORIA" or "CATEGORY" when format is null: + part = new Part(PartKind.Category, string.Empty, 0); + return true; + default: + return false; + } + } + + private readonly record struct Part(PartKind Kind, string Text, int Digits) + { + public string ToMask() => Kind switch + { + PartKind.Sequence => Digits > 0 ? "{seq:" + new string('0', Digits) + "}" : "{seq}", + PartKind.Year => "{anno}", + PartKind.Category => "{categoria}", + _ => Text, + }; + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_015_CreateCodeSequences.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_015_CreateCodeSequences.cs new file mode 100644 index 0000000..68737ff --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_015_CreateCodeSequences.cs @@ -0,0 +1,23 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// The sequences of the automatic codes (SPEC §11.12): one row per rule, year and category. +[Migration(20261111_015, "create_code_sequences")] +public sealed class M20261111_015_CreateCodeSequences : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("code_sequences", t => + { + t.Id(); + t.String("key", 100).NotNull(); + t.Int64("last_value").NotNull(); + t.AuditColumns(); + t.Unique("ux_code_sequences_key", "key"); + }); + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/TableMaps.cs b/src/Khaemhat.Data/CompanyDatabase/TableMaps.cs index a0d2894..32419c1 100644 --- a/src/Khaemhat.Data/CompanyDatabase/TableMaps.cs +++ b/src/Khaemhat.Data/CompanyDatabase/TableMaps.cs @@ -435,3 +435,14 @@ public sealed class JobMap : EntityMap Map(x => x.Description).MaxLength(100); } } + +/// Map of to code_sequences. +public sealed class CodeSequenceMap : EntityMap +{ + /// Creates the map. + public CodeSequenceMap() + { + ToTable("code_sequences"); + Map(x => x.Key).MaxLength(100); + } +} diff --git a/src/Khaemhat.Fiscal.Abstractions/Identifiers.cs b/src/Khaemhat.Fiscal.Abstractions/Identifiers.cs index 148a39e..ed657e2 100644 --- a/src/Khaemhat.Fiscal.Abstractions/Identifiers.cs +++ b/src/Khaemhat.Fiscal.Abstractions/Identifiers.cs @@ -83,10 +83,10 @@ public interface ITaxIdentifierRules /// A bank found from its national code. /// The national bank code (Italy: ABI). -/// The name of the bank. +/// The name of the bank, when the directory does not know it. /// The BIC, when known. /// The branch code (Italy: CAB), when the IBAN has one. -public sealed record BankInfo(string BankCode, string Name, string? Bic, string? BranchCode); +public sealed record BankInfo(string BankCode, string? Name, string? Bic, string? BranchCode); /// The country's directory of banks, to fill bank name and BIC from an IBAN. public interface IBankDirectory @@ -95,4 +95,9 @@ public interface IBankDirectory /// The IBAN. /// The bank, or if the IBAN is foreign, invalid or the bank unknown. BankInfo? FindByIban(string? iban); + + /// The bank and branch codes of a domestic IBAN, with name and BIC when the directory knows the bank. + /// The IBAN. + /// The codes, or if the IBAN is foreign or invalid. + BankInfo? ReadIban(string? iban); } diff --git a/src/Khaemhat.Fiscal.Italy/ItalianIdentifiers.cs b/src/Khaemhat.Fiscal.Italy/ItalianIdentifiers.cs index 3017b53..7955f2a 100644 --- a/src/Khaemhat.Fiscal.Italy/ItalianIdentifiers.cs +++ b/src/Khaemhat.Fiscal.Italy/ItalianIdentifiers.cs @@ -346,4 +346,10 @@ public sealed class ItalianBankDirectory : IBankDirectory /// public BankInfo? FindByIban(string? iban) => CodesOf(iban) is { } codes && _byAbi.TryGetValue(codes.Abi, out var bank) ? bank with { BranchCode = codes.Cab } : null; + + /// + public BankInfo? ReadIban(string? iban) => + CodesOf(iban) is not { } codes ? null + : _byAbi.TryGetValue(codes.Abi, out var bank) ? bank with { BranchCode = codes.Cab } + : new BankInfo(codes.Abi, null, null, codes.Cab); } diff --git a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs index 73755e6..e1b6623 100644 --- a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs +++ b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs @@ -20,6 +20,9 @@ public sealed class ItalyFiscalPack : FiscalPackBase AddFeature(new F24Exporter()); AddFeature(new ItalianTaxIdentifierRules()); AddFeature(new ItalianBaseTables()); + + // ABI and CAB are read from every Italian IBAN; bank names and BICs arrive with the ABI list (ADR 0026). + AddFeature(new ItalianBankDirectory([])); } /// diff --git a/src/Khaemhat.Web/Components/Pages/Profile.razor b/src/Khaemhat.Web/Components/Pages/Profile.razor index 33a19cb..9d83547 100644 --- a/src/Khaemhat.Web/Components/Pages/Profile.razor +++ b/src/Khaemhat.Web/Components/Pages/Profile.razor @@ -99,7 +99,7 @@
@foreach (var density in Enum.GetValues()) { - }
@@ -110,7 +110,7 @@
@foreach (var size in UserPreferences.TextSizes) { - }
@@ -121,7 +121,7 @@
@foreach (var (value, key) in MenuChoices) { - }
diff --git a/src/Khaemhat.Web/Components/Pages/Tables/CompanyPreferencesPage.razor b/src/Khaemhat.Web/Components/Pages/Tables/CompanyPreferencesPage.razor new file mode 100644 index 0000000..eec751b --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Tables/CompanyPreferencesPage.razor @@ -0,0 +1,249 @@ +@page "/tabelle/preferenze" +@attribute [Authorize] +@using Khaemhat.Application.Licensing +@using Khaemhat.Application.Security +@using Khaemhat.Application.Tables +@using Khaemhat.Core.Tables +@using Khaemhat.Web.Tables +@inject ShellSession Session +@inject CodeRuleService Codes +@inject AutoFillService AutoFill +@inject TableService Tables +@inject ILicenseGate License +@inject ToastService Toasts +@inject TimeProvider Clock + +@* Company preferences (SPEC §11.12, mockup 074): the masks of the automatic codes with the preview of the next code, + and the automatic filling options. The other tabs of the mockup arrive with the documents and the e-mails. *@ + + + +
+
+
@T["Shell.Menu.CompanyTables"] / @T["CompanyPreferences.Title"]
+

@T["CompanyPreferences.Heading"]

+
@T["CompanyPreferences.Hint"]
+
+
+ @if (_modified) + { + @T["CompanyTables.Modified"] + } +
+ + +
+
+ + @if (_loaded) + { +
+ + @if (_tab == "codes") + { + + @foreach (var group in CodeRuleService.Definitions.GroupBy(d => d.Group)) + { + + @foreach (var definition in group) + { + var rule = _rules[definition.Key]; + + } + + @if (group.Key == "items") + { + + } + + } + +

@T["CompanyPreferences.Numerators"] @T["CompanyPreferences.NumeratorsLink"]

+
+
+

@T["CompanyPreferences.Placeholders"]

+ } + else + { +
+ @foreach (var option in AutoFillService.Options) + { + + } +

@T["CompanyPreferences.AutoFillHint"]

+
+ } +
+ } +
+ +@code { + private readonly KhValidation _validation = new(); + private Dictionary _rules = new(StringComparer.Ordinal); + private Dictionary _savedRules = new(StringComparer.Ordinal); + private Dictionary _options = new(StringComparer.Ordinal); + private Dictionary _savedOptions = new(StringComparer.Ordinal); + private readonly Dictionary _previews = new(StringComparer.Ordinal); + private string? _category; + private string _tab = "codes"; + private bool _loaded; + private bool _modified; + private bool _busy; + + private bool CanWrite => Session.Permissions.Allows(TableService.WritePermission); + + private bool UniqueBarcode => _rules.TryGetValue("items", out var items) && items.UniqueBarcode; + + private IReadOnlyList TabItems => + [ + new("codes", "key", T["CompanyPreferences.Tabs.codes"], _validation.Messages.Count is > 0 and var n ? n : null), + new("autofill", "zap", T["CompanyPreferences.Tabs.autofill"], null), + ]; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(TableService.ReadPermission)) + { + _category = (await Tables.ActiveAsync(actor, company)).OrderBy(c => c.Code, StringComparer.Ordinal).FirstOrDefault()?.Code ?? "GEN"; + Show(await Codes.RulesAsync(actor, company), await AutoFill.OptionsAsync(actor, company)); + await PreviewAllAsync(); + _loaded = true; + } + } + + private void Show(IReadOnlyList rules, IReadOnlyDictionary options) + { + _rules = rules.ToDictionary(r => r.Key, StringComparer.Ordinal); + _savedRules = new(_rules, StringComparer.Ordinal); + _options = options.ToDictionary(o => o.Key, o => o.Value, StringComparer.Ordinal); + _savedOptions = new(_options, StringComparer.Ordinal); + _modified = false; + _validation.Clear(); + } + + private string HintOf(CodeRuleDefinition definition) + { + if (!License.IsModuleActive(definition.Module)) + { + return T.Format("CompanyPreferences.ModuleOff", definition.Module); + } + + return _previews.GetValueOrDefault(definition.Key) is { } next ? T.Format("CompanyPreferences.Next", next) : T["CompanyPreferences.NextInvalid"]; + } + + private static string GroupIcon(string group) => group switch + { + "parties" => "users", + "items" => "box", + _ => "target", + }; + + private async Task ChangeMaskAsync(string key, string? mask) + { + _rules[key] = _rules[key] with { Mask = (mask ?? string.Empty).Trim() }; + _modified = true; + await PreviewAsync(key); + } + + private void SetManual(string group, bool allow) + { + foreach (var definition in CodeRuleService.Definitions.Where(d => d.Group == group)) + { + _rules[definition.Key] = _rules[definition.Key] with { AllowManual = allow }; + } + + _modified = true; + } + + private void SetUniqueBarcode(bool unique) + { + _rules["items"] = _rules["items"] with { UniqueBarcode = unique }; + _modified = true; + } + + private void SetOption(string key, bool on) + { + if (!CanWrite) + { + return; + } + + _options[key] = on; + _modified = true; + } + + private async Task PreviewAllAsync() + { + foreach (var key in _rules.Keys.ToList()) + { + await PreviewAsync(key); + } + } + + private async Task PreviewAsync(string key) + { + if (Session.Actor is { } actor && Session.Company?.Code is { } company) + { + var today = DateOnly.FromDateTime(Clock.GetLocalNow().DateTime); + _previews[key] = await Codes.PreviewAsync(actor, company, _rules[key], today, _category); + } + } + + private async Task UndoAsync() + { + Show([.. _savedRules.Values], _savedOptions); + await PreviewAllAsync(); + } + + private async Task SaveAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _busy = true; + _validation.Clear(); + try + { + var problems = CodeRuleService.Validate(_rules.Values); + if (problems.Count > 0) + { + Refuse(problems.Select(p => ((string?)p.Field, p.Code))); + return; + } + + var rules = await Codes.SaveAsync(actor, company, [.. _rules.Values]); + var options = await AutoFill.SaveOptionsAsync(actor, company, _options); + Show(rules, options); + await PreviewAllAsync(); + Toasts.Show(ToastKind.Success, T["CompanyPreferences.Saved"], null); + } + catch (ValidationFailedException ex) + { + Refuse(ex.Errors.Select(TableValues.SplitError)); + } + finally + { + _busy = false; + } + } + + private void Refuse(IEnumerable<(string? Field, string Code)> errors) + { + foreach (var (field, code) in errors) + { + _validation.Add(field, T.Contains(code) ? T[code] : T["CompanyTables.UnknownError"]); + } + + _tab = "codes"; + Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], T["CompanyTables.FixFields"]); + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Tables/TablesIndex.razor b/src/Khaemhat.Web/Components/Pages/Tables/TablesIndex.razor index 15cca65..3623d55 100644 --- a/src/Khaemhat.Web/Components/Pages/Tables/TablesIndex.razor +++ b/src/Khaemhat.Web/Components/Pages/Tables/TablesIndex.razor @@ -41,6 +41,7 @@ [ ("/tabelle/profilo-azienda", "building", "CompanyTables.Profile.Title", "CompanyTables.Profile.Hint"), ("/tabelle/esercizi", "calendar", "CompanyTables.FiscalYears.Title", "CompanyTables.FiscalYears.Hint"), + ("/tabelle/preferenze", "settings", "CompanyPreferences.Title", "CompanyPreferences.Hint"), ("/tabelle/cambi", "euro", "CompanyTables.Rates.Title", "CompanyTables.Rates.Hint"), ]; } diff --git a/src/Khaemhat.Web/Components/Ui/KhSwitchRow.razor b/src/Khaemhat.Web/Components/Ui/KhSwitchRow.razor index 03780f0..8741e90 100644 --- a/src/Khaemhat.Web/Components/Ui/KhSwitchRow.razor +++ b/src/Khaemhat.Web/Components/Ui/KhSwitchRow.razor @@ -1,5 +1,5 @@ @* An on/off option with its label and a short explanation (mockup 008). The whole row is the switch. *@ -