M4 · Tabelle, anagrafiche, articoli (v0.4.0) #121

Merged
Alby96 merged 12 commits from feat/37-tabelle-anagrafiche into main 2026-11-12 13:03:38 +01:00
27 changed files with 1627 additions and 40 deletions
Showing only changes of commit 07555de700 - Show all commits

No files matched your search

+7
View File
@@ -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
+16
View File
@@ -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 |
+4 -4
View File
@@ -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`,
@@ -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.<archivio>.mask`, `codes.<archivio>.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.<opzione>`); 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.
+42 -24
View File
@@ -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
@@ -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;
/// <summary>A municipality proposed for an address.</summary>
/// <param name="MunicipalityCode">The code of the municipality (Italy: cadastral code).</param>
/// <param name="Name">The name.</param>
/// <param name="ProvinceCode">The province.</param>
/// <param name="Region">The region.</param>
/// <param name="PostalCode">The postal code: the one typed, or the only one of the municipality.</param>
public sealed record PlaceSuggestion(string MunicipalityCode, string Name, string ProvinceCode, string? Region, string? PostalCode);
/// <summary>An option of the automatic filling (mockup 074).</summary>
/// <param name="Key">The key, also the setting <c>autofill.&lt;key&gt;</c>.</param>
/// <param name="Default">Whether it is on in a new company.</param>
public sealed record AutoFillOption(string Key, bool Default = true);
/// <summary>
/// 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 <see cref="IsOnAsync"/> before
/// filling. The defaults that documents take from the customer and the document type come with the documents (M5).
/// </summary>
/// <param name="tables">The company tables.</param>
/// <param name="fiscal">The fiscal pack of the company.</param>
/// <param name="settings">The company settings.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="vies">The VIES client.</param>
public sealed class AutoFillService(TableService tables, CompanyFiscalContext fiscal, CompanySettingsService settings, PermissionService permissions, ViesClient vies)
{
/// <summary>The start of the setting keys.</summary>
public const string SettingPrefix = "autofill.";
/// <summary>Municipality, province and region from the postal code.</summary>
public const string PostalCode = "postal-code";
/// <summary>Personal tax code from the personal data.</summary>
public const string TaxCode = "tax-code";
/// <summary>VIES check of EU VAT numbers when saving.</summary>
public const string Vies = "vies";
/// <summary>Bank and BIC from the IBAN.</summary>
public const string BankFromIban = "bank-from-iban";
/// <summary>Daily ECB exchange rates.</summary>
public const string EcbRates = "ecb-rates";
/// <summary>Item description copied into document lines.</summary>
public const string ItemDescription = "item-description";
/// <summary>Last price charged to the customer shown as reference.</summary>
public const string LastPrice = "last-price";
/// <summary>Start from the last similar document of the customer.</summary>
public const string LastDocument = "last-document";
/// <summary>Delivery date = document date + lead time.</summary>
public const string DeliveryDate = "delivery-date";
/// <summary>Revenue and cost accounts from item, category and reason.</summary>
public const string Accounts = "accounts";
private const int MaxSuggestions = 20;
/// <summary>The options, in the order of the preferences page.</summary>
public static readonly IReadOnlyList<AutoFillOption> Options =
[
new(PostalCode), new(TaxCode), new(Vies), new(BankFromIban), new(EcbRates),
new(ItemDescription), new(LastPrice), new(LastDocument, Default: false), new(DeliveryDate), new(Accounts),
];
/// <summary>The options of a company.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Whether each option is on, by key.</returns>
public async Task<IReadOnlyDictionary<string, bool>> 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);
}
/// <summary>Whether an option is on, for the forms and services that fill fields (no permission check).</summary>
/// <param name="companyCode">The company.</param>
/// <param name="key">The option.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns><see langword="true"/> when on.</returns>
public async Task<bool> IsOnAsync(string companyCode, string key, CancellationToken cancellationToken = default) =>
(await ReadAsync(companyCode, cancellationToken).ConfigureAwait(false)).GetValueOrDefault(key);
/// <summary>Saves the options of a company.</summary>
/// <param name="actor">Who saves.</param>
/// <param name="companyCode">The company.</param>
/// <param name="values">The options to change, by key.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The options now in force.</returns>
public async Task<IReadOnlyDictionary<string, bool>> SaveOptionsAsync(Actor actor, string companyCode, IReadOnlyDictionary<string, bool> 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);
}
/// <summary>The municipalities with a postal code.</summary>
/// <param name="actor">Who asks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="postalCode">The postal code.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The municipalities, by name; empty when none or when the code is not complete.</returns>
public async Task<IReadOnlyList<PlaceSuggestion>> 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)),
];
}
/// <summary>The municipalities whose name starts with some text.</summary>
/// <param name="actor">Who asks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="name">The start of the name.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The municipalities, exact name first.</returns>
public async Task<IReadOnlyList<PlaceSuggestion>> 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)),
];
}
/// <summary>Whether a postal code is in a list such as <c>10121,10122</c> or <c>00118-00199</c>.</summary>
/// <param name="list">The postal codes of a municipality.</param>
/// <param name="code">The postal code.</param>
/// <returns><see langword="true"/> when it is one of them.</returns>
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;
}
/// <summary>The personal tax code of a person, computed by the fiscal pack of the company.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="data">The personal data.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The code, or <see langword="null"/> when the country has no such code or the data are incomplete.</returns>
public async Task<string?> PersonalTaxCodeAsync(string companyCode, PersonalTaxCodeData data, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(data);
var pack = await fiscal.PackOfAsync(companyCode, cancellationToken).ConfigureAwait(false);
if (pack.GetFeature<ITaxIdentifierRules>() 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;
}
}
/// <summary>Checks an EU VAT number with VIES.</summary>
/// <param name="countryCode">The ISO country code.</param>
/// <param name="vatNumber">The number.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The outcome; a service that does not answer gives <see cref="ViesStatus.Unavailable"/>.</returns>
public Task<ViesResult> CheckVatAsync(string countryCode, string vatNumber, CancellationToken cancellationToken = default) =>
vies.CheckAsync(countryCode, vatNumber, cancellationToken);
/// <summary>
/// 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.
/// </summary>
/// <param name="actor">Who asks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="iban">The IBAN.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The bank, or <see langword="null"/> when the IBAN is not a domestic one.</returns>
public async Task<BankInfo?> BankFromIbanAsync(Actor actor, string companyCode, string? iban, CancellationToken cancellationToken = default)
{
var pack = await fiscal.PackOfAsync(companyCode, cancellationToken).ConfigureAwait(false);
if (pack.GetFeature<IBankDirectory>() is not { } directory || directory.ReadIban(iban) is not { } bank)
{
return null;
}
if (bank.Name is not null)
{
return bank;
}
var known = (await tables.ActiveAsync<BankAccount>(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;
}
/// <summary>The delivery date of a record: its date plus the lead time, moved to the next working day.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="date">The date of the document.</param>
/// <param name="leadTimeDays">The lead time in calendar days.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The date.</returns>
public async Task<DateOnly> 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<IReadOnlyList<Municipality>> MunicipalitiesAsync(Actor actor, string companyCode, CancellationToken cancellationToken) =>
await tables.ActiveAsync<Municipality>(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<IReadOnlyDictionary<string, bool>> 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);
}
}
@@ -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;
/// <summary>A table whose codes can be given automatically (SPEC §11.12, mockup 074).</summary>
/// <param name="Key">The rule key, also the start of the sequence keys, such as <c>customers</c>.</param>
/// <param name="Group">The box of the preferences page: <c>parties</c>, <c>items</c> or <c>crm</c>.</param>
/// <param name="DefaultMask">The mask of a new company.</param>
/// <param name="Module">The licence module the table belongs to.</param>
/// <param name="CategoriesAllowed">Whether the mask may use the category.</param>
/// <param name="MaxLength">The longest code the table accepts.</param>
public sealed record CodeRuleDefinition(string Key, string Group, string DefaultMask, string Module, bool CategoriesAllowed = false, int MaxLength = 20);
/// <summary>The automatic code of a table as the company set it.</summary>
/// <param name="Key">The rule key.</param>
/// <param name="Mask">The mask.</param>
/// <param name="AllowManual">Whether a user may write a code instead of the automatic one.</param>
/// <param name="UniqueBarcode">Items only: refuse two items with the same EAN.</param>
public sealed record CodeRule(string Key, string Mask, bool AllowManual, bool UniqueBarcode = false);
/// <summary>
/// The automatic codes of a company (SPEC §11.12): the mask of each table in the company settings
/// (<c>codes.&lt;table&gt;.mask</c>, <c>codes.&lt;table&gt;.manual</c>) and the numbers in <c>code_sequences</c>, 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.
/// </summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="settings">The company settings.</param>
public sealed class CodeRuleService(IUnitOfWorkFactory factory, PermissionService permissions, CompanySettingsService settings)
{
/// <summary>The start of the setting keys.</summary>
public const string SettingPrefix = "codes.";
/// <summary>Error: the code was written by hand where only automatic codes are allowed.</summary>
public const string ManualNotAllowed = "codes.manual";
/// <summary>Error: the mask uses the category and the record has none.</summary>
public const string CategoryRequired = "codes.category-required";
/// <summary>Error: the code is longer than the table accepts.</summary>
public const string CodeTooLong = "codes.too-long";
/// <summary>Error: no free code was found (too many codes taken by hand).</summary>
public const string Exhausted = "codes.exhausted";
/// <summary>The field the errors of a record's code are reported on.</summary>
public const string CodeField = "Code";
/// <summary>The field the errors of a mask are reported on.</summary>
public const string MaskField = "Mask";
private const int MaxSkips = 1000;
/// <summary>The tables with automatic codes and their masks of SPEC §11.12.</summary>
public static readonly IReadOnlyList<CodeRuleDefinition> 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),
];
/// <summary>The definition of a rule.</summary>
/// <param name="key">The rule key.</param>
/// <returns>The definition.</returns>
/// <exception cref="KeyNotFoundException">The key is not a rule.</exception>
public static CodeRuleDefinition Definition(string key) =>
Definitions.FirstOrDefault(d => d.Key == key) ?? throw new KeyNotFoundException("Unknown code rule " + key + ".");
/// <summary>The rule of a new company.</summary>
/// <param name="definition">The table.</param>
/// <returns>The rule.</returns>
public static CodeRule DefaultRule(CodeRuleDefinition definition)
{
ArgumentNullException.ThrowIfNull(definition);
return new CodeRule(definition.Key, definition.DefaultMask, AllowManual: true, UniqueBarcode: definition.Key == "items");
}
/// <summary>Checks a set of rules.</summary>
/// <param name="rules">The rules.</param>
/// <returns>The errors, on <c>&lt;key&gt;.Mask</c>.</returns>
public static IReadOnlyList<TableProblem> Validate(IEnumerable<CodeRule> rules)
{
ArgumentNullException.ThrowIfNull(rules);
var problems = new List<TableProblem>();
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;
}
/// <summary>The rules of a company, every table included (the default where the company set nothing).</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rules, in the order of <see cref="Definitions"/>.</returns>
public async Task<IReadOnlyList<CodeRule>> 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);
}
/// <summary>The rule of one table, for the services that save its records (no permission check).</summary>
/// <param name="companyCode">The company.</param>
/// <param name="key">The rule key.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rule.</returns>
public async Task<CodeRule> RuleAsync(string companyCode, string key, CancellationToken cancellationToken = default)
{
_ = Definition(key);
return (await ReadRulesAsync(CompanyCodes.Normalize(companyCode), cancellationToken).ConfigureAwait(false)).First(r => r.Key == key);
}
/// <summary>Saves the rules of a company.</summary>
/// <param name="actor">Who saves.</param>
/// <param name="companyCode">The company.</param>
/// <param name="rules">The rules (tables left out keep their rule).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rules now in force.</returns>
/// <exception cref="ValidationFailedException">A mask is not valid (<c>&lt;key&gt;.Mask:code</c>).</exception>
public async Task<IReadOnlyList<CodeRule>> SaveAsync(Actor actor, string companyCode, IReadOnlyList<CodeRule> 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<string, string?>(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);
}
/// <summary>The code the next record would get, without taking it.</summary>
/// <param name="actor">Who asks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="rule">The rule, possibly not saved yet.</param>
/// <param name="date">The date of the record (for masks with the year).</param>
/// <param name="category">The category (for masks with the category).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The code, or <see langword="null"/> when the mask is not valid.</returns>
public async Task<string?> 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<CodeSequence, long>().FindAsync(Query.For<CodeSequence>().Where(s => s.Key == key), cancellationToken).ConfigureAwait(false);
return mask.Format((last?.LastValue ?? 0) + 1, date.Year, category);
}
/// <summary>
/// Takes the next free code inside the caller's transaction; the number is used up only if the transaction commits.
/// </summary>
/// <param name="unitOfWork">The unit of work of the save, with a transaction open.</param>
/// <param name="rule">The rule.</param>
/// <param name="date">The date of the record.</param>
/// <param name="category">The category, for masks with the category.</param>
/// <param name="taken">Whether a code is already used in the table.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The code.</returns>
/// <exception cref="ValidationFailedException">No category, code too long, or no free code (<c>Code:code</c>).</exception>
public static async Task<string> AssignAsync(IUnitOfWork unitOfWork, CodeRule rule, DateOnly date, string? category,
Func<string, CancellationToken, Task<bool>> 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<CodeSequence, long>();
var sequence = await repository.FindAsync(Query.For<CodeSequence>().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]);
}
/// <summary>Checks a code written by hand against the rule.</summary>
/// <param name="rule">The rule.</param>
/// <param name="code">The code, empty to get the automatic one.</param>
/// <returns>The error code, or <see langword="null"/>.</returns>
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<IReadOnlyList<CodeRule>> 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<string, string?> values, string key, bool fallback) =>
values.TryGetValue(key, out var value) && bool.TryParse(value, out var flag) ? flag : fallback;
}
@@ -176,11 +176,15 @@ public sealed class ExchangeRateService
}
}
/// <summary>Loads the ECB reference rates into every active company (SPEC §11.12 "cambi BCE"), on working days.</summary>
/// <summary>
/// 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.
/// </summary>
/// <param name="client">The ECB client.</param>
/// <param name="rates">The exchange rates.</param>
/// <param name="companies">The companies.</param>
public sealed class EcbRatesJob(EcbRatesClient client, ExchangeRateService rates, ICompanyRegistry companies) : IScheduledJob
/// <param name="autoFill">The automatic filling options.</param>
public sealed class EcbRatesJob(EcbRatesClient client, ExchangeRateService rates, ICompanyRegistry companies, AutoFillService autoFill) : IScheduledJob
{
/// <summary>The job type.</summary>
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);
}
+268
View File
@@ -0,0 +1,268 @@
using System.Globalization;
using System.Text;
using Khaemhat.Core.Entities;
namespace Khaemhat.Core.Tables;
/// <summary>
/// The last number given by an automatic code sequence (<c>code_sequences</c>, SPEC §11.12). One row per rule and,
/// when the mask asks for it, per year and per category: the key is <c>items:VALV</c> or <c>leads:2026</c>.
/// </summary>
public sealed class CodeSequence : Entity<long>
{
/// <summary>The key of the sequence, see <see cref="CodeMask.SequenceKey"/>.</summary>
public string Key { get; set; } = string.Empty;
/// <summary>The last number given; the next code uses this plus one.</summary>
public long LastValue { get; set; }
}
/// <summary>
/// A mask of automatic codes (SPEC §11.12, mockup 074), such as <c>C{seq:000000}</c> or <c>{categoria}-{seq:0000}</c>:
/// letters, digits and <c>- _ / .</c> written as they are, plus the placeholders <c>{seq:000}</c> (the progressive
/// number with as many digits as zeros; <c>{seq}</c> without zeros in front), <c>{anno}</c> (the year, four digits; also
/// <c>{year}</c>) and <c>{categoria}</c> (the code of the category; also <c>{category}</c>). The number restarts every
/// year when the mask has the year, and runs separately per category when it has the category.
/// </summary>
public sealed record CodeMask
{
/// <summary>Error: the mask needs exactly one <c>{seq}</c>.</summary>
public const string SequenceRequired = "codes.mask.sequence";
/// <summary>Error: a placeholder is not known.</summary>
public const string UnknownPlaceholder = "codes.mask.placeholder";
/// <summary>Error: the mask has characters not allowed in a code.</summary>
public const string InvalidCharacter = "codes.mask.character";
/// <summary>Error: the codes of the mask are longer than the code column.</summary>
public const string TooLong = "codes.mask.too-long";
/// <summary>Error: the mask uses the category for a table without categories.</summary>
public const string CategoryNotAllowed = "codes.mask.category";
private const string AllowedLiterals = "-_/.";
private readonly IReadOnlyList<Part> _parts;
private CodeMask(string text, IReadOnlyList<Part> 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,
}
/// <summary>The mask, with the written characters in upper case.</summary>
public string Text { get; }
/// <summary>The digits of the number (0: as many as needed).</summary>
public int Digits { get; }
/// <summary>Whether the number restarts every year.</summary>
public bool UsesYear { get; }
/// <summary>Whether the code contains the category and the number runs per category.</summary>
public bool UsesCategory { get; }
/// <summary>The length of a code without the category, with the number at its minimum width.</summary>
public int FixedLength { get; }
/// <summary>Reads a mask.</summary>
/// <param name="text">The mask as typed.</param>
/// <param name="mask">The mask, when valid.</param>
/// <param name="error">The error code, when not.</param>
/// <returns><see langword="true"/> when valid.</returns>
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<Part>();
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;
}
/// <summary>Reads a mask that is known to be valid.</summary>
/// <param name="text">The mask.</param>
/// <returns>The mask.</returns>
/// <exception cref="FormatException">The mask is not valid.</exception>
public static CodeMask Parse(string text) =>
TryParse(text, out var mask, out var error) ? mask! : throw new FormatException(error);
/// <summary>The checks of a mask for a table.</summary>
/// <param name="text">The mask as typed.</param>
/// <param name="maxLength">The longest code the table accepts.</param>
/// <param name="categoriesAllowed">Whether the table has categories.</param>
/// <returns>The error code, or <see langword="null"/> when the mask can be used.</returns>
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;
}
/// <summary>The key of the sequence a code of this mask takes its number from.</summary>
/// <param name="rule">The rule, such as <c>customers</c>.</param>
/// <param name="year">The year of the record.</param>
/// <param name="category">The category code, for masks with the category.</param>
/// <returns>The key, such as <c>items:VALV</c> or <c>leads:2026</c>.</returns>
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();
}
/// <summary>Writes a code.</summary>
/// <param name="number">The progressive number.</param>
/// <param name="year">The year.</param>
/// <param name="category">The category code, for masks with the category.</param>
/// <returns>The code.</returns>
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();
}
/// <inheritdoc />
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,
};
}
}
@@ -0,0 +1,23 @@
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.CompanyDatabase.Migrations;
/// <summary>The sequences of the automatic codes (SPEC §11.12): one row per rule, year and category.</summary>
[Migration(20261111_015, "create_code_sequences")]
public sealed class M20261111_015_CreateCodeSequences : IMigration
{
/// <inheritdoc />
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");
});
}
}
@@ -435,3 +435,14 @@ public sealed class JobMap : EntityMap<Job>
Map(x => x.Description).MaxLength(100);
}
}
/// <summary>Map of <see cref="CodeSequence"/> to <c>code_sequences</c>.</summary>
public sealed class CodeSequenceMap : EntityMap<CodeSequence>
{
/// <summary>Creates the map.</summary>
public CodeSequenceMap()
{
ToTable("code_sequences");
Map(x => x.Key).MaxLength(100);
}
}
@@ -83,10 +83,10 @@ public interface ITaxIdentifierRules
/// <summary>A bank found from its national code.</summary>
/// <param name="BankCode">The national bank code (Italy: ABI).</param>
/// <param name="Name">The name of the bank.</param>
/// <param name="Name">The name of the bank, <see langword="null"/> when the directory does not know it.</param>
/// <param name="Bic">The BIC, when known.</param>
/// <param name="BranchCode">The branch code (Italy: CAB), when the IBAN has one.</param>
public sealed record BankInfo(string BankCode, string Name, string? Bic, string? BranchCode);
public sealed record BankInfo(string BankCode, string? Name, string? Bic, string? BranchCode);
/// <summary>The country's directory of banks, to fill bank name and BIC from an IBAN.</summary>
public interface IBankDirectory
@@ -95,4 +95,9 @@ public interface IBankDirectory
/// <param name="iban">The IBAN.</param>
/// <returns>The bank, or <see langword="null"/> if the IBAN is foreign, invalid or the bank unknown.</returns>
BankInfo? FindByIban(string? iban);
/// <summary>The bank and branch codes of a domestic IBAN, with name and BIC when the directory knows the bank.</summary>
/// <param name="iban">The IBAN.</param>
/// <returns>The codes, or <see langword="null"/> if the IBAN is foreign or invalid.</returns>
BankInfo? ReadIban(string? iban);
}
@@ -346,4 +346,10 @@ public sealed class ItalianBankDirectory : IBankDirectory
/// <inheritdoc />
public BankInfo? FindByIban(string? iban) =>
CodesOf(iban) is { } codes && _byAbi.TryGetValue(codes.Abi, out var bank) ? bank with { BranchCode = codes.Cab } : null;
/// <inheritdoc />
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);
}
@@ -20,6 +20,9 @@ public sealed class ItalyFiscalPack : FiscalPackBase
AddFeature<ITaxPaymentFormExporter>(new F24Exporter());
AddFeature<ITaxIdentifierRules>(new ItalianTaxIdentifierRules());
AddFeature<IBaseTablesTemplate>(new ItalianBaseTables());
// ABI and CAB are read from every Italian IBAN; bank names and BICs arrive with the ABI list (ADR 0026).
AddFeature<IBankDirectory>(new ItalianBankDirectory([]));
}
/// <inheritdoc />
@@ -99,7 +99,7 @@
<div class="kh-seg" role="radiogroup" aria-label="@T["Pages.Profile.Density"]">
@foreach (var density in Enum.GetValues<Density>())
{
<button type="button" role="radio" class="@(Draft.Density == density ? "on" : null)" aria-checked="@(Draft.Density == density)"
<button type="button" role="radio" class="@(Draft.Density == density ? "on" : null)" aria-checked="@(Draft.Density == density ? "true" : "false")"
@onclick="() => ChangeAsync(Draft with { Density = density })">@T["Pages.Profile.Density." + density]</button>
}
</div>
@@ -110,7 +110,7 @@
<div class="kh-seg" role="radiogroup" aria-label="@T["Pages.Profile.TextSize"]">
@foreach (var size in UserPreferences.TextSizes)
{
<button type="button" role="radio" class="@(Draft.TextSize == size ? "on" : null)" aria-checked="@(Draft.TextSize == size)"
<button type="button" role="radio" class="@(Draft.TextSize == size ? "on" : null)" aria-checked="@(Draft.TextSize == size ? "true" : "false")"
@onclick="() => ChangeAsync(Draft with { TextSize = size })">@T.Format("Pages.Profile.TextSize.Value", size)</button>
}
</div>
@@ -121,7 +121,7 @@
<div class="kh-seg" role="radiogroup" aria-label="@T["Pages.Profile.Menu"]">
@foreach (var (value, key) in MenuChoices)
{
<button type="button" role="radio" class="@(Draft.MenuCollapsed == value ? "on" : null)" aria-checked="@(Draft.MenuCollapsed == value)"
<button type="button" role="radio" class="@(Draft.MenuCollapsed == value ? "on" : null)" aria-checked="@(Draft.MenuCollapsed == value ? "true" : "false")"
@onclick="() => ChangeAsync(Draft with { MenuCollapsed = value })">@T[key]</button>
}
</div>
@@ -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. *@
<KhPageTitle Text="@T["CompanyPreferences.Title"]" Icon="settings" />
<TablesGuard>
<div class="phead">
<div>
<div class="crumbs"><a href="@TableScreens.BasePath">@T["Shell.Menu.CompanyTables"]</a> / @T["CompanyPreferences.Title"]</div>
<h1>@T["CompanyPreferences.Heading"]</h1>
<div class="sub">@T["CompanyPreferences.Hint"]</div>
</div>
<div class="grow"></div>
@if (_modified)
{
<KhBadge Tone="KhTone.Warning">@T["CompanyTables.Modified"]</KhBadge>
}
<div class="toolbar">
<button type="button" class="btn" disabled="@(!_modified)" @onclick="UndoAsync"><KhIcon Name="undo" /> @T["CompanyTables.Undo"]</button>
<button type="button" class="btn primary" disabled="@(!_modified || !CanWrite || _busy)" @onclick="SaveAsync"><KhIcon Name="save" /> @T["Common.Save"]</button>
</div>
</div>
@if (_loaded)
{
<section class="panel kh-tables-profile">
<KhTabs Items="TabItems" Active="@_tab" ActiveChanged="t => _tab = t" Label="@T["CompanyPreferences.Title"]" />
@if (_tab == "codes")
{
<KhForm Validation="_validation" ReadOnly="!CanWrite" Layout="KhFormLayout.Groups">
@foreach (var group in CodeRuleService.Definitions.GroupBy(d => d.Group))
{
<KhFieldGroup Title="@T["CompanyPreferences.Groups." + group.Key]" Icon="@GroupIcon(group.Key)">
@foreach (var definition in group)
{
var rule = _rules[definition.Key];
<KhTextBox Label="@T["CompanyPreferences.Rules." + definition.Key]" Name="@(definition.Key + "." + CodeRuleService.MaskField)" Mono="true"
Value="@rule.Mask" MaxLength="40" ReadOnly="!CanWrite" Hint="@HintOf(definition)"
ValueChanged="v => ChangeMaskAsync(definition.Key, v)" Span="6" />
}
<KhCheck Label="@T["CompanyPreferences.AllowManual"]" Name="@(group.Key + ".manual")" Value="group.All(d => _rules[d.Key].AllowManual)"
ValueChanged="v => SetManual(group.Key, v)" ReadOnly="!CanWrite" Span="12" />
@if (group.Key == "items")
{
<KhCheck Label="@T["CompanyPreferences.UniqueBarcode"]" Name="items.unique-barcode" Value="UniqueBarcode"
ValueChanged="SetUniqueBarcode" ReadOnly="!CanWrite" Span="12" />
}
</KhFieldGroup>
}
<KhFieldGroup Title="@T["CompanyPreferences.Groups.documents"]" Icon="file">
<p class="muted c12">@T["CompanyPreferences.Numerators"] <a href="/tabelle/numeratori">@T["CompanyPreferences.NumeratorsLink"]</a></p>
</KhFieldGroup>
</KhForm>
<p class="muted kh-pad"><KhIcon Name="info" /> @T["CompanyPreferences.Placeholders"]</p>
}
else
{
<div class="kh-pad kh-autofill">
@foreach (var option in AutoFillService.Options)
{
<KhSwitchRow Label="@T["CompanyPreferences.Options." + option.Key]" Hint="@T["CompanyPreferences.Options." + option.Key + ".Hint"]"
Value="_options.GetValueOrDefault(option.Key)" ValueChanged="v => SetOption(option.Key, v)" />
}
<p class="muted"><KhIcon Name="info" /> @T["CompanyPreferences.AutoFillHint"]</p>
</div>
}
</section>
}
</TablesGuard>
@code {
private readonly KhValidation _validation = new();
private Dictionary<string, CodeRule> _rules = new(StringComparer.Ordinal);
private Dictionary<string, CodeRule> _savedRules = new(StringComparer.Ordinal);
private Dictionary<string, bool> _options = new(StringComparer.Ordinal);
private Dictionary<string, bool> _savedOptions = new(StringComparer.Ordinal);
private readonly Dictionary<string, string?> _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<KhTabItem> 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),
];
/// <inheritdoc />
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<ItemCategory>(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<CodeRule> rules, IReadOnlyDictionary<string, bool> 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"]);
}
}
@@ -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"),
];
}
@@ -1,5 +1,5 @@
@* An on/off option with its label and a short explanation (mockup 008). The whole row is the switch. *@
<button type="button" class="kh-switch-row" role="switch" aria-checked="@Value" @onclick="() => ValueChanged.InvokeAsync(!Value)">
<button type="button" class="kh-switch-row" role="switch" aria-checked="@(Value ? "true" : "false")" @onclick="() => ValueChanged.InvokeAsync(!Value)">
<span class="grow">
<span class="t">@Label</span>
@if (!string.IsNullOrEmpty(Hint))
@@ -142,6 +142,8 @@ internal static class KhaemhatServices
services.AddSingleton<CompanyProfileService>();
services.AddSingleton<FiscalYearService>();
services.AddSingleton<PaymentTermService>();
services.AddSingleton<CodeRuleService>();
services.AddSingleton<AutoFillService>();
services.AddSingleton<ExchangeRateService>();
services.AddHttpClient<EcbRatesClient>(c => c.Timeout = TimeSpan.FromSeconds(30));
services.AddHttpClient<ViesClient>(c => c.Timeout = TimeSpan.FromSeconds(20));
@@ -0,0 +1,93 @@
{
"CompanyPreferences": {
"Title": "Preferenze azienda",
"Heading": "Preferenze azienda · codici automatici e compilazione",
"Hint": "Maschere dei codici automatici e campi che Khaemhat compila da solo.",
"Saved": "Preferenze salvate",
"Tabs": {
"codes": "Codici automatici",
"autofill": "Compilazione automatica"
},
"Groups": {
"parties": "Anagrafiche",
"items": "Articoli e cespiti",
"crm": "CRM e servizi",
"documents": "Documenti e contabilità"
},
"Rules": {
"customers": "Clienti",
"suppliers": "Fornitori",
"leads": "Contatti e lead",
"items": "Articoli",
"assets": "Cespiti",
"opportunities": "Opportunità",
"tickets": "Ticket",
"service-contracts": "Contratti di servizio",
"interventions": "Interventi"
},
"Next": "Prossimo codice: {0}",
"NextInvalid": "Maschera non valida",
"ModuleOff": "Modulo {0} non attivo: la maschera vale quando lo attivi.",
"AllowManual": "Consenti codice manuale",
"UniqueBarcode": "Blocca duplicati per EAN",
"Placeholders": "Segnaposto: {seq:0000} progressivo con le cifre indicate, {anno} anno, {categoria} codice della categoria (solo articoli). Il progressivo riparte ogni anno se la maschera contiene l'anno e va per categoria se contiene la categoria. Cambiare una maschera non riscrive i codici già assegnati.",
"Numerators": "Fatture, protocollo degli acquisti, registrazioni e gli altri documenti sono numerati dai numeratori, per anno e sezionale.",
"NumeratorsLink": "Apri i numeratori",
"AutoFillHint": "Le opzioni spente non compilano nulla: i campi restano da scrivere a mano.",
"Options": {
"postal-code": {
"_": "Comune, provincia e regione dal CAP",
"Hint": "Scrivendo il CAP propone il comune; scrivendo il comune propone CAP e provincia."
},
"tax-code": {
"_": "Codice fiscale dai dati anagrafici",
"Hint": "Calcola il codice fiscale delle persone fisiche da nome, cognome, data e comune di nascita."
},
"vies": {
"_": "Verifica P.IVA UE (VIES) al salvataggio",
"Hint": "Interroga il servizio VIES della Commissione europea e salva l'esito sulla controparte."
},
"bank-from-iban": {
"_": "Banca e BIC dall'IBAN",
"Hint": "Legge ABI e CAB dall'IBAN e propone banca e BIC già usati per la stessa banca."
},
"ecb-rates": {
"_": "Cambi BCE giornalieri",
"Hint": "Scarica ogni giorno lavorativo i cambi di riferimento della Banca centrale europea."
},
"item-description": {
"_": "Descrizione articolo nelle righe",
"Hint": "Copia la descrizione dell'articolo nella riga del documento."
},
"last-price": {
"_": "Ultimo prezzo praticato al cliente",
"Hint": "Mostra nella riga l'ultimo prezzo fatto al cliente per lo stesso articolo."
},
"last-document": {
"_": "Proponi ultimo documento simile",
"Hint": "Un nuovo documento parte dalle righe dell'ultimo dello stesso tipo e cliente."
},
"delivery-date": {
"_": "Data di consegna = data + lead time",
"Hint": "Calcola la consegna prevista dal tempo di approvvigionamento, spostandola al primo giorno lavorativo."
},
"accounts": {
"_": "Conti contabili da articolo, categoria e causale",
"Hint": "Propone i conti di ricavo e di costo nelle registrazioni dei documenti."
}
}
},
"codes": {
"mask": {
"sequence": "La maschera deve contenere una volta il progressivo, ad esempio {seq:0000}.",
"placeholder": "Segnaposto non riconosciuto: usa {seq:0000}, {anno} o {categoria}.",
"character": "Nella maschera sono ammessi lettere, cifre e i caratteri - _ / .",
"too-long": "I codici di questa maschera sono più lunghi di quanto ammette la tabella.",
"category": "Questa tabella non ha categorie: togli {categoria}."
},
"manual": "Il codice viene assegnato in automatico: lascia il campo vuoto.",
"category-required": "Il codice usa la categoria: scegli prima la categoria.",
"too-long": "Il codice è più lungo di quanto ammette la tabella.",
"exhausted": "Nessun codice libero trovato: controlla la maschera e i codici scritti a mano."
}
}
@@ -123,6 +123,7 @@
"_": "Tabelle azienda",
"Profile": "Profilo azienda",
"FiscalYears": "Esercizi e periodi",
"Preferences": "Preferenze e codici automatici",
"TaxCodes": "Codici IVA",
"Payments": "Pagamenti",
"Numerators": "Numeratori",
+1
View File
@@ -89,6 +89,7 @@ public static class MenuCatalog
[
Area("Shell.Menu.CompanyTables", "layers", "/tabelle", ModuleCodes.Core, "company.settings.read", null,
("Shell.Menu.CompanyTables.Profile", "profilo-azienda"), ("Shell.Menu.CompanyTables.FiscalYears", "esercizi"),
("Shell.Menu.CompanyTables.Preferences", "preferenze"),
("Shell.Menu.CompanyTables.TaxCodes", "codici-iva"), ("Shell.Menu.CompanyTables.Payments", "pagamenti"),
("Shell.Menu.CompanyTables.Numerators", "numeratori"), ("Shell.Menu.CompanyTables.Warehouses", "depositi"),
("Shell.Menu.CompanyTables.Currencies", "valute"), ("Shell.Menu.CompanyTables.ExchangeRates", "cambi")),
@@ -0,0 +1,69 @@
using Khaemhat.Core.Tables;
namespace Khaemhat.Core.Tests.Common;
/// <summary>The masks of the automatic codes (SPEC §11.12, issue #43).</summary>
[TestClass]
public sealed class CodeMaskTests
{
[TestMethod]
[DataRow("C{seq:000000}", 124L, null, "C000124")]
[DataRow("F{seq:000000}", 32L, null, "F000032")]
[DataRow("L{anno}-{seq:0000}", 1L, null, "L2026-0001")]
[DataRow("{categoria}-{seq:0000}", 13L, "valv", "VALV-0013")]
[DataRow("OPP-{year}-{seq:0000}", 7L, null, "OPP-2026-0007")]
[DataRow("cl/{seq}", 1234567L, null, "CL/1234567")]
[DataRow("A{seq:00}", 123L, null, "A123")]
public void Format_WritesTheCode(string text, long number, string? category, string expected)
{
Assert.AreEqual(expected, CodeMask.Parse(text).Format(number, 2026, category));
}
[TestMethod]
public void Parse_NormalizesTheMask_AndReadsWhatTheNumberDependsOn()
{
var mask = CodeMask.Parse(" l{ANNO}-{Seq:0000} ");
Assert.AreEqual("L{anno}-{seq:0000}", mask.Text);
Assert.AreEqual(4, mask.Digits);
Assert.IsTrue(mask.UsesYear);
Assert.IsFalse(mask.UsesCategory);
Assert.AreEqual(10, mask.FixedLength);
Assert.AreEqual("{categoria}-{seq:0000}", CodeMask.Parse("{category}-{seq:0000}").Text);
}
[TestMethod]
[DataRow("C000001", CodeMask.SequenceRequired)]
[DataRow("C{seq:0000}{seq:00}", CodeMask.SequenceRequired)]
[DataRow("C{seq:0a00}", CodeMask.UnknownPlaceholder)]
[DataRow("C{mese}{seq:0000}", CodeMask.UnknownPlaceholder)]
[DataRow("C{seq:0000", CodeMask.UnknownPlaceholder)]
[DataRow("C {seq:0000}", CodeMask.InvalidCharacter)]
[DataRow("È{seq:0000}", CodeMask.InvalidCharacter)]
[DataRow("", CodeMask.SequenceRequired)]
public void TryParse_RefusesWrongMasks(string text, string error)
{
Assert.IsFalse(CodeMask.TryParse(text, out var mask, out var found));
Assert.IsNull(mask);
Assert.AreEqual(error, found);
}
[TestMethod]
public void Check_LooksAtLengthAndCategories()
{
Assert.IsNull(CodeMask.Check("C{seq:000000}", 20, categoriesAllowed: false));
Assert.AreEqual(CodeMask.TooLong, CodeMask.Check("CLIENTE-{anno}-{seq:00000000}", 20, categoriesAllowed: false));
Assert.AreEqual(CodeMask.CategoryNotAllowed, CodeMask.Check("{categoria}{seq:0000}", 20, categoriesAllowed: false));
Assert.IsNull(CodeMask.Check("{categoria}-{seq:0000}", 30, categoriesAllowed: true));
Assert.AreEqual(CodeMask.UnknownPlaceholder, CodeMask.Check("{x}", 20, categoriesAllowed: true));
}
[TestMethod]
public void SequenceKey_SeparatesYearsAndCategories()
{
Assert.AreEqual("customers", CodeMask.Parse("C{seq:000000}").SequenceKey("customers", 2026, "IGNORED"));
Assert.AreEqual("leads:2026", CodeMask.Parse("L{anno}-{seq:0000}").SequenceKey("leads", 2026, null));
Assert.AreEqual("items:VALV", CodeMask.Parse("{categoria}-{seq:0000}").SequenceKey("items", 2026, " valv"));
Assert.AreEqual("items:2027:PUMP", CodeMask.Parse("{categoria}{anno}{seq:000}").SequenceKey("items", 2027, "pump"));
}
}
+1 -1
View File
@@ -75,7 +75,7 @@ public sealed class MappingTests
"company_profile", "fiscal_years", "fiscal_periods", "countries", "provinces", "municipalities", "currencies", "exchange_rates", "units_of_measure",
"tax_codes", "payment_methods", "payment_terms", "payment_term_lines", "bank_accounts", "salespeople", "carriers", "shipping_terms", "transport_means",
"goods_appearances", "delivery_terms", "transport_reasons", "inventory_reasons", "warehouses", "item_categories", "party_categories", "price_lists",
"discount_policies", "document_numerators", "document_types", "cost_centers", "jobs",
"discount_policies", "document_numerators", "document_types", "cost_centers", "jobs", "code_sequences",
];
CollectionAssert.AreEquivalent(expected, registry.Maps.Select(m => m.Table).ToArray());
}
@@ -137,4 +137,18 @@ public sealed class ItalianBankDirectoryTests
Assert.IsNull(directory.FindByIban("DE89 3704 0044 0532 0130 00"));
Assert.AreEqual(("05428", "11101"), ItalianBankDirectory.CodesOf("IT60X0542811101000000123456"));
}
[TestMethod]
public void ReadIban_GivesTheCodes_EvenForAnUnknownBank()
{
var directory = new ItalianBankDirectory([]);
var bank = directory.ReadIban("IT60X0542811101000000123456");
Assert.AreEqual(new BankInfo("05428", null, null, "11101"), bank);
Assert.IsNull(directory.FindByIban("IT60X0542811101000000123456"));
Assert.IsNull(directory.ReadIban("DE89370400440532013000"));
Assert.IsNull(directory.ReadIban("IT00X0542811101000000123456"));
Assert.IsNotNull(new ItalyFiscalPack().GetFeature<IBankDirectory>());
}
}
@@ -0,0 +1,171 @@
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Security;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Fiscal.Abstractions;
using Khaemhat.Web.Tests.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace Khaemhat.Web.Tests.Tables;
/// <summary>Automatic codes and automatic filling on a real instance (issue #43).</summary>
[TestClass]
public sealed class CodeRulesTests
{
private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
private static readonly DateOnly Day = new(2026, 11, 11);
[TestMethod]
public async Task Rules_StartFromTheSpecification_AndAreSavedInTheCompanySettings()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var codes = app.Services.GetRequiredService<CodeRuleService>();
var rules = await codes.RulesAsync(Root, company);
Assert.HasCount(CodeRuleService.Definitions.Count, rules);
Assert.AreEqual("C{seq:000000}", rules.Single(r => r.Key == "customers").Mask);
Assert.IsTrue(rules.Single(r => r.Key == "items").UniqueBarcode);
var refused = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() =>
codes.SaveAsync(Root, company, [new CodeRule("customers", "CLI", true), new CodeRule("suppliers", "{categoria}{seq:000}", true)]));
CollectionAssert.AreEquivalent(new[] { "customers.Mask:" + CodeMask.SequenceRequired, "suppliers.Mask:" + CodeMask.CategoryNotAllowed }, refused.Errors.ToArray());
var saved = await codes.SaveAsync(Root, company, [new CodeRule("customers", "cl{seq:0000}", AllowManual: false)]);
Assert.AreEqual(new CodeRule("customers", "CL{seq:0000}", false), saved.Single(r => r.Key == "customers"));
Assert.AreEqual("F{seq:000000}", saved.Single(r => r.Key == "suppliers").Mask, "Tables left out keep their rule.");
Assert.AreEqual(CodeRuleService.ManualNotAllowed, CodeRuleService.CheckManual(saved[0], "MIO"));
Assert.IsNull(CodeRuleService.CheckManual(saved[0], " "));
await app.StopAsync();
}
}
[TestMethod]
public async Task Assign_GivesNumbersInOrder_SkipsCodesTaken_AndKeepsYearsAndCategoriesApart()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var codes = app.Services.GetRequiredService<CodeRuleService>();
var factory = app.Services.GetRequiredService<IUnitOfWorkFactory>();
var customers = await codes.RuleAsync(company, "customers");
var items = await codes.RuleAsync(company, "items");
var leads = await codes.RuleAsync(company, "leads");
var taken = new HashSet<string>(StringComparer.Ordinal) { "C000002" };
async Task<string> AssignAsync(CodeRule rule, DateOnly date, string? category = null, bool commit = true)
{
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company));
await uow.BeginAsync();
var code = await CodeRuleService.AssignAsync(uow, rule, date, category, (c, _) => Task.FromResult(taken.Contains(c)));
if (commit)
{
await uow.CommitAsync();
}
return code;
}
Assert.AreEqual("C000001", await codes.PreviewAsync(Root, company, customers, Day, null));
Assert.AreEqual("C000001", await AssignAsync(customers, Day));
Assert.AreEqual("C000003", await AssignAsync(customers, Day), "C000002 was written by hand.");
Assert.AreEqual("C000004", await AssignAsync(customers, Day, commit: false));
Assert.AreEqual("C000004", await codes.PreviewAsync(Root, company, customers, Day, null), "A rolled back save gives its number back.");
Assert.AreEqual("VALV-0001", await AssignAsync(items, Day, "valv"));
Assert.AreEqual("PUMP-0001", await AssignAsync(items, Day, "PUMP"));
Assert.AreEqual("VALV-0002", await AssignAsync(items, Day, "VALV"));
var noCategory = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => AssignAsync(items, Day));
Assert.AreEqual("Code:" + CodeRuleService.CategoryRequired, noCategory.Errors.Single());
Assert.AreEqual("L2026-0001", await AssignAsync(leads, Day));
Assert.AreEqual("L2027-0001", await AssignAsync(leads, Day.AddYears(1)));
Assert.AreEqual("L2026-0002", await AssignAsync(leads, Day));
// A mask changed later continues the same sequence: codes already given are never rewritten.
Assert.AreEqual("CL0004", await AssignAsync(customers with { Mask = "CL{seq:0000}" }, Day));
await app.StopAsync();
}
}
[TestMethod]
public async Task Assign_NeverGivesTheSameCodeToTwoSavesAtTheSameTime()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var factory = app.Services.GetRequiredService<IUnitOfWorkFactory>();
var rule = await app.Services.GetRequiredService<CodeRuleService>().RuleAsync(company, "suppliers");
var assigned = await Task.WhenAll(Enumerable.Range(0, 8).Select(async _ =>
{
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company));
await uow.BeginAsync();
var code = await CodeRuleService.AssignAsync(uow, rule, Day, null, (_, _) => Task.FromResult(false));
await uow.CommitAsync();
return code;
}));
CollectionAssert.AreEquivalent(Enumerable.Range(1, 8).Select(n => "F" + n.ToString("D6", System.Globalization.CultureInfo.InvariantCulture)).ToArray(), assigned);
await app.StopAsync();
}
}
[TestMethod]
public async Task AutoFill_FindsPlacesBanksAndDates_AndRespectsTheOptions()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var services = app.Services;
var tables = services.GetRequiredService<TableService>();
var autoFill = services.GetRequiredService<AutoFillService>();
await tables.SaveAsync(Root, company, new Province { Code = "TO", Description = "Torino", Region = "Piemonte" });
await tables.SaveAsync(Root, company, new Municipality { Code = "L219", Description = "Torino", ProvinceCode = "TO", Region = "Piemonte", PostalCodes = "10121-10156" });
await tables.SaveAsync(Root, company, new Municipality { Code = "G674", Description = "Pinerolo", ProvinceCode = "TO", Region = "Piemonte", PostalCodes = "10064" });
var turin = (await autoFill.PlacesByPostalCodeAsync(Root, company, "10128")).Single();
Assert.AreEqual(new PlaceSuggestion("L219", "Torino", "TO", "Piemonte", "10128"), turin);
Assert.AreEqual("10064", (await autoFill.PlacesByNameAsync(Root, company, "pin")).Single().PostalCode);
Assert.IsEmpty(await autoFill.PlacesByPostalCodeAsync(Root, company, "1012"));
Assert.IsEmpty(await autoFill.PlacesByPostalCodeAsync(Root, company, "10157"));
var code = await autoFill.PersonalTaxCodeAsync(company, new PersonalTaxCodeData("Rossi", "Mario", new DateOnly(1980, 1, 1), PersonSex.Male, "L219"));
Assert.AreEqual("RSSMRA80A01L219", code![..15]);
// The bank is not in the directory yet: name and BIC come from an account of the company at the same bank.
var iban = "IT60X0542811101000000123456";
Assert.AreEqual(new BankInfo("05428", null, null, "11101"), await autoFill.BankFromIbanAsync(Root, company, iban));
await tables.SaveAsync(Root, company, new BankAccount { Code = "BPR", Description = "Conto ordinario", BankName = "Banca di prova", Bic = "BPROITMMXXX", Iban = "IT42L1234512345123456789012" });
await tables.SaveAsync(Root, company, new BankAccount { Code = "BP2", Description = "Altro conto", BankName = "Banca di prova", Bic = "BPROITMMXXX", Iban = "IT84S0542811101000000654321" });
Assert.AreEqual(new BankInfo("05428", "Banca di prova", "BPROITMMXXX", "11101"), await autoFill.BankFromIbanAsync(Root, company, iban));
Assert.IsNull(await autoFill.BankFromIbanAsync(Root, company, "DE89370400440532013000"));
// Friday 14 August 2026 + 1 day is Saturday 15th (also a holiday), then Sunday: the delivery moves to Monday 17th.
Assert.AreEqual(new DateOnly(2026, 8, 17), await autoFill.DeliveryDateAsync(company, new DateOnly(2026, 8, 14), 1));
Assert.IsTrue(await autoFill.IsOnAsync(company, AutoFillService.PostalCode));
Assert.IsFalse(await autoFill.IsOnAsync(company, AutoFillService.LastDocument));
var options = await autoFill.SaveOptionsAsync(Root, company, new Dictionary<string, bool> { [AutoFillService.PostalCode] = false, ["unknown"] = true });
Assert.IsFalse(options[AutoFillService.PostalCode]);
Assert.IsFalse(options.ContainsKey("unknown"));
Assert.IsFalse(await autoFill.IsOnAsync(company, AutoFillService.PostalCode));
await app.StopAsync();
}
}
[TestMethod]
[DataRow("10121-10156", "10128", true)]
[DataRow("10121-10156", "10157", false)]
[DataRow("10064", "10064", true)]
[DataRow("00118-00199, 00010", "00010", true)]
[DataRow(null, "00010", false)]
[DataRow("1012-1015", "10128", false)]
public void PostalCodeMatches_ReadsListsAndRanges(string? list, string code, bool expected)
{
Assert.AreEqual(expected, AutoFillService.PostalCodeMatches(list, code));
}
}
@@ -108,10 +108,11 @@ public sealed partial class TableScreensTests
[TestMethod]
public void EveryErrorCode_HasAText()
{
var codes = new[] { typeof(TableService), typeof(TableCatalog), typeof(CompanyProfileService), typeof(FiscalYearService), typeof(PaymentTermService), typeof(ExchangeRateService) }
var codes = new[] { typeof(TableService), typeof(TableCatalog), typeof(CompanyProfileService), typeof(FiscalYearService), typeof(PaymentTermService), typeof(ExchangeRateService), typeof(CodeRuleService), typeof(CodeMask) }
.SelectMany(t => t.GetFields(BindingFlags.Public | BindingFlags.Static).Where(f => f.IsLiteral && f.FieldType == typeof(string)))
.Select(f => (string)f.GetRawConstantValue()!)
.Where(c => c.StartsWith("tables.", StringComparison.Ordinal) || c.StartsWith("profile.", StringComparison.Ordinal) || c.StartsWith("fiscal.", StringComparison.Ordinal))
.Where(c => c.StartsWith("tables.", StringComparison.Ordinal) || c.StartsWith("profile.", StringComparison.Ordinal) || c.StartsWith("fiscal.", StringComparison.Ordinal)
|| c.StartsWith("codes.", StringComparison.Ordinal))
.Where(c => !c.EndsWith('.'))
.Concat(Enum.GetValues<PeriodState>().Select(FiscalYearService.ErrorOf))
.ToList();