diff --git a/CHANGELOG.md b/CHANGELOG.md index 89d0fc6..d2df3f8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,91 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`. ## [Unreleased] +## [0.4.0] - 2026-11-12 + +M4 — Tabelle, anagrafiche, articoli. Il pacchetto fiscale italiano, il profilo e le tabelle dell'azienda con i dati +di base (province, comuni e CAP compresi), clienti, fornitori e contatti, articoli e listini, i codici automatici, +l'import/export guidato e i dati di esempio: le prime maschere gestionali vere. + +### Added +- Pacchetto fiscale (ADR 0025): `IFiscalPack` con codici IVA, motore delle imposte e calendario fiscale, più funzioni + facoltative per paese; `FiscalPackCatalog` sceglie il pacchetto dal paese dell'azienda. Il pacchetto italiano + (`IT 2026.2`) porta nature IVA N1-N7, codici IVA di base, code list FatturaPA (specifiche **1.9.1**: TD, MP, TP, + RF, ritenute, casse previdenziali), castelletto IVA con arrotondamento sul totale per aliquota, regola del bollo, + scadenze IVA mensili e trimestrali con slittamenti di agosto e dei festivi, ritenute, regole di base dei cespiti e + codici tributo F24. +- Controlli degli identificativi: IBAN (mod 97 e lunghezza per paese), codici a barre EAN/GTIN, e-mail; partita IVA + italiana, codice fiscale con calcolo, lettura dei dati e omocodia, codice destinatario SDI per azienda, PA, privato + ed estero; `ViesClient` per la verifica delle partite IVA comunitarie (esito *valida*, *non valida* o *servizio + non disponibile*). +- Tabelle azienda (ADR 0026): 26 tabelle codificate (codici IVA, modalità e condizioni di pagamento con le rate, + banche, valute, tipi documento, numeratori, listini, sconti, agenti, depositi, causali di magazzino, unità di misura, + vettori, porto, trasporto, causali di trasporto, aspetto dei beni, rese, nazioni, province, comuni, categorie, + centri di costo, commesse) con un'unica maschera a `/tabelle/`: elenco con filtro attive/disattivate, + dettaglio con errori e avvisi, disattivazione al posto dell'eliminazione per le righe usate, export e import CSV + tutto o niente, storico e cache condivisa fra istanze. Indice delle tabelle a `/tabelle` e voci nel menu. +- Profilo azienda a schede (dati societari, fiscale e SDI, banche, stampa, esercizi, trasmittente e intermediario) + con i controlli del pacchetto fiscale; esercizi e mesi con blocco e sblocco; cambi BCE giornalieri (attività di + sistema) e cambi manuali. +- Dati di base aggiunti alla creazione dell'azienda e a ogni avvio, solo per i codici mancanti: paesi, valute, unità + di misura, codici IVA, pagamenti, tipi documento, numeratori, causali, trasporti, deposito, listino ed esercizio in + corso. Versione salvata nelle impostazioni dell'azienda (`IT 2026.3`). +- Province e comuni dall'elenco ISTAT dei codici dei comuni al 26/02/2026 (ADR 0028, CC BY 4.0): 110 province e + 7.894 comuni con codice catastale, provincia, regione e codice ISTAT, nei dati di base del pacchetto italiano + (`IT 2026.3`), con i CAP di GeoNames (CC BY 4.0) per 7.750 comuni; i mancanti si completano nella tabella + *Comuni*. `tools/Khaemhat.PlacesTool` rigenera i due elenchi dai file scaricati. +- `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`). +- Anagrafiche (ADR 0029): clienti, fornitori, prospect e lead in un solo archivio, con tre radar + (`/anagrafiche/clienti`, `/fornitori`, `/contatti`) con ricerca, filtri rapidi, disattivazione e riattivazione di + più righe, e la scheda a otto schede: dati principali, indirizzi, contatti, condizioni di vendita e di acquisto, + fiscale e SDI (fatturazione elettronica, regime IVA, ritenute e casse, dichiarazione d'intento), banche, note e + allegati, storico. Controlli del pacchetto fiscale su partita IVA, codice fiscale, codice destinatario e paese, con + avvisi che non bloccano (P.IVA doppia, privato senza codice fiscale); codice destinatario proposto per privati ed + esteri; verifica VIES al salvataggio e su richiesta; calcolo del codice fiscale; CAP e comune compilati a vicenda. + *Converti in cliente* per prospect e lead (nuovo codice, il vecchio resta come codice precedente) e per i fornitori + (diventano anche clienti con lo stesso codice). Un'anagrafica usata da altri dati si disattiva invece di cancellarsi. +- Dati di esempio delle anagrafiche con `KHAEMHAT_SEED_DEMO=true`: 3 agenti, 12 clienti di ogni tipo soggetto, + 5 fornitori, 2 prospect e 2 lead, con numeri inventati ma formalmente validi. +- Articoli (ADR 0030): radar `/anagrafiche/articoli` con ricerca anche per codice a barre, filtri per tipo, + categoria, magazzino e stato, disattivazione e riattivazione; scheda con dati principali, UM alternative, codici + alternativi, listini e prezzi netti dei clienti, fornitori con il fornitore abituale, sostitutivi, note e allegati, + storico. Codice dalla maschera per categoria, verifica EAN con duplicati bloccati o segnalati secondo le + preferenze, NC8, solo le merci a magazzino; costi visibili solo con `items.cost.read` e conservati per chi non li + vede; un articolo usato si disattiva invece di cancellarsi. +- Listini (ADR 0030): prezzi con data di validità e storico, listino base, listini derivati con ricarico e + arrotondamento, griglia `/anagrafiche/listini` articoli x listini con modifica in cella, prezzi netti di un + cliente, margine e aggiornamento massivo con anteprima; ricerca del prezzo per i documenti (netto, listino del + documento o del cliente, base, articolo) con la fonte e gli sconti del cliente a cascata. +- Scheda *Articoli e codici* delle anagrafiche: i codici con cui un cliente o un fornitore chiama i tuoi articoli, + trovati dalla ricerca nei suoi documenti. +- 120 articoli di esempio con listini *Pubblico* e *Rivenditori*, prezzi dell'anno precedente, fornitori, UM e + codici alternativi, sostitutivi e prezzi netti di un cliente; `scripts/seed.sh --demo [--scale N]` carica i dati + di esempio da riga di comando e moltiplica il catalogo per le prove di prestazione. +- Import/export guidato (ADR 0031) in *Amministrazione → Import / export dati*: CSV (separatore e codifica dedotti), + XLSX (lettore interno, primo foglio) e JSON per clienti, fornitori, articoli e prezzi di listino e netti cliente; + mappatura automatica delle colonne con alias, validazione riga per riga con le regole della scheda, esiti *nuovo*, + *aggiorna*, *avviso*, *errore*, opzioni per codici esistenti o mancanti, VIES e comune da CAP, report errori CSV, + esito nel log. Export con le stesse colonne dell'import e modelli vuoti. Giacenze iniziali e piano dei conti (tracciato + `codice;descrizione;livello;padre;natura;tipo;voce_cee;riclassifica;flag` e `khaemhat-coa.json`) si verificano + già, la scrittura arriva con M6 e M7. + +### Changed +- Tabella *Listini*: nuovi campi *Listino base* (uno solo) e *Derivato da*; la migrazione marca come base il listino + `BASE` esistente. +- Il componente dei passi verticali mette il dettaglio di ogni passo su una riga propria. + +### Known issues +- L'azienda demo creata da `KHAEMHAT_SEED_DEMO` ha il profilo vuoto (indirizzo, partita IVA): va compilato prima dei + documenti (M5). +- Mancano le banche ABI/CAB nei dati di base: non c'è ancora una fonte con licenza compatibile (#45). + ## [0.3.0] - 2026-11-11 M3 — Framework UI. La shell dell'applicazione, la libreria di componenti `Kh*` con griglie, radar e pagine record, la diff --git a/CLAUDE.md b/CLAUDE.md index ded8367..617c526 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -88,6 +88,11 @@ fermandosi solo per blocchi reali (SDK mancante, credenziali, PNG o dati che sol inglese che dicono *cosa cambia e perché*. Il push su Gitea e le pull request seguono le indicazioni dell'utente; il tag `vX.Y.Z` si crea alla chiusura di ogni milestone (§20). +**E7 — Versioni 0.x fino al via dell'utente** (sostituisce la colonna versione di §20 per M13 e M14; deciso +dall'utente il 2026-11-12). Finché il prodotto è in sviluppo le versioni restano **0.x**: ogni milestone chiude con +`v0..0` (M13 `v0.13.0`, M14 `v0.14.0` e seguenti). La **1.0.0 non si crea** (tag, immagine, release, CHANGELOG) +finché l'utente non lo dice esplicitamente. L'icona versionata `icon-v1.0` resta il modello grafico. + ## 4. Vincoli non negoziabili (sintesi di SPEC §1 — leggere l'originale) 1. C# 14 su .NET 10; JavaScript solo come interop minimo in `wwwroot/js`, senza framework né bundler. diff --git a/Khaemhat.sln b/Khaemhat.sln index d1ee8aa..fa14e80 100644 --- a/Khaemhat.sln +++ b/Khaemhat.sln @@ -43,6 +43,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.LicenseTool", "too EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.DataModelTool", "tools\Khaemhat.DataModelTool\Khaemhat.DataModelTool.csproj", "{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.PlacesTool", "tools\Khaemhat.PlacesTool\Khaemhat.PlacesTool.csproj", "{04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -257,6 +259,18 @@ Global {7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Release|x64.Build.0 = Release|Any CPU {7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Release|x86.ActiveCfg = Release|Any CPU {7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Release|x86.Build.0 = Release|Any CPU + {04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Debug|x64.ActiveCfg = Debug|Any CPU + {04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Debug|x64.Build.0 = Debug|Any CPU + {04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Debug|x86.ActiveCfg = Debug|Any CPU + {04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Debug|x86.Build.0 = Debug|Any CPU + {04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Release|Any CPU.Build.0 = Release|Any CPU + {04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Release|x64.ActiveCfg = Release|Any CPU + {04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Release|x64.Build.0 = Release|Any CPU + {04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Release|x86.ActiveCfg = Release|Any CPU + {04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -279,5 +293,6 @@ Global {FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A} = {0AB3BF05-4346-4AA6-1389-037BE0695223} {4317FFD0-9473-43FD-8543-F80EF9BA812A} = {07C2787E-EAC7-C090-1BA3-A61EC2A24D84} {7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F} = {07C2787E-EAC7-C090-1BA3-A61EC2A24D84} + {04C6CC82-F19E-437A-BDFE-7A6F66E29D2E} = {07C2787E-EAC7-C090-1BA3-A61EC2A24D84} EndGlobalSection EndGlobal diff --git a/docker/Dockerfile b/docker/Dockerfile index 709c53e..6458206 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -65,8 +65,8 @@ ENV ASPNETCORE_ENVIRONMENT=Production \ WORKDIR /app COPY --from=build /app ./ COPY docker/entrypoint.sh /app/entrypoint.sh -COPY scripts/restore-system.sh /app/scripts/restore-system.sh -RUN chmod 0755 /app/entrypoint.sh /app/scripts/restore-system.sh \ +COPY scripts/restore-system.sh scripts/seed.sh /app/scripts/ +RUN chmod 0755 /app/entrypoint.sh /app/scripts/restore-system.sh /app/scripts/seed.sh \ && install -d -o app -g app -m 0750 /data LABEL org.opencontainers.image.title="Khaemhat" \ diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 07a371a..3d17892 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -75,6 +75,7 @@ client degli aggiornamenti è `GiteaPackagesClient`. | `Khaemhat.Web` | host ASP.NET Core 10, Blazor Interactive Server, Minimal API, MCP, autenticazione | M0 → M13 | | `tools/Khaemhat.LicenseTool` | CLI per chiavi ed emissione licenze (chiave privata mai nel repository; non distribuito) | M2 | | `tools/Khaemhat.DataModelTool` | rigenera la sezione generata di `docs/DATA-MODEL.md` dalle migrazioni (non distribuito, ADR 0018) | M1 | +| `tools/Khaemhat.PlacesTool` | rigenera province e comuni del pacchetto italiano dall'elenco ISTAT e dai CAP GeoNames (non distribuito, ADR 0028) | M4 | | `tests/*` | `Core`, `Data`, `Infrastructure`, `Fiscal.Italy`, `Application`, `Web` (MSTest) | ogni milestone | ## 3. Regole di dipendenza @@ -380,7 +381,7 @@ Khaemhat/ │ └── Khaemhat.Web/ Program.cs Configuration/ Auth/ Api/ Mcp/ Help/ Components/ │ (App, Routes, Layout/, Ui/, Pages//, Shared/) Localization/ wwwroot/ ├── tests/ Core, Data, Infrastructure, Fiscal.Italy, Application, Web -├── tools/Khaemhat.LicenseTool/ +├── tools/ Khaemhat.LicenseTool, Khaemhat.DataModelTool, Khaemhat.PlacesTool └── docs/ ├── SPEC.md ARCHITECTURE.md DATA-MODEL.md MODULES.md API.md MCP.md ├── DEPLOY.md DEVELOPMENT.md SECURITY.md STATUS.md diff --git a/docs/DATA-MODEL.md b/docs/DATA-MODEL.md index eaf4f5d..471e9b0 100644 --- a/docs/DATA-MODEL.md +++ b/docs/DATA-MODEL.md @@ -168,7 +168,7 @@ public sealed class M20261013_001_CreateParties : IMigration | `warehouses` | codice, descrizione, indirizzo | | | `item_categories` | codice, descrizione, `parent_id` → (3 livelli) | | | `party_categories` | codice, descrizione | | -| `price_lists` | codice, descrizione, valuta, IVA inclusa, listino padre → | listini derivati | +| `price_lists` | codice, descrizione, valuta, IVA inclusa, `is_base` (listino base), listino di partenza →, ricarico %, passo di arrotondamento, validità | listini derivati (ADR 0030) | | `discount_policies` | codice, descrizione, formula sconto | | | `document_types` | kind, numeratore →, causale magazzino →, causale contabile →, registro IVA →, TD SDI, modello stampa | catalogo statico | | `cost_centers`, `jobs` | codice, descrizione | centri di costo, commesse | @@ -177,26 +177,26 @@ public sealed class M20261013_001_CreateParties : IMigration | Tabella | Colonne principali | Relazioni / note | |---|---|---| -| `parties` | `code` (automatico), `kind` (cliente/fornitore/prospect/lead), ragione sociale o nome/cognome, P.IVA, codice fiscale, `party_type` (*azienda/privato/PA/UE/extra-UE/forfettario*), sede, contatti, lingua, `country_id` →, `category_id` →, `salesperson_id` →, note, `disabled`, `is_demo`, conti cliente/fornitore → | disabilitazione al posto della cancellazione se esistono documenti | -| `party_addresses` | `party_id` →, tipo (destinazione), indirizzo | | -| `party_contacts` | `party_id` →, nome, ruolo, telefono, e-mail | | -| `party_bank_accounts` | `party_id` →, IBAN, BIC, banca | | -| `party_sales_terms` | `party_id` →, listino →, sconti, pagamento →, banca RiBa, agente →, vettore →, porto, deposito →, fido, blocco, raggruppa DDT, giorno fatturazione, invio documenti e-mail/PEC | | -| `party_purchase_terms` | `party_id` →, pagamento →, lead time, minimo, sconti | | -| `party_fiscal` | `party_id` →, codice destinatario, PEC, split payment, reverse charge, ritenuta e aliquota, causale, cassa previdenza, ENASARCO, EORI, GLN, forfettario, esito VIES | | +| `parties` | `code` (automatico per tipo, ADR 0027), `previous_code` (codice da lead o prospect), `kind` (cliente/fornitore/prospect/lead), `is_also_supplier`, `subject_type` (*impresa/privato/PA/UE/extra-UE/forfettario*), ragione sociale o cognome e nome, P.IVA, codice fiscale, REA, sede, `country_code`, recapiti, lingua, valuta, `category_id` →, `salesperson_id` →, consensi, note, esito e data VIES, conti cliente/fornitore, `disabled`, `is_demo` | disattivazione al posto della cancellazione se altri dati la usano (ADR 0029) | +| `party_addresses` | `party_id` → (cascata), tipo (destinazione, fatturazione, cantiere, altro), denominazione, indirizzo, predefinito | | +| `party_contacts` | `party_id` → (cascata), nome, ruolo, telefono, cellulare, e-mail, principale | | +| `party_bank_accounts` | `party_id` → (cascata), IBAN, BIC, banca, ABI, CAB, predefinito | | +| `party_sales_terms` | `party_id` → (unico), listino →, sconti, pagamento →, nostra banca →, vettore →, porto →, deposito →, fido, blocco, raggruppa DDT, giorno fatturazione, invio documenti e-mail/PEC | i dati di vendita del cliente | +| `party_purchase_terms` | `party_id` → (unico), pagamento →, lead time, minimo d'ordine, sconto, porto →, registro IVA, conto di costo, e-mail ordini | i dati di acquisto del fornitore | +| `party_fiscal` | `party_id` → (unico), codice destinatario, PEC, riferimento amministrazione, split payment, reverse charge, codice IVA →, esigibilità, bollo, ritenuta e aliquota, causale, cassa previdenza, ENASARCO, dichiarazione d'intento (numero, data, protocollo, codice IVA →, plafond, utilizzato, validità), EORI, GLN | | | `intent_declarations` † | `party_id` →, direzione (ricevuta/emessa), protocollo, anno, plafond, utilizzato, residuo, validità | mockup 061 | -| `party_item_codes` | `party_id` →, `item_id` →, codice e descrizione del cliente/fornitore | | +| `party_item_codes` | `party_id` → (cascata), `item_id` → (cascata), codice e descrizione del cliente/fornitore | salvati con la scheda dell'anagrafica; codice unico per anagrafica (ADR 0030) | ### 4.4 Articoli e listini (`Items`, CORE) | Tabella | Colonne principali | Relazioni / note | |---|---|---| -| `items` | `code` (automatico), descrizioni, `item_type` (*merce/servizio/spesa/testo/cespite*), `category_id` →, UM →, IVA vendita/acquisto →, EAN, NC8, produttore, marca, pesi, deposito →, scorta minima, punto/lotto di riordino, costi (standard/ultimo/medio), gestione a magazzino, conti ricavo/costo → | immagine come allegato | -| `item_uoms` | `item_id` →, UM →, fattore di conversione | | -| `item_barcodes` | `item_id` →, codice, tipo | | -| `item_prices` | `item_id` →, `price_list_id` →, prezzo, validità, `party_id` → (prezzo netto cliente) | griglia listino x articolo (mockup 018) | -| `item_suppliers` | `item_id` →, `party_id` →, codice fornitore, prezzo, lead time, minimo | | -| `item_substitutes` | `item_id` →, `substitute_item_id` → | | +| `items` | `code` (automatico, maschera `{categoria}-{seq:0000}`), descrizioni, `kind` (*merce/servizio/spesa/testo/cespite*), `category_id` →, UM →, IVA vendita/acquisto →, EAN, NC8, produttore, marca, pesi, deposito →, scorta minima, punto/lotto di riordino, prezzo, costi (standard/ultimo/medio), gestione a magazzino (solo merci), conti ricavo/costo →, `disabled`, `is_demo` | immagine come allegato; disattivazione al posto della cancellazione se usato | +| `item_uoms` | `item_id` → (cascata), UM →, fattore di conversione, EAN della confezione | | +| `item_barcodes` | `item_id` → (cascata), codice, descrizione | codici alternativi, trovati dalla ricerca | +| `item_prices` | `item_id` → (cascata), `price_list_id` → oppure `party_id` → (prezzo netto cliente), prezzo, `valid_from` | storico per data di validità; griglia listino x articolo (mockup 018, ADR 0030) | +| `item_suppliers` | `item_id` → (cascata), `party_id` →, codice fornitore, prezzo, lead time, minimo, `is_default` (fornitore abituale) | | +| `item_substitutes` | `item_id` → (cascata), `substitute_id` →, note | | ### 4.5 Documenti, vendite e acquisti (`Sales`, `Purchases`, CORE) @@ -721,6 +721,14 @@ Migrazioni applicate in ordine: - `core` 20261111007 `create_attachments` (M20261111_007_CreateAttachments) - `core` 20261111008 `create_company_settings` (M20261111_008_CreateCompanySettings) - `core` 20261111009 `create_notification_reads` (M20261111_009_CreateNotificationReads) +- `core` 20261111010 `create_company_profile` (M20261111_010_CreateCompanyProfile) +- `core` 20261111011 `create_geography_and_currencies` (M20261111_011_CreateGeographyAndCurrencies) +- `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) +- `core` 20261112001 `create_parties` (M20261112_001_CreateParties) +- `core` 20261112002 `create_items` (M20261112_002_CreateItems) #### `attachments` @@ -767,6 +775,113 @@ Migrazioni applicate in ordine: - indice `ix_audit_log_at` su `at` - indice `ix_audit_log_entity_entity_id` su `entity`, `entity_id` +#### `bank_accounts` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(10) | no | | | +| `description` | String(100) | no | | | +| `disabled` | Bool | no | `false` | | +| `bank_name` | String(100) | sì | | | +| `iban` | String(34) | sì | | | +| `bic` | String(11) | sì | | | +| `sia_code` | String(5) | sì | | | +| `cuc_code` | String(8) | sì | | | +| `account_code` | String(20) | sì | | | +| `is_default` | Bool | no | `false` | | +| `is_demo` | Bool | no | `false` | | +| `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_bank_accounts_code` su `code` + +#### `carriers` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(10) | no | | | +| `description` | String(100) | no | | | +| `disabled` | Bool | no | `false` | | +| `vat_number` | String(28) | sì | | | +| `address` | String(200) | sì | | | +| `city` | String(100) | sì | | | +| `phone` | String(30) | sì | | | +| `email` | String(254) | sì | | | +| `register_number` | String(30) | sì | | | +| `is_demo` | Bool | no | `false` | | +| `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_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 | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `legal_name` | String(200) | no | | | +| `fiscal_name` | String(200) | sì | | | +| `vat_number` | String(28) | sì | | | +| `tax_code` | String(16) | sì | | | +| `rea_office` | String(2) | sì | | | +| `rea_number` | String(20) | sì | | | +| `share_capital` | Decimal(19,6) | sì | | | +| `shareholders` | String(2) | sì | | | +| `liquidation_status` | String(2) | sì | | | +| `address` | String(200) | sì | | | +| `street_number` | String(8) | sì | | | +| `postal_code` | String(10) | sì | | | +| `city` | String(100) | sì | | | +| `province_code` | String(2) | sì | | | +| `address_country` | String(2) | sì | | | +| `phone` | String(30) | sì | | | +| `email` | String(254) | sì | | | +| `pec` | String(254) | sì | | | +| `website` | String(200) | sì | | | +| `tax_regime` | String(4) | no | | | +| `recipient_code` | String(7) | sì | | | +| `logo_attachment_id` | Int64 | sì | | | +| `default_bank_account_id` | Int64 | sì | | | +| `currency_code` | String(3) | no | | | +| `country` | String(2) | no | | | +| `vat_periodicity` | String(40) | no | | | +| `pro_rata_percent` | Decimal(19,6) | no | | | +| `cash_vat` | Bool | no | `false` | | +| `fiscal_year_start_month` | Int32 | no | | | +| `transmitter_country` | String(2) | sì | | | +| `transmitter_id` | String(28) | sì | | | +| `intermediary_name` | String(200) | sì | | | +| `intermediary_tax_code` | String(16) | sì | | | +| `footer_notes` | Text | sì | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + #### `company_settings` | Colonna | Tipo | Null | Default | Note | @@ -782,6 +897,437 @@ Migrazioni applicate in ordine: - indice unico `ux_company_settings_key` su `key` +#### `cost_centers` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(20) | no | | | +| `description` | String(100) | no | | | +| `disabled` | Bool | no | `false` | | +| `parent_id` | Int64 | sì | | -> `cost_centers` (Restrict) | +| `is_demo` | Bool | no | `false` | | +| `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_cost_centers_code` su `code` + +#### `countries` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(2) | no | | | +| `description` | String(100) | no | | | +| `disabled` | Bool | no | `false` | | +| `iso3` | String(3) | sì | | | +| `eu_member` | Bool | no | `false` | | +| `vat_prefix` | String(2) | sì | | | +| `currency_code` | String(3) | sì | | | +| `is_demo` | Bool | no | `false` | | +| `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_countries_code` su `code` + +#### `currencies` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(3) | no | | | +| `description` | String(100) | no | | | +| `disabled` | Bool | no | `false` | | +| `symbol` | String(5) | sì | | | +| `decimals` | Int32 | no | | | +| `is_demo` | Bool | no | `false` | | +| `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_currencies_code` su `code` + +#### `delivery_terms` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(10) | no | | | +| `description` | String(100) | no | | | +| `disabled` | Bool | no | `false` | | +| `is_demo` | Bool | no | `false` | | +| `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_delivery_terms_code` su `code` + +#### `discount_policies` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(10) | no | | | +| `description` | String(100) | no | | | +| `disabled` | Bool | no | `false` | | +| `formula` | String(60) | no | | | +| `is_demo` | Bool | no | `false` | | +| `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_discount_policies_code` su `code` + +#### `document_numerators` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(10) | no | | | +| `description` | String(100) | no | | | +| `disabled` | Bool | no | `false` | | +| `kind` | String(40) | no | | | +| `section` | String(10) | sì | | | +| `year` | Int32 | no | | | +| `prefix` | String(10) | sì | | | +| `format` | String(60) | no | | | +| `last_number` | Int64 | no | | | +| `gaps_allowed` | Bool | no | `false` | | +| `is_demo` | Bool | no | `false` | | +| `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_document_numerators_code_year` su `code`, `year` + +#### `document_types` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(10) | no | | | +| `description` | String(100) | no | | | +| `disabled` | Bool | no | `false` | | +| `kind` | String(40) | no | | | +| `numerator_id` | Int64 | sì | | | +| `inventory_reason_id` | Int64 | sì | | -> `inventory_reasons` (Restrict) | +| `e_invoice_type` | String(4) | sì | | | +| `journal_template_code` | String(10) | sì | | | +| `vat_register_code` | String(10) | sì | | | +| `print_template` | String(60) | sì | | | +| `is_demo` | Bool | no | `false` | | +| `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_document_types_code` su `code` + +#### `exchange_rates` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `currency_code` | String(3) | no | | | +| `rate_date` | Date | no | | | +| `rate` | Decimal(19,6) | no | | | +| `source` | String(10) | 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_exchange_rates_currency_code_rate_date` su `currency_code`, `rate_date` + +#### `fiscal_periods` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `fiscal_year_id` | Int64 | no | | -> `fiscal_years` (Cascade) | +| `number` | Int32 | no | | | +| `start_date` | Date | no | | | +| `end_date` | Date | no | | | +| `status` | String(40) | 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 `ix_fiscal_periods_start_date` su `start_date` +- indice unico `ux_fiscal_periods_fiscal_year_id_number` su `fiscal_year_id`, `number` + +#### `fiscal_years` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(10) | no | | | +| `start_date` | Date | no | | | +| `end_date` | Date | no | | | +| `status` | String(40) | no | | | +| `journal_first_page` | Int32 | no | | | +| `last_final_entry_number` | Int64 | no | | | +| `last_final_entry_date` | Date | sì | | | +| `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_fiscal_years_code` su `code` +- indice unico `ux_fiscal_years_start_date` su `start_date` + +#### `goods_appearances` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(10) | no | | | +| `description` | String(100) | no | | | +| `disabled` | Bool | no | `false` | | +| `is_demo` | Bool | no | `false` | | +| `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_goods_appearances_code` su `code` + +#### `inventory_reasons` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(10) | no | | | +| `description` | String(100) | no | | | +| `disabled` | Bool | no | `false` | | +| `effect` | String(40) | no | | | +| `affects_value` | Bool | no | `false` | | +| `is_transfer` | Bool | no | `false` | | +| `is_demo` | Bool | no | `false` | | +| `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_inventory_reasons_code` su `code` + +#### `item_barcodes` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `item_id` | Int64 | no | | -> `items` (Cascade) | +| `code` | String(40) | no | | | +| `description` | String(100) | sì | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_item_barcodes_code` su `code` + +#### `item_categories` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(20) | no | | | +| `description` | String(100) | no | | | +| `disabled` | Bool | no | `false` | | +| `parent_id` | Int64 | sì | | -> `item_categories` (Restrict) | +| `level` | Int32 | no | | | +| `is_demo` | Bool | no | `false` | | +| `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_item_categories_code` su `code` + +#### `item_prices` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `item_id` | Int64 | no | | -> `items` (Cascade) | +| `price_list_id` | Int64 | sì | | -> `price_lists` (Restrict) | +| `party_id` | Int64 | sì | | -> `parties` (Restrict) | +| `price` | Decimal(19,6) | no | | | +| `valid_from` | Date | sì | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_item_prices_item` su `item_id` +- indice `ix_item_prices_party` su `party_id` +- indice `ix_item_prices_price_list` su `price_list_id` + +#### `item_substitutes` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `item_id` | Int64 | no | | -> `items` (Cascade) | +| `substitute_id` | Int64 | no | | -> `items` (Restrict) | +| `notes` | String(200) | sì | | | +| `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_item_substitutes_pair` su `item_id`, `substitute_id` + +#### `item_suppliers` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `item_id` | Int64 | no | | -> `items` (Cascade) | +| `party_id` | Int64 | no | | -> `parties` (Restrict) | +| `supplier_code` | String(40) | sì | | | +| `price` | Decimal(19,6) | sì | | | +| `lead_time_days` | Int32 | sì | | | +| `minimum_quantity` | Decimal(19,6) | sì | | | +| `is_default` | Bool | no | `false` | | +| `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_item_suppliers_item_party` su `item_id`, `party_id` + +#### `item_uoms` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `item_id` | Int64 | no | | -> `items` (Cascade) | +| `unit_of_measure_id` | Int64 | no | | -> `units_of_measure` (Restrict) | +| `factor` | Decimal(19,6) | no | `1` | | +| `barcode` | String(20) | sì | | | +| `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_item_uoms_item_unit` su `item_id`, `unit_of_measure_id` + +#### `items` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(30) | no | | | +| `kind` | String(40) | no | | | +| `description` | String(200) | no | | | +| `extended_description` | Text | sì | | | +| `category_id` | Int64 | sì | | -> `item_categories` (Restrict) | +| `unit_of_measure_id` | Int64 | sì | | -> `units_of_measure` (Restrict) | +| `sales_tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) | +| `purchase_tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) | +| `barcode` | String(20) | sì | | | +| `customs_code` | String(10) | sì | | | +| `manufacturer` | String(100) | sì | | | +| `brand` | String(100) | sì | | | +| `net_weight` | Decimal(19,6) | sì | | | +| `gross_weight` | Decimal(19,6) | sì | | | +| `stocked` | Bool | no | `false` | | +| `warehouse_id` | Int64 | sì | | -> `warehouses` (Restrict) | +| `minimum_stock` | Decimal(19,6) | sì | | | +| `reorder_point` | Decimal(19,6) | sì | | | +| `reorder_lot` | Decimal(19,6) | sì | | | +| `price` | Decimal(19,6) | sì | | | +| `standard_cost` | Decimal(19,6) | sì | | | +| `last_cost` | Decimal(19,6) | sì | | | +| `average_cost` | Decimal(19,6) | sì | | | +| `revenue_account_code` | String(20) | sì | | | +| `cost_account_code` | String(20) | sì | | | +| `notes` | Text | sì | | | +| `disabled` | Bool | no | `false` | | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_items_barcode` su `barcode` +- indice `ix_items_category` su `category_id` +- indice `ix_items_description` su `description` +- indice unico `ux_items_code` su `code` + +#### `jobs` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(20) | no | | | +| `description` | String(100) | no | | | +| `disabled` | Bool | no | `false` | | +| `party_id` | Int64 | sì | | | +| `start_date` | Date | sì | | | +| `end_date` | Date | sì | | | +| `status` | String(40) | no | | | +| `is_demo` | Bool | no | `false` | | +| `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_jobs_code` su `code` + +#### `municipalities` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(4) | no | | | +| `description` | String(100) | no | | | +| `disabled` | Bool | no | `false` | | +| `province_code` | String(2) | no | | | +| `region` | String(60) | sì | | | +| `istat_code` | String(6) | sì | | | +| `postal_codes` | String(400) | sì | | | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_municipalities_description` su `description` +- indice `ix_municipalities_province_code` su `province_code` +- indice unico `ux_municipalities_code` su `code` + #### `notification_reads` | Colonna | Tipo | Null | Default | Note | @@ -818,6 +1364,352 @@ Migrazioni applicate in ordine: - indice `ix_notifications_recipient_user_id` su `recipient_user_id` +#### `parties` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(30) | no | | | +| `previous_code` | String(30) | sì | | | +| `kind` | String(40) | no | | | +| `is_also_supplier` | Bool | no | `false` | | +| `subject_type` | String(40) | no | | | +| `name` | String(200) | no | | | +| `first_name` | String(80) | sì | | | +| `last_name` | String(80) | sì | | | +| `fiscal_name` | String(200) | sì | | | +| `vat_number` | String(30) | sì | | | +| `tax_code` | String(30) | sì | | | +| `rea` | String(20) | sì | | | +| `category_id` | Int64 | sì | | -> `party_categories` (Restrict) | +| `address` | String(200) | sì | | | +| `street_number` | String(20) | sì | | | +| `postal_code` | String(10) | sì | | | +| `city` | String(100) | sì | | | +| `province` | String(10) | sì | | | +| `country_code` | String(2) | no | | | +| `phone` | String(40) | sì | | | +| `email` | String(200) | sì | | | +| `pec` | String(200) | sì | | | +| `website` | String(200) | sì | | | +| `salesperson_id` | Int64 | sì | | -> `salespeople` (Restrict) | +| `language` | String(5) | no | | | +| `currency_code` | String(3) | no | | | +| `since` | Date | sì | | | +| `privacy_accepted` | Bool | no | `false` | | +| `marketing` | Bool | no | `false` | | +| `notes` | Text | sì | | | +| `vat_check` | String(40) | no | | | +| `vat_checked_at` | DateTimeUtc | sì | | | +| `customer_account_code` | String(20) | sì | | | +| `supplier_account_code` | String(20) | sì | | | +| `disabled` | Bool | no | `false` | | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_parties_kind` su `kind` +- indice `ix_parties_name` su `name` +- indice `ix_parties_tax_code` su `tax_code` +- indice `ix_parties_vat_number` su `vat_number` +- indice unico `ux_parties_code` su `code` + +#### `party_addresses` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `party_id` | Int64 | no | | -> `parties` (Cascade) | +| `kind` | String(40) | no | | | +| `name` | String(200) | no | | | +| `address` | String(200) | sì | | | +| `street_number` | String(20) | sì | | | +| `postal_code` | String(10) | sì | | | +| `city` | String(100) | sì | | | +| `province` | String(10) | sì | | | +| `country_code` | String(2) | no | | | +| `is_default` | Bool | no | `false` | | +| `notes` | Text | sì | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_party_addresses_party` su `party_id` + +#### `party_bank_accounts` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `party_id` | Int64 | no | | -> `parties` (Cascade) | +| `iban` | String(34) | no | | | +| `bic` | String(11) | sì | | | +| `bank_name` | String(100) | sì | | | +| `bank_code` | String(10) | sì | | | +| `branch_code` | String(10) | sì | | | +| `is_default` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_party_bank_accounts_party` su `party_id` + +#### `party_categories` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(10) | no | | | +| `description` | String(100) | no | | | +| `disabled` | Bool | no | `false` | | +| `is_demo` | Bool | no | `false` | | +| `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_party_categories_code` su `code` + +#### `party_contacts` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `party_id` | Int64 | no | | -> `parties` (Cascade) | +| `name` | String(120) | no | | | +| `role` | String(80) | sì | | | +| `phone` | String(40) | sì | | | +| `mobile` | String(40) | sì | | | +| `email` | String(200) | sì | | | +| `is_default` | Bool | no | `false` | | +| `notes` | Text | sì | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_party_contacts_party` su `party_id` + +#### `party_fiscal` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `party_id` | Int64 | no | | -> `parties` (Cascade) | +| `recipient_code` | String(7) | sì | | | +| `recipient_pec` | String(200) | sì | | | +| `administration_reference` | String(20) | sì | | | +| `attach_pdf` | Bool | no | `true` | | +| `send_copy` | Bool | no | `false` | | +| `split_payment` | Bool | no | `false` | | +| `reverse_charge` | Bool | no | `false` | | +| `tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) | +| `exigibility` | String(1) | sì | | | +| `stamp_duty_charged` | Bool | no | `true` | | +| `withholding` | Bool | no | `false` | | +| `withholding_rate` | Decimal(19,6) | sì | | | +| `withholding_reason` | String(4) | sì | | | +| `pension_fund` | String(4) | sì | | | +| `pension_fund_rate` | Decimal(19,6) | sì | | | +| `enasarco` | Bool | no | `false` | | +| `intent_active` | Bool | no | `false` | | +| `intent_number` | String(40) | sì | | | +| `intent_date` | Date | sì | | | +| `intent_protocol` | String(40) | sì | | | +| `intent_tax_code_id` | Int64 | sì | | -> `tax_codes` (Restrict) | +| `intent_ceiling` | Decimal(19,6) | sì | | | +| `intent_used` | Decimal(19,6) | no | `0` | | +| `intent_from` | Date | sì | | | +| `intent_to` | Date | sì | | | +| `gln` | String(13) | sì | | | +| `eori` | String(17) | sì | | | +| `our_code` | String(40) | sì | | | +| `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_party_fiscal_party` su `party_id` + +#### `party_item_codes` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `party_id` | Int64 | no | | -> `parties` (Cascade) | +| `item_id` | Int64 | no | | -> `items` (Cascade) | +| `code` | String(40) | no | | | +| `description` | String(200) | sì | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_party_item_codes_item` su `item_id` +- indice unico `ux_party_item_codes_party_code` su `party_id`, `code` + +#### `party_purchase_terms` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `party_id` | Int64 | no | | -> `parties` (Cascade) | +| `payment_term_id` | Int64 | sì | | -> `payment_terms` (Restrict) | +| `lead_time_days` | Int32 | sì | | | +| `minimum_order` | Decimal(19,6) | sì | | | +| `discount` | Decimal(19,6) | sì | | | +| `shipping_term_id` | Int64 | sì | | -> `shipping_terms` (Restrict) | +| `vat_register_code` | String(10) | sì | | | +| `cost_account_code` | String(20) | sì | | | +| `orders_email` | String(200) | sì | | | +| `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_party_purchase_terms_party` su `party_id` + +#### `party_sales_terms` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `party_id` | Int64 | no | | -> `parties` (Cascade) | +| `price_list_id` | Int64 | sì | | -> `price_lists` (Restrict) | +| `discount1` | Decimal(19,6) | sì | | | +| `discount2` | Decimal(19,6) | sì | | | +| `payment_term_id` | Int64 | sì | | -> `payment_terms` (Restrict) | +| `company_bank_account_id` | Int64 | sì | | -> `bank_accounts` (Restrict) | +| `carrier_id` | Int64 | sì | | -> `carriers` (Restrict) | +| `shipping_term_id` | Int64 | sì | | -> `shipping_terms` (Restrict) | +| `warehouse_id` | Int64 | sì | | -> `warehouses` (Restrict) | +| `credit_limit` | Decimal(19,6) | sì | | | +| `blocked` | Bool | no | `false` | | +| `group_delivery_notes` | Bool | no | `true` | | +| `invoice_day` | Int32 | sì | | | +| `send_documents` | String(40) | no | | | +| `documents_email` | String(200) | sì | | | +| `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_party_sales_terms_party` su `party_id` + +#### `payment_methods` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(10) | no | | | +| `description` | String(100) | no | | | +| `disabled` | Bool | no | `false` | | +| `e_invoice_code` | String(4) | no | | | +| `needs_bank` | Bool | no | `false` | | +| `is_demo` | Bool | no | `false` | | +| `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_payment_methods_code` su `code` + +#### `payment_term_lines` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `payment_term_id` | Int64 | no | | -> `payment_terms` (Cascade) | +| `number` | Int32 | no | | | +| `days` | Int32 | no | | | +| `end_of_month` | Bool | no | `false` | | +| `fixed_day` | Int32 | sì | | | +| `percent` | Decimal(19,6) | 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_payment_term_lines_payment_term_id_number` su `payment_term_id`, `number` + +#### `payment_terms` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(10) | no | | | +| `description` | String(100) | no | | | +| `disabled` | Bool | no | `false` | | +| `payment_method_id` | Int64 | sì | | -> `payment_methods` (Restrict) | +| `condition` | String(4) | no | | | +| `vat_on_first_installment` | Bool | no | `false` | | +| `is_demo` | Bool | no | `false` | | +| `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_payment_terms_code` su `code` + +#### `price_lists` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(10) | no | | | +| `description` | String(100) | no | | | +| `disabled` | Bool | no | `false` | | +| `currency_code` | String(3) | no | | | +| `vat_included` | Bool | no | `false` | | +| `valid_from` | Date | sì | | | +| `valid_to` | Date | sì | | | +| `base_price_list_id` | Int64 | sì | | -> `price_lists` (Restrict) | +| `markup_percent` | Decimal(19,6) | no | | | +| `rounding_step` | Decimal(19,6) | no | | | +| `is_demo` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | +| `is_base` | Bool | no | `false` | | + +- indice unico `ux_price_lists_code` su `code` + +#### `provinces` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(2) | no | | | +| `description` | String(100) | no | | | +| `disabled` | Bool | no | `false` | | +| `region` | String(60) | sì | | | +| `is_demo` | Bool | no | `false` | | +| `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_provinces_code` su `code` + #### `role_permissions` | Colonna | Tipo | Null | Default | Note | @@ -851,6 +1743,27 @@ Migrazioni applicate in ordine: - indice unico `ux_roles_code` su `code` +#### `salespeople` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(10) | no | | | +| `description` | String(100) | no | | | +| `disabled` | Bool | no | `false` | | +| `email` | String(254) | sì | | | +| `phone` | String(30) | sì | | | +| `commission_percent` | Decimal(19,6) | no | | | +| `enasarco` | Bool | no | `false` | | +| `is_demo` | Bool | no | `false` | | +| `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_salespeople_code` su `code` + #### `schema_version` | Colonna | Tipo | Null | Default | Note | @@ -863,6 +1776,103 @@ Migrazioni applicate in ordine: Chiave primaria: `module`, `version`. +#### `shipping_terms` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(10) | no | | | +| `description` | String(100) | no | | | +| `disabled` | Bool | no | `false` | | +| `is_demo` | Bool | no | `false` | | +| `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_shipping_terms_code` su `code` + +#### `tax_codes` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(10) | no | | | +| `description` | String(100) | no | | | +| `disabled` | Bool | no | `false` | | +| `rate` | Decimal(19,6) | no | | | +| `nature` | String(5) | sì | | | +| `kind` | String(40) | no | | | +| `exigibility` | String(40) | no | | | +| `non_deductible_percent` | Decimal(19,6) | no | | | +| `legal_reference` | String(200) | sì | | | +| `valid_from` | Date | sì | | | +| `valid_to` | Date | sì | | | +| `sales_account_code` | String(20) | sì | | | +| `purchase_account_code` | String(20) | sì | | | +| `is_demo` | Bool | no | `false` | | +| `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_tax_codes_code` su `code` + +#### `transport_means` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(10) | no | | | +| `description` | String(100) | no | | | +| `disabled` | Bool | no | `false` | | +| `is_demo` | Bool | no | `false` | | +| `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_transport_means_code` su `code` + +#### `transport_reasons` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(10) | no | | | +| `description` | String(100) | no | | | +| `disabled` | Bool | no | `false` | | +| `is_demo` | Bool | no | `false` | | +| `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_transport_reasons_code` su `code` + +#### `units_of_measure` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(10) | no | | | +| `description` | String(100) | no | | | +| `disabled` | Bool | no | `false` | | +| `decimals` | Int32 | no | | | +| `e_invoice_code` | String(10) | sì | | | +| `is_demo` | Bool | no | `false` | | +| `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_units_of_measure_code` su `code` + #### `user_permission_overrides` | Colonna | Tipo | Null | Default | Note | @@ -972,4 +1982,25 @@ Chiave primaria: `module`, `version`. - indice unico `ux_users_user_name` su `user_name` +#### `warehouses` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(10) | no | | | +| `description` | String(100) | no | | | +| `disabled` | Bool | no | `false` | | +| `address` | String(200) | sì | | | +| `city` | String(100) | sì | | | +| `province_code` | String(2) | sì | | | +| `is_default` | Bool | no | `false` | | +| `is_demo` | Bool | no | `false` | | +| `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_warehouses_code` su `code` + diff --git a/docs/DEPLOY.md b/docs/DEPLOY.md index 7ef2aa0..f587b5c 100644 --- a/docs/DEPLOY.md +++ b/docs/DEPLOY.md @@ -219,7 +219,8 @@ Regole (SPEC §16.6, E1): VERSION` (`/p:Version`) insieme a `GIT_SHA` (`/p:SourceRevisionId`, mostrato come `+sha`). - Dove compare (SPEC §16.5): barra superiore (`major.minor`), barra di stato (completa), *Stato sistema*, `manifest.webmanifest`, etichette OCI, icona versionata. -- Milestone: `v0.0.1` (M0) … `v0.12.0` (M12), `v1.0.0` (M13), `v1.1.0`+ (M14) — SPEC §20. +- Milestone: `v0.0.1` (M0) … `v0.12.0` (M12), `v0.13.0` (M13), `v0.14.0`+ (M14). La `1.0.0` si crea solo quando + l'utente lo decide (emendamento E7 in `CLAUDE.md`, che modifica SPEC §20). - Le migrazioni non si riscrivono mai dopo un rilascio: una correzione è una migrazione nuova. ## 8. Endpoint di salute diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 5fe8bae..bb3f45f 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -34,8 +34,10 @@ Se manca l'SDK 10 ci si ferma e lo si chiede al titolare (SPEC §23). Su Windows | `scripts/gen-datamodel.sh [--check]` | rigenera la sezione generata di `docs/DATA-MODEL.md` dalle migrazioni; `--check` verifica soltanto | | `KHAEMHAT_PERF=1 scripts/test.sh --filter TestCategory=Performance` | misure di riferimento dello strato dati con 100.000 righe (`docs/DATA-MODEL.md` §6.1) | -Gli stub `seed.sh` (M4) e `restore-system.sh` (M12, incluso nell'immagine, ADR 0017) spiegano l'uso previsto ed -escono con errore finché la loro milestone non li completa. +`scripts/seed.sh --base [--company CODICE]` aggiunge i dati di base mancanti (ADR 0026) con le variabili `KHAEMHAT_*` +già impostate (ad esempio quelle di `run-dev.sh`); è incluso nell'immagine in `/app/scripts/`. `--demo` arriva con +anagrafiche e articoli. Lo stub `restore-system.sh` (M12, incluso nell'immagine, ADR 0017) spiega l'uso previsto ed +esce con errore finché la sua milestone non lo completa. #### Test sui due motori diff --git a/docs/STATUS.md b/docs/STATUS.md index 24e416e..c0d834e 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -2,19 +2,19 @@ > Punto di ripresa per ogni sessione. Aggiornare a fine sessione. -**Ultimo aggiornamento:** 2026-11-11 -**Milestone corrente:** M4 — Tabelle, anagrafiche, articoli (issue #37-#46, nel progetto in *Da fare*). M3 chiusa: -PR #119 in `main`, tag `v0.3.0`, immagine e release. -**Prossimo passo:** M4, a partire dal pacchetto fiscale (#37) e dal profilo azienda (#38). #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 +**Ultimo aggiornamento:** 2026-11-12 +**Milestone corrente:** M4 — Tabelle, anagrafiche, articoli: chiusa sul ramo `feat/37-tabelle-anagrafiche` (#46), +in attesa del merge in `main` con l'approvazione del titolare; poi tag `v0.4.0`, immagine e release. +**Prossimo passo:** dopo il merge, M5 — Motore documenti e Vendite (#47-#54). #35 (PNG ad alta risoluzione) resta +aperta e non blocca; #45 resta aperta solo per le banche ABI/CAB (manca una fonte con licenza compatibile). +Da recuperare: profilo dell'azienda demo (indirizzo, partita IVA) prima dei documenti di M5; misure di riferimento su PostgreSQL in `docs/DATA-MODEL.md` §6.1; indicatore di robustezza della +password (mockup 003); schede *Layout salvati* e *Notifiche* (con le e-mail, M5) del profilo; rinomina e filtro predefinito nei radar. ## Fatto -- Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E6. -- ADR 0001-0024. +- Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E7. +- ADR 0001-0031. - 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`, @@ -50,6 +50,14 @@ filtro predefinito nei radar. cestino e storico; anteprima di stampa A4; catalogo dei componenti e documento di prova per gli sviluppatori; primi screenshot reali in `docs/wiki/img/`; ADR 0020-0024. Test: 368 verdi in locale, 21 di PostgreSQL saltati; immagine costruita in locale e avviata da zero con SQLite. +- **M4 (chiusa, `v0.4.0`):** pacchetto fiscale `IT 2026.3` (codici IVA, nature, code list FatturaPA, motore IVA, + calendario, ritenute, F24; ADR 0025); validatori e `ViesClient`; 26 tabelle azienda con un'unica maschera, profilo + azienda, esercizi e cambi BCE (ADR 0026); dati di base con province e comuni ISTAT e CAP GeoNames (ADR 0028) e + `scripts/seed.sh --base|--demo`; codici automatici e compilazione automatica (ADR 0027); clienti, fornitori e + contatti con radar, scheda, controlli e VIES (ADR 0029); articoli e listini con prezzi a validità, listini derivati e + aggiornamento massivo (ADR 0030); import/export guidato CSV/XLSX/JSON con tracciato del piano dei conti (ADR 0031); + 21 anagrafiche e 120 articoli di esempio; screenshot reali nella wiki. Test: 631 verdi in locale, 21 di PostgreSQL + saltati; immagine costruita in locale e avviata da zero con SQLite e dati di esempio. - Su Gitea: etichette, milestone M0-M14, 114 issue con checklist, progetti *Khaemhat 1.0 — Sviluppo* (M0-M13) e *Khaemhat 1.1+ — Fase 2* (M14). Numerazione: M0 #1-#6 e #114, M1 #7-#14, M2 #15-#24, M3 #25-#36, M4 #37-#46, M5 #47-#54, M6 #55-#61, M7 #62-#68, M8 #69-#73, M9 #74-#81, M10 #82-#87, M11 #88-#91, diff --git a/docs/adr/0025-pacchetto-fiscale-a-funzioni.md b/docs/adr/0025-pacchetto-fiscale-a-funzioni.md new file mode 100644 index 0000000..4eda851 --- /dev/null +++ b/docs/adr/0025-pacchetto-fiscale-a-funzioni.md @@ -0,0 +1,51 @@ +# ADR 0025 - Pacchetto fiscale con parti obbligatorie e funzioni facoltative + +- **Stato:** accettata +- **Data:** 2026-11-11 +- **Modifica:** SPEC §1.10, §3, §21 (Fiscal e Validatori); ADR 0007; milestone M4, issue #37 e #40 + +## Contesto + +ADR 0007 isola la fiscalità in `Khaemhat.Fiscal.Abstractions` (interfacce) e `Khaemhat.Fiscal.Italy` +(implementazione). SPEC §21 elenca una dozzina di interfacce (`ITaxEngine`, `IEInvoiceFormat`, `IWithholdingRules`, +`IIntrastatExporter`…), ma non dice come il pacchetto le espone né cosa succede a quelle che arrivano con milestone +successive (FatturaPA in M9, bilancio CEE e Intrastat in M10). Inoltre non tutti i paesi hanno tutte le funzioni: +un paese fuori dall'UE non ha Intrastat, non ovunque esistono le ritenute d'acconto. + +## Decisione + +1. **Tre parti obbligatorie** come proprietà di `IFiscalPack`: `TaxCodes` (`ITaxCodeCatalog`: nature, codici IVA di + base, regole del codice IVA), `TaxEngine` (`ITaxEngine`: arrotondamenti, castelletto, bollo) e `Calendar` + (`IFiscalCalendar`: periodi, scadenze, festivi). Ogni paese ha imposte e scadenze. +2. **Funzioni facoltative** chieste per tipo: `GetFeature()` restituisce `null` se il paese (o la versione) non + la offre; `Require()` lancia `FiscalFeatureNotAvailableException` con paese e funzione. In 0.4.0 il pacchetto + italiano offre `IEInvoiceFormat` (versione delle specifiche e code list FatturaPA), `IWithholdingRules`, + `IFixedAssetRules` e `ITaxPaymentFormExporter` (codici tributo F24); `IFinancialStatementsSchema`, + `IChartOfAccountsTemplate` e `IIntrastatExporter` sono definite ma arrivano con la milestone che le usa. +3. **Le interfacce crescono con le milestone.** Ognuna contiene oggi solo ciò che serve e si può verificare + (code list, regole, costanti); scrittori e lettori di file si aggiungono quando arriva la loro maschera. +4. **Problemi come codici.** Le regole restituiscono `FiscalProblem` (campo, codice stabile come + `fiscal.tax.nature-required`, errore o avviso); l'interfaccia traduce il codice con le risorse. +5. **Risoluzione per paese.** `FiscalPackCatalog` raccoglie i pacchetti registrati e li trova per + `company_profile.country` (senza distinzione di maiuscole). La composizione in `Hosting/KhaemhatServices.cs` è + l'unico file fuori dal pacchetto che nomina `Khaemhat.Fiscal.Italy`: lo verifica `FiscalPackIsolationTests`, che + controlla anche che le astrazioni non contengano nomi italiani. +6. **Identificativi italiani nel pacchetto.** SPEC §21 mette `ItalianVatNumberValidator`, `FiscalCodeValidator`, + `FiscalCodeCalculator` e `SdiRecipientCodeValidator` in `Khaemhat.Core`; il vincolo non negoziabile di SPEC §1.10 + ("tutto ciò che è italiano sta in `Fiscal.Italy`") prevale: stanno nel pacchetto italiano dietro la funzione + `ITaxIdentifierRules`, e la banca da IBAN dietro `IBankDirectory`. In `Core` restano i controlli internazionali: + `IbanValidator` (mod 97 e lunghezza per paese), `EanValidator` (EAN-8, UPC-A, EAN-13, GTIN-14), `EmailValidator`. + Il controllo VIES è `ViesClient` in `Infrastructure` (servizio REST della Commissione europea): un servizio che + non risponde dà *non disponibile*, mai *non valida*. +7. **Versione delle specifiche.** `FatturaPaCodeLists.SpecVersion` è **1.9.1** (pubblicata il 31 marzo 2026, in + vigore dal 15 maggio 2026; non cambia le code list della 1.9, che aveva introdotto TD29 e ridefinito TD20). Va + ricontrollata sul sito dell'Agenzia delle Entrate a ogni rilascio. + +## Conseguenze + +- Un modulo che usa una funzione facoltativa decide cosa mostrare quando manca (per esempio nascondere Intrastat), + invece di fallire alla prima chiamata. +- Codici IVA di base, nature e code list del seed (#45) vengono dal pacchetto: c'è un'unica fonte. +- La regola del bollo considera le nature N1, N2.x, N3.5, N3.6, N4 e N5; esportazioni, cessioni intracomunitarie, + San Marino, operazioni assimilate, inversione contabile e N7 non contano. È da rivedere con i documenti di + vendita (M5) se la normativa cambia. diff --git a/docs/adr/0026-tabelle-azienda-e-dati-di-base.md b/docs/adr/0026-tabelle-azienda-e-dati-di-base.md new file mode 100644 index 0000000..32e81fd --- /dev/null +++ b/docs/adr/0026-tabelle-azienda-e-dati-di-base.md @@ -0,0 +1,53 @@ +# ADR 0026 - Tabelle azienda generiche e dati di base solo in aggiunta + +- **Stato:** accettata +- **Data:** 2026-11-11 +- **Modifica:** SPEC §4 (`scripts/seed.sh`), §11.1, §14; ADR 0025; milestone M4, issue #38, #39 e #45 + +## Contesto + +SPEC §11.1 elenca una ventina di tabelle azienda (codici IVA, pagamenti, depositi, vettori, numeratori, categorie…), +ognuna con elenco, dettaglio, import ed export CSV. SPEC §14 chiede che le tabelle di base si carichino alla creazione +dell'azienda e si aggiornino a ogni versione "senza toccare le righe modificate dall'azienda", ma non dice come +riconoscere una riga modificata. Province, comuni con CAP e la tabella ABI/CAB delle banche sono elenchi pubblici +grandi (8.000 comuni, decine di migliaia di sportelli) che non sono nel repository e hanno licenze da verificare. + +## Decisione + +1. **Un servizio per tutte le tabelle codificate.** Ogni tabella è un'entità `CodedEntity` (codice, descrizione, + disattivata) descritta in `TableCatalog`: le regole comuni (codice unico, una sola riga predefinita, eliminazione + rifiutata se la riga è usata e proposta di disattivarla, storico, cache invalidata fra istanze, CSV tutto o niente) + stanno in `TableService`. Le regole proprie di una tabella sono funzioni del catalogo; quelle italiane (natura + IVA, codici SDI) arrivano dal pacchetto fiscale (ADR 0025). +2. **Una maschera generica.** L'interfaccia descrive ogni tabella in `TableScreens` (campi, tipo, lookup, code list + del pacchetto) e la mostra con un unico editor `KhTableEditor` all'indirizzo `/tabelle/`. Profilo + azienda, esercizi e cambi hanno pagine proprie perché non sono elenchi di codici. +3. **Dati di base solo in aggiunta.** Il caricamento inserisce **solo i codici che mancano** e non modifica né + cancella righe esistenti, anche se identiche al pacchetto: una riga presente è dell'azienda. Non serve quindi + distinguere righe "modificate" da righe "originali". La versione caricata è salvata nelle impostazioni + dell'azienda (`seed.base.version`, ad esempio `IT 2026.2`). Correggere una riga di base già presente è un'azione + esplicita dell'utente, non dell'aggiornamento. +4. **Origine delle righe.** Righe fiscali (codici IVA, modalità e condizioni di pagamento, tipi documento) dal + pacchetto del paese tramite `IBaseTablesTemplate`; paesi ISO da un CSV incorporato; valute BCE, unità di misura, + trasporti, causali, deposito principale, listino base, numeratori ed esercizio corrente dal seeder di base. +5. **Comuni.** Il **codice** di un comune è il suo codice catastale (4 caratteri, quello del codice fiscale): non + serve una colonna in più. +6. **Elenchi pubblici caricati a parte.** Province, comuni con CAP e banche ABI/CAB non sono nel seed di 0.4.0: + arriveranno come file di dati con origine e licenza indicate (ISTAT, CC BY 4.0, per province e comuni) dopo il + via dell'utente al download. Fino ad allora le tabelle si riempiono a mano o con l'import CSV. + *Aggiornato dall'ADR 0028:* province e comuni ISTAT, con i CAP di GeoNames, sono nei dati di base dalla + versione `IT 2026.3`; le banche restano fuori. +7. **Riga di comando.** `scripts/seed.sh --base [--company CODICE]` esegue la sequenza di avvio senza servire pagine + (migrazioni, prima azienda) e aggiunge i dati di base a un'azienda o a tutte quelle attive. Nel container lo + script è in `/app/scripts/` e passa da `entrypoint.sh` con il verbo `seed`; in sviluppo usa `dotnet run`. + `--demo` e `--scale` arrivano con anagrafiche e articoli. + +## Conseguenze + +- Un aggiornamento delle tabelle di base non può mai rovinare una configurazione aziendale; il rovescio è che una + correzione a un codice già presente (ad esempio un riferimento normativo cambiato) va comunicata nel `CHANGELOG` + e fatta dall'utente, o con una migrazione mirata quando è obbligatoria. +- Aggiungere una tabella costa un'entità, una mappa, una voce in `TableCatalog` e una in `TableScreens`, più i testi: + i test controllano che ogni schermata abbia le chiavi di testo e ogni codice di errore la sua traduzione. +- Il pulsante *Aggiorna da tabelle base* delle maschere e la pagina di amministrazione (mockup 089) usano lo + stesso `SeedRunner`. 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/adr/0028-elenco-istat-di-province-e-comuni.md b/docs/adr/0028-elenco-istat-di-province-e-comuni.md new file mode 100644 index 0000000..68beba5 --- /dev/null +++ b/docs/adr/0028-elenco-istat-di-province-e-comuni.md @@ -0,0 +1,53 @@ +# ADR 0028 - Province e comuni dall'elenco ISTAT e CAP da GeoNames nel pacchetto fiscale + +- **Stato:** accettata +- **Data:** 2026-11-12 +- **Modifica:** ADR 0026 punto 6; SPEC §11.1, §11.12, §14; milestone M4, issue #45 + +## Contesto + +L'ADR 0026 rimandava province, comuni con CAP e banche ABI/CAB a file di dati con origine e licenza verificate, +caricati dopo il via dell'utente. Il via è arrivato il 2026-11-12 per due fonti: + +- l'**elenco dei codici dei comuni dell'ISTAT** (*Codici statistici delle unità amministrative territoriali*), + pubblicato con licenza **CC BY 4.0** (note legali ISTAT). Il file CSV allo stesso indirizzo è fermo al gennaio 2024 + e ha ancora le 107 province precedenti al riordino della Sardegna; il file xlsx è aggiornato al **26/02/2026** e ha + le **110 province** e i **7.894 comuni** in vigore; +- il repository **comuni-json** per i CAP. La sua licenza non è MIT come si era ipotizzato: i comuni vengono + dall'ISTAT (CC BY), ma per i CAP l'autore dichiara che le fonti non indicano una licenza e che al repository + **non si applica nessuna licenza**. I dati sono fermi al 01/01/2020, prima delle fusioni di comuni successive. + +## Decisione + +1. **Province e comuni nel pacchetto fiscale.** Sono dati italiani, quindi stanno in `Khaemhat.Fiscal.Italy` + (`Data/province.csv`, `Data/comuni.csv`, risorse incorporate) dietro una nuova funzione facoltativa del pacchetto, + `IPlaceDirectory` (province, comuni, origine). `BaseTablesSeeder` li aggiunge come il resto dei dati di base: solo + i codici mancanti, mai modificando una riga già presente. +2. **Formato ridotto.** Dal foglio ISTAT si tengono, per le province, sigla, denominazione e regione; per i comuni, + codice catastale (il **codice** del comune, ADR 0026), denominazione in italiano, sigla della provincia, regione e + codice ISTAT a 6 cifre. I file si rigenerano dal foglio ISTAT con lo stesso schema; ogni aggiornamento porta una + nuova versione dei dati del pacchetto (da `IT 2026.2` a `IT 2026.3`). +3. **Attribuzione.** L'origine (ISTAT, data dell'elenco, CC BY 4.0; GeoNames per i CAP) è scritta in + `ItalianPlaces.ListSource`, nella wiki *Dati di base e di esempio* e in questo ADR. +4. **Niente CAP da comuni-json.** Un file senza licenza non entra in un repository pubblico né nell'immagine + distribuita, e i CAP del 2020 sarebbero comunque incompleti. +5. **CAP da GeoNames.** Con un secondo via dell'utente (2026-11-12) i CAP vengono dall'elenco dei codici postali + italiani di **GeoNames** (`IT.zip`, CC BY 4.0, attribuzione a www.geonames.org). GeoNames elenca località, non + comuni: una riga si assegna a un comune quando nome (senza accenti, apostrofi e trattini, parte italiana dei nomi + bilingui) e sigla della provincia coincidono con un solo comune; in Sardegna, dove le sigle sono cambiate, basta + il nome entro la regione. Le frazioni con nome proprio restano fuori. Risultato: **7.750 comuni su 7.894** hanno i + CAP (un CAP, una lista o intervalli come `10121-10156`); i 144 senza sono in gran parte comuni rinominati o nati da + fusioni (ad esempio Sanremo, che GeoNames chiama *San Remo*) e si completano a mano o con l'**Importa CSV**. +6. **Strumento di rigenerazione.** `tools/Khaemhat.PlacesTool` (non distribuito, solo framework) legge il foglio ISTAT + e `IT.zip` e riscrive `Data/province.csv` e `Data/comuni.csv`; i file scaricati restano fuori dal repository. +7. **Banche ABI/CAB** restano fuori finché non c'è una fonte aperta con licenza chiara (ADR 0026, ADR 0027 punto 6). + +## Conseguenze + +- Un'azienda nuova ha subito province, comuni e CAP: il calcolo del codice fiscale, la scelta del comune e la + compilazione dal CAP funzionano senza caricare nulla. Le aziende esistenti li ricevono al primo avvio con la + versione `IT 2026.3`, o con *Aggiorna tabelle di base*. +- Il caricamento di base aggiunge circa 8.000 righe alla creazione dell'azienda: su SQLite resta sotto i due secondi; + su PostgreSQL va misurato insieme alle altre misure di riferimento (`docs/DATA-MODEL.md` §6.1). +- Un comune soppresso per fusione resta nella tabella di chi lo aveva già: va disattivato a mano. Le variazioni + vanno annotate nel `CHANGELOG` quando si aggiorna l'elenco. diff --git a/docs/adr/0029-anagrafiche.md b/docs/adr/0029-anagrafiche.md new file mode 100644 index 0000000..a0f2e07 --- /dev/null +++ b/docs/adr/0029-anagrafiche.md @@ -0,0 +1,65 @@ +# ADR 0029 - Anagrafiche: un archivio per clienti, fornitori, prospect e lead + +- **Stato:** accettata +- **Data:** 2026-11-12 +- **Modifica:** SPEC §9 (modello dati delle anagrafiche), §11.2, §11.12, §14; milestone M4, issue #41 + +## Contesto + +SPEC §11.2 descrive clienti, fornitori, prospect e lead con radar (mockup 012-013), scheda a gruppi (014-016), +condizioni commerciali, dati fiscali e SDI, banche, contatti e indirizzi. §9 elenca le tabelle `parties` e i +dettagli, ma lascia aperti alcuni punti: come si rappresenta un soggetto che è sia cliente sia fornitore, che codice +riceve un prospect, quando si verifica il VIES, come si cancella un'anagrafica usata, come sono fatti i dati di +esempio prima che esistano gli articoli e i documenti. + +## Decisione + +1. **Un archivio, quattro tipi.** `parties` ha un `kind` (*Customer*, *Supplier*, *Prospect*, *Lead*) e un + `subject_type` (*Company*, *Person*, *PublicAdministration*, *EuCompany*, *NonEuCompany*, *FlatRate*) che decide i + controlli e i valori proposti. Un soggetto che è sia cliente sia fornitore è un **cliente** con + `is_also_supplier`: compare in entrambi i radar con lo stesso codice cliente. Un fornitore che diventa cliente + (azione *Converti in cliente*) diventa quindi `Customer` con `is_also_supplier = true` e tiene il suo codice. +2. **Tre radar.** `/anagrafiche/clienti` (tipo *Customer*), `/anagrafiche/fornitori` (*Supplier* più i clienti che + sono anche fornitori), `/anagrafiche/contatti` (*Prospect* e *Lead*, con il filtro rapido del tipo). +3. **Codici.** Clienti e fornitori usano le maschere `customers` e `suppliers`; prospect e lead la maschera `leads` + (`L{anno}-{seq:0000}`, ADR 0027). Alla conversione in cliente un prospect o un lead riceve il codice cliente e il + vecchio resta in `previous_code`, così i riferimenti esterni (e-mail, appunti) si ritrovano con la ricerca. +4. **Dettagli in tabelle proprie.** Indirizzi, contatti e conti sono liste (`party_addresses`, `party_contacts`, + `party_bank_accounts`, al più un predefinito per tipo); condizioni di vendita, di acquisto e dati fiscali sono + tabelle 1:1 (`party_sales_terms`, `party_purchase_terms`, `party_fiscal`) create insieme all'anagrafica. Il + salvataggio riscrive la scheda intera in una transazione; lo storico registra testata e dettagli. La cancellazione + dei dettagli è a cascata. +5. **Controlli dal pacchetto fiscale.** Partita IVA, codice fiscale, codice destinatario e PEC passano da + `ITaxIdentifierRules` (ADR 0025). Errori bloccanti: ragione sociale, P.IVA per un'impresa, identificativo per una + PA, codice fiscale non valido, codice duplicato, paese incoerente con il tipo soggetto, dichiarazione d'intento + senza numero o plafond. **Avvisi**, che non bloccano: P.IVA già usata da un'altra anagrafica (filiali, sedi + distinte), privato senza codice fiscale. Per un cliente privato o estero, o per un'impresa con sola PEC, il codice + destinatario mancante si compila con il valore del formato (`0000000`, `XXXXXXX`). +6. **VIES al salvataggio.** Per un'impresa UE la verifica parte dopo il commit, solo se la P.IVA o il paese sono + cambiati o non è mai stata verificata, e solo se la compilazione automatica *Vies* è accesa. L'esito (*valida*, + *non valida*, *non verificata*) e la data restano sull'anagrafica; un VIES irraggiungibile non impedisce di + salvare. L'azione *Verifica VIES* della scheda ripete la verifica. Le date sono `DateTime` in UTC, come nel + resto del modello. +7. **Cancellare o disattivare.** *Elimina* prova a cancellare; se il database rifiuta per riferimenti (documenti dalle + prossime milestone), l'anagrafica viene **disattivata** e l'utente lo legge in un messaggio. Il radar disattiva e + riattiva più righe insieme; le disattivate sono escluse per filtro iniziale. +8. **Dati di esempio senza documenti.** `DemoPartiesSeeder` (seeder *Demo*, solo se le anagrafiche sono vuote) crea + 3 agenti e 21 anagrafiche con `is_demo`: 12 clienti che coprono tutti i tipi soggetto (PA con split payment, + cliente bloccato, disattivato, anche fornitore, con dichiarazione d'intento), 5 fornitori (ritenuta, ENASARCO, UE), + 2 prospect e 2 lead. Partite IVA, codici fiscali e IBAN sono **numeri inventati ma formalmente validi** (cifra di + controllo, mod 97), scritti come costanti e controllati da un test; nessuno appartiene a un soggetto reale per + scelta, ma la coincidenza non si può escludere e per questo non si verificano sul VIES. Il volume completo della + SPEC (40 clienti, 15 fornitori, documenti) arriva in M9 con `seed --demo`. +9. **Rinviati.** `party_item_codes` (codici articolo del cliente o del fornitore) arriva con gli articoli (#42); + fatturato, scaduto, fido usato e *Scheda 360°* con vendite (M5) e scadenzario (M9); il flag utente *vede solo i + propri clienti* con i filtri per riga sui permessi, non ancora previsti in una milestone. Gli agenti di esempio non hanno `is_demo` perché la tabella + degli agenti (ADR 0026) non ha la colonna: si rimuovono a mano. + +## Conseguenze + +- Una sola tabella e una sola query per i tre radar; le condizioni commerciali si leggono con un join 1:1. +- Il passaggio fornitore → cliente non cambia codice né documenti; il passaggio prospect → cliente cambia codice e + lascia traccia in `previous_code` e nello storico. +- I controlli fiscali italiani restano nel pacchetto; un altro paese porterà le sue regole senza toccare il servizio. +- I dati di esempio non hanno numeri reali e restano validi per i controlli, quindi le prove automatiche li usano come + casi realistici (ogni anagrafica di esempio supera `ValidateAsync`). diff --git a/docs/adr/0030-articoli-e-listini.md b/docs/adr/0030-articoli-e-listini.md new file mode 100644 index 0000000..129af9c --- /dev/null +++ b/docs/adr/0030-articoli-e-listini.md @@ -0,0 +1,67 @@ +# ADR 0030 - Articoli e listini: prezzi con validità, listini derivati, ricerca del prezzo + +- **Stato:** accettata +- **Data:** 2026-11-12 +- **Modifica:** SPEC §9 (modello dati degli articoli), §11.2, §11.3, §14; milestone M4, issue #42 + +## Contesto + +SPEC §11.2 descrive la scheda articolo (mockup 017) con UM alternative, codici alternativi, listini, fornitori, +sostitutivi, giacenze e movimenti, e la griglia dei listini (mockup 018) con modifica in cella e aggiornamento +massivo. §11.3 fissa l'ordine di ricerca del prezzo di una riga (netto cliente-articolo, listino del cliente o del +documento, listino base, prezzo dell'articolo) e dice che i listini hanno validità, possono essere derivati e hanno +regole di arrotondamento. Restavano aperti: dove stanno i prezzi netti dei clienti, come convivono prezzi vecchi e +nuovi, quale listino è "il base", come si calcola un listino derivato, che cosa vede chi non può vedere i costi, che +cosa si fa delle giacenze prima del magazzino (M6). + +## Decisione + +1. **Una tabella di prezzi.** `item_prices` tiene sia i prezzi di listino (`price_list_id`) sia i **prezzi netti** + di un cliente (`party_id`): una riga ha esattamente uno dei due. Ogni riga ha un `valid_from`; il prezzo in vigore + a una data è quello con l'**inizio più recente non successivo** alla data (una riga senza data vale sempre). + Scrivere un prezzo con una data nuova aggiunge una riga, così i documenti già fatti e quelli datati prima + ritrovano il prezzo di allora; scriverlo con la stessa data cambia la riga, e "nessun prezzo" la toglie. Un prezzo + uguale a quello già in vigore non si riscrive. +2. **Listino base.** `price_lists.is_base` marca il listino base (al più uno, regola della tabella); in mancanza + vale quello con codice `BASE`, che i dati di base creano già marcato. La migrazione marca il `BASE` esistente. +3. **Listini derivati.** Un listino con `base_price_list_id` senza un proprio prezzo per l'articolo prende il prezzo + del listino di partenza alla stessa data, applica `markup_percent` (anche negativo) e arrotonda a `rounding_step` + (al centesimo se zero). Il prezzo scritto nel listino derivato vince su quello calcolato. La derivazione si segue + per al più cinque livelli. Il calcolo è in `PriceBook`, che lavora in memoria sui prezzi letti una volta. +4. **Ricerca del prezzo** (`PriceListService.QuoteAsync`, usata dai documenti da M5): netto del cliente, poi il + listino del documento o del cliente se valido alla data, poi il listino base, poi `items.price`. La risposta dice + la **fonte** (`PriceSource`), che la riga del documento conserva. Gli sconti 1 e 2 del cliente si propongono come + formula a cascata (`10+5`), **mai su un prezzo netto**. +5. **Griglia dei listini.** Legge e scrive tutti i prezzi a **una data di validità** scelta in alto (oggi di + default). Le celle modificate e quelle calcolate dall'aggiornamento massivo restano in sospeso, evidenziate, finché + non si salva; l'anteprima dell'aggiornamento massivo (`PreviewAsync`) non scrive nulla. Le celle dei listini + derivati senza prezzo proprio sono in corsivo. +6. **Costi.** Costo standard, ultimo costo e costo medio si vedono solo con `items.cost.read`; per gli altri il + servizio li restituisce vuoti e al salvataggio conserva quelli in archivio. Ultimo costo e costo medio non si + scrivono dalla scheda: li aggiornano i carichi di magazzino (M6); fino ad allora li valorizzano solo i dati di + esempio. Il margine è sul prezzo: (prezzo - costo) / prezzo. +7. **Tipi e magazzino.** Solo le merci possono essere *gestite a magazzino*; servizi, spese, righe descrittive e + cespiti non lo sono mai (il servizio lo corregge). Giacenze, impegni, movimenti e proposta di riordino arrivano + con il magazzino (M6): la scheda li annuncia, i campi di riordino si compilano già. +8. **Codici.** Il codice segue la maschera `items` (`{categoria}-{seq:0000}`, ADR 0027); se la maschera usa la + categoria, la categoria è obbligatoria. Il codice a barre principale e quelli delle UM alternative hanno la + verifica EAN; un codice a barre già usato da un altro articolo è un avviso, o un errore se le preferenze chiedono + codici a barre univoci. La ricerca degli articoli trova esattamente anche i **codici alternativi** e, nei + documenti di un'anagrafica, i **codici che quell'anagrafica usa** (`party_item_codes`). +9. **Codici dell'anagrafica.** `party_item_codes` si gestisce nella scheda *Articoli e codici* dell'anagrafica e si + salva con essa (un codice non si ripete per la stessa anagrafica); i controlli sono di `ItemService`. +10. **Cancellazione.** Un articolo usato (sostitutivo di un altro, in documenti da M5) si disattiva invece di + cancellarsi, come le anagrafiche (ADR 0029). Un cliente con prezzi netti non si cancella. +11. **Dati di esempio.** `DemoItemsSeeder` crea 120 articoli fittizi di un grossista termoidraulico (SPEC §14) in dieci + categorie, due listini derivati dal base (*Pubblico* +45% arrotondato a 0,10, *Rivenditori* -10%), un prezzo + dell'anno precedente per lo storico, prezzi netti e codici di Rossi Impianti, fornitori abituali, UM alternative, + codici alternativi e sostitutivi. I codici a barre hanno prefisso 200, riservato all'uso interno. Il comando + `seed --demo [--scale N]` esegue prima i dati di base e poi quelli di esempio, ripetendo il catalogo N volte. + +## Conseguenze + +- I documenti (M5) chiamano `PriceListService.QuoteAsync` dentro la propria unità di lavoro e salvano prezzo e fonte; + la stessa logica serve l'API (`items`, `price-lists`) e il tool MCP `search_items`. +- Cambiare un prezzo non tocca i documenti esistenti; per correggere un prezzo sbagliato si riscrive con la stessa + data, per un aumento si usa una data nuova. +- Il magazzino (M6) aggiornerà `last_cost` e `average_cost` e aggiungerà le schede *Giacenze* e *Movimenti*. diff --git a/docs/adr/0031-import-e-export-guidato.md b/docs/adr/0031-import-e-export-guidato.md new file mode 100644 index 0000000..1ee4eff --- /dev/null +++ b/docs/adr/0031-import-e-export-guidato.md @@ -0,0 +1,69 @@ +# ADR 0031 - Import e export guidato: entità, tracciati, controlli come da scheda + +- **Stato:** accettata +- **Data:** 2026-11-12 +- **Modifica:** SPEC §11.7, §12.12, mockup 077; milestone M4, issue #44 + +## Contesto + +SPEC §12.12 chiede una procedura guidata di import/export (CSV, XLSX, JSON) per anagrafiche, articoli, listini, +giacenze iniziali, piano dei conti, saldi e partite di apertura, con mappatura delle colonne, validazione riga per +riga, report degli errori e un tracciato proprio del piano dei conti (`codice;descrizione;livello;padre;natura;tipo; +voce_cee;riclassifica;flag` e `khaemhat-coa.json`). Restavano aperti: dove sta la procedura, quali entità esistono già +in M4, come si controllano le righe, che cosa succede ai codici esistenti o mancanti, i valori ammessi di `natura`, +`tipo` e `flag`, come si legge un XLSX senza librerie esterne, chi può esportare. + +## Decisione + +1. **Dove.** Pagina `/amministrazione/import-export` (voce *Import / export dati* sotto *Amministrazione*, visibile + agli account di istanza), consegnata in M4 prima del resto dell'area (M13). Una persona dell'azienda la apre se ha + il permesso di scrittura o di export di almeno un'entità. +2. **Entità.** `IImportTarget` descrive un'entità: chiave, modulo di licenza, permesso di import e di export, colonne + (con alias per l'abbinamento automatico), verifica, scrittura ed export. In M4: `clienti`, `fornitori`, + `articoli`, `listini` (prezzi di listino e netti cliente), `giacenze-iniziali`, `piano-dei-conti`. Le ultime due + **si verificano soltanto** finché non esistono i movimenti di magazzino (M6) e la contabilità (M7): la procedura + prepara il file in anticipo, la scrittura arriva con il modulo. Saldi e partite di apertura arrivano con M7 e M9. +3. **Le righe passano dalla scheda.** Clienti, fornitori e articoli si leggono per codice (o si creano con i valori + proposti dalla scheda), si riempiono con le celle **non vuote** della riga e si controllano e salvano con + `PartyService` e `ItemService`: stesse regole, stessi codici di errore, stesso storico. Una cella vuota lascia il + valore che c'è. I codici di altre tabelle (categoria, pagamento, listino, agente, UM, IVA, deposito) devono + esistere. I prezzi si scrivono con `PriceListService` in una sola transazione (stessa voce e stessa data: + sostituisce; data nuova: aggiunge, come la griglia dei listini, ADR 0030). +4. **Opzioni.** *Se il codice esiste*: aggiorna (predefinito) o salta la riga (avviso). *Codice mancante*: genera con + le regole dei codici automatici (ADR 0027) o errore. Un codice scritto per un record nuovo rispetta la regola + (*codice manuale ammesso*). Un codice ripetuto nel file è un errore dalla seconda riga; un codice di un'anagrafica di + altro tipo è un errore. *Verifica P.IVA su VIES* chiama VIES durante l'import (spento: nessuna chiamata, qualunque + sia l'opzione automatica dell'azienda). *Completa comune da CAP* propone comune e provincia da un CAP con un solo + comune, o il CAP da un comune con un solo CAP, come avviso. +5. **Esiti.** Ogni riga ha *OK*, *avviso* (importabile) o *errore* (esclusa), con colonna, codice del testo e valore. + Si importano solo le righe senza errori; le altre finiscono nel **report errori** (CSV con riga, codice, colonna, + esito, messaggio). L'esito dell'import va nel log, sezione *Sistema*. +6. **Valori.** Numeri all'italiana (`1.234,56`) o con il punto decimale (`1234.56`, come li scrivono XLSX e JSON); + date `gg/mm/aaaa`, ISO, `aaaammgg` o numero seriale del foglio; sì/no come `sì`, `x`, `1`, `VERO`, `true` e i + contrari; le parole di una scelta senza badare a maiuscole, accenti e punteggiatura. +7. **Piano dei conti.** Codice di 1-3 parti separate da punto (mastro, conto, sottoconto); `livello` è il numero di + parti; `padre` è il codice senza l'ultima parte e deve essere nel file; la `natura` (`attivo`, `passivo`, `costo`, + `ricavo`, `ordine`) si eredita dal padre e non può essere diversa; `tipo` è `generico`, `clienti`, `fornitori`, + `banca`, `cassa`, `iva`, `erario` (nuovo `AccountType` in `Khaemhat.Core.Accounting`); `flag` è un insieme di lettere: + `M` movimentabile (solo conti senza sottoconti), `I` rilevante IVA, `P` con partitario, `C` chiusura automatica, + `X` disattivato. `khaemhat-coa.json` è un oggetto `{format, version, accounts, statementLines, journalTemplates, + mappings}`: `accounts` ha le stesse colonne, le altre sezioni si contano e si importano in M7. Il controllo è puro + (`ChartOfAccountsImportValidator`) perché M7 scriva esattamente ciò che accetta. +8. **File.** CSV in UTF-8 (con o senza BOM) o, se non è UTF-8 valido, Windows-1252; separatore `;`, `,` o tabulazione + dedotto dall'intestazione; l'apostrofo che l'export mette davanti al testo che inizia con `=`, `+`, `-`, `@` si + toglie. XLSX: primo foglio letto da `XlsxReader` (System.IO.Compression e XmlReader, DTD vietate, stringhe + condivise, celle in linea, numeri formattati come data restituiti come data). JSON: elenco di oggetti. Al più + 50.000 righe e 25 MB. +9. **Export e modelli.** L'export scrive le stesse colonne dell'import in CSV (`;`, UTF-8 con BOM, numeri e date + all'italiana), XLSX o JSON, così il file si corregge e si reimporta; richiede il permesso di export dell'entità e + il flag utente *Può esportare dati*. Il **modello** è il file con le sole intestazioni (in JSON un oggetto con i + valori vuoti). + +## Conseguenze + +- L'import non ha regole proprie: ogni regola nuova di una scheda vale subito anche per i file. +- Un file di un altro gestionale con codici propri richiede che la regola dei codici ammetta il codice manuale. +- M6 e M7 aggiungono la scrittura di giacenze e piano dei conti senza cambiare tracciati né controlli; M7 e M9 + aggiungono saldi e partite come nuove entità. +- Le righe si scrivono una alla volta (anagrafiche e articoli): un errore a metà non annulla le righe già scritte, + che il report indica come create o aggiornate. diff --git a/docs/wiki/Anagrafiche.md b/docs/wiki/Anagrafiche.md index 072dd5f..a294942 100644 --- a/docs/wiki/Anagrafiche.md +++ b/docs/wiki/Anagrafiche.md @@ -1,7 +1,7 @@ # Anagrafiche -> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M4) -> **Modulo di licenza:** CORE · **Permessi principali:** famiglia `parties.*` (`read`, `write`, `delete`, `export`; codici esatti definiti in sviluppo) · **Specifica:** SPEC §11.2, §11.12, §22 +> **Stato:** completa · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (milestone M4) +> **Modulo di licenza:** CORE · **Permessi principali:** `parties.party.read` (consultare), `parties.party.write` (inserire, modificare, disattivare, convertire), `parties.party.delete` (eliminare) · **Specifica:** SPEC §11.2, §11.12, §22 · **Decisioni:** ADR 0029 Le **anagrafiche** sono l'archivio unico delle controparti dell'azienda: **clienti**, **fornitori**, **prospect** e **lead**. Un soggetto è registrato una volta sola; il suo *tipo* (cliente, fornitore…) dice come viene usato. Dalla @@ -10,8 +10,9 @@ codici che il cliente o il fornitore usa per i tuoi articoli. ## Dove si trova -Menu **Anagrafiche** → **Clienti**, **Fornitori**, **Contatti** (prospect e lead), **Categorie**. Nello stesso menu ci -sono anche *Articoli* e *Listini* (vedi [Articoli e listini](Articoli-e-listini)). +Menu **Anagrafiche** → **Clienti** (`/anagrafiche/clienti`), **Fornitori** (`/anagrafiche/fornitori`), **Contatti** +(`/anagrafiche/contatti`, prospect e lead). Le categorie sono una tabella azienda (vedi [Tabelle azienda](Tabelle-azienda)). +Nello stesso menu arriveranno *Articoli* e *Listini* (vedi [Articoli e listini](Articoli-e-listini)). ## Tipi di anagrafica @@ -19,13 +20,15 @@ sono anche *Articoli* e *Listini* (vedi [Articoli e listini](Articoli-e-listini) |---|---|---| | **Cliente** | intestatario di preventivi, ordini, DDT e fatture di vendita | `C{seq:000000}` → `C000124` | | **Fornitore** | intestatario di ordini fornitore, DDT di carico, fatture di acquisto | `F{seq:000000}` → `F000032` | -| **Prospect** | potenziale cliente già qualificato, senza documenti fiscali | assegnato alla conversione in cliente | +| **Prospect** | potenziale cliente già qualificato, senza documenti fiscali | come i lead; alla conversione riceve il codice cliente | | **Lead** | contatto commerciale da qualificare (gestito con il CRM) | `L{anno}-{seq:0000}` → `L2026-0001` | -Lo stesso soggetto può essere sia cliente sia fornitore. +Lo stesso soggetto può essere sia cliente sia fornitore: è un **cliente** con la casella *È anche fornitore* e compare +in entrambi gli elenchi con lo stesso codice. -Il **tipo soggetto** (*azienda*, *privato*, *pubblica amministrazione*, *UE*, *extra-UE*, *forfettario*) determina -i controlli e i valori proposti: codice destinatario SDI, split payment, bollo, partita IVA estera. +Il **tipo soggetto** (*impresa italiana*, *privato*, *pubblica amministrazione*, *impresa UE*, *impresa extra-UE*, +*forfettario*) determina i controlli e i valori proposti: codice destinatario SDI, split payment, partita IVA estera, +paese della sede. ## Radar dei clienti @@ -35,55 +38,68 @@ i controlli e i valori proposti: codice destinatario SDI, split payment, bollo, ![012 · Clienti · radar](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/012-clienti-radar.png) *Mockup 012 — lo stesso radar con il menu espanso (anteprima ridotta).* -Il radar elenca le anagrafiche con le colonne **Codice**, **Ragione sociale**, **P.IVA / C.F.**, **Città**, -**Pagamento**, **Listino**, **Agente**, **Fatturato** dell'anno, **Scaduto** (in rosso se presente) e **Stato**. Lo -stato è un badge: *Attivo*, *Disabilitato*, *PA · split*, *UE*, *Extra-UE*, *Privato*, *Fido superato*. +![Khaemhat 0.4.0 · radar dei clienti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/anagrafiche-radar.png) +*Khaemhat 0.4.0 — il radar dei clienti di esempio con i filtri Soggetto, Agente e Stato e lo stato di ogni anagrafica (impresa UE, PA con split payment, privato, bloccato, anche fornitore). Fatturato e scaduto arrivano con vendite e scadenzario.* -- Filtri: ricerca libera, **Tipo**, **Agente**, **Stato**, più filtri aggiunti come chip (ad esempio *Scaduto > 0*, - *Provincia: CN, TO, AT*). -- Il piede mostra i totali della selezione (ad esempio *1.284 clienti · 12 selezionati · fatturato visibile*). -- Tasti: `F9` radar, `Invio` apri, `Spazio` seleziona. Con più righe selezionate si possono usare le azioni - multiple (stampa, e-mail, esporta, **Disabilita**). +Il radar elenca le anagrafiche con le colonne **Codice**, **Ragione sociale**, **P.IVA / C.F.**, **Città** (con la +provincia), **Pagamento**, **Listino** (solo clienti), **Agente** e **Stato**; nei *Contatti* al posto di pagamento e +listino c'è il **Tipo** (prospect o lead). Lo stato è un badge: *Attivo*, *Disattivato*, *Bloccato*, *PA · split*, +*Privato*, *Impresa UE*, *Impresa extra-UE*, *Anche fornitore* / *Anche cliente*. Le colonne **Fatturato** e +**Scaduto** del mockup arrivano con le vendite (M5) e lo scadenzario (M9). + +- Ricerca libera su codice, nome, partita IVA, codice fiscale e città. +- Filtri rapidi: **Tipo** (solo contatti), **Soggetto**, **Agente**, **Stato**; all'apertura sono mostrate solo le + anagrafiche attive. +- Tasti: `F9` radar, `Invio` o doppio clic apre la scheda, `Spazio` seleziona. Con più righe selezionate si usano + **Disattiva** e **Riattiva**; l'esportazione CSV/XLSX è quella di tutti i radar. ## La scheda anagrafica ![014 · Cliente · scheda anagrafica a gruppi](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/014-cliente-scheda.png) *Mockup 014 — scheda cliente: azioni Scheda 360°, Nuovo documento, VIES, Attività CRM; intestazione con identità, condizioni e fatturato; scheda Dati principali a gruppi (anteprima ridotta).* -**Toolbar**: comandi standard a icone (vedi [Interfaccia e scorciatoie](Interfaccia-e-scorciatoie)) e le azioni -contestuali **Scheda 360°** (visione completa: documenti, partite, attività CRM), **Nuovo documento**, **VIES** -(verifica della partita IVA comunitaria), **Attività CRM**. +![Khaemhat 0.4.0 · scheda cliente](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/anagrafiche-scheda.png) +*Khaemhat 0.4.0 — la scheda di un cliente di esempio: intestazione con condizioni e agente, schede con i contatori e gruppi Identità, Sede legale, Recapiti, Classificazione e consensi.* -**Intestazione** in tre blocchi: a sinistra tipo (*Cliente*), codice e nome, stato (*Attivo*), uso del fido, data -di inizio rapporto, agente; al centro ragione sociale con P.IVA, indirizzo, contatti e i chip delle condizioni -(pagamento, listino e sconto, codice SDI, dichiarazione d'intento, scaduto); a destra il **fatturato** dell'anno con -anno precedente, aperto e fido. +**Toolbar**: comandi standard a icone (vedi [Interfaccia e scorciatoie](Interfaccia-e-scorciatoie)) e le azioni +contestuali **Verifica VIES** (partita IVA comunitaria) e, per prospect, lead e fornitori, **Converti in cliente**; +nel menu `…` **Disattiva** o **Riattiva**. *Scheda 360°*, *Nuovo documento* e *Attività CRM* arrivano con vendite e +CRM. + +**Intestazione**: tipo, codice e nome, stato, data di inizio rapporto e agente; i chip delle condizioni (pagamento, +listino, agente, esito VIES, split payment). Il blocco del **fatturato** arriva con le vendite (M5). **Schede**: | Scheda | Contenuto | |---|---| -| **Dati principali** | gruppi *Identità*, *Sede legale*, *Classificazione e note* | -| **Indirizzi** | destinazioni diverse (cantieri, sedi di consegna, indirizzo di fatturazione) | -| **Contatti** | persone di riferimento con ruolo, telefono, e-mail | -| **Condizioni commerciali** | condizioni di vendita (clienti) o di acquisto (fornitori) | -| **Fiscale e SDI** | fatturazione elettronica, regime IVA, ritenute, dichiarazione d'intento, identificativi | -| **Banche** | conti correnti della controparte (IBAN) | -| **Articoli e codici** | codici con cui la controparte identifica i tuoi articoli | +| **Dati principali** | gruppi *Identità*, *Dati di nascita* (privati), *Sede legale*, *Recapiti*, *Classificazione e consensi* | +| **Indirizzi** | destinazioni diverse (destinazione merce, fatturazione, cantiere o sede operativa), una predefinita per tipo | +| **Contatti** | persone di riferimento con ruolo, telefono, cellulare, e-mail; un contatto principale | +| **Condizioni** | condizioni di vendita (clienti), di acquisto (fornitori, e clienti che sono anche fornitori), conti contabili | +| **Fiscale e SDI** | fatturazione elettronica, regime IVA, ritenute e casse, dichiarazione d'intento, identificativi | +| **Banche** | conti correnti della controparte (IBAN), uno predefinito | +| **Articoli e codici** | i codici con cui il cliente o il fornitore identifica i tuoi articoli: codice, articolo (ricerca F4), descrizione; nei documenti di quell'anagrafica la ricerca degli articoli trova anche questi codici (vedi [Articoli e listini](Articoli-e-listini)) | | **Note e allegati** | note libere e file allegati all'anagrafica | -| **CRM** | lead, opportunità e attività collegate (con modulo CRM) | | **Storico** | modifiche registrate: chi, quando, cosa | +Una scheda con errori mostra il numero degli errori nell'etichetta; le liste mostrano quante righe contengono. La +scheda *CRM* arriva con il modulo CRM. Nella scheda *Articoli e codici* lo stesso codice non si ripete per la stessa +anagrafica. + ### Dati principali | Gruppo | Campi | |---|---| -| **Identità** | Codice (automatico), Tipo, Tipo soggetto, **Ragione sociale** *, Denominazione fiscale, **Partita IVA** *, Codice fiscale, REA, Categoria | -| **Sede legale** | Indirizzo, N., CAP, Comune, Provincia, Paese, Telefono, E-mail, PEC, Sito | -| **Classificazione e note** | Agente, Lingua, Valuta, Attivo, Privacy accettata, Marketing, Note | +| **Identità** | Codice (automatico), Codice precedente, Tipo, Tipo soggetto, **Ragione sociale** *, Denominazione per i documenti, **Partita IVA** *, Codice fiscale, REA, Categoria | +| **Dati di nascita** | Data, Sesso, Comune di nascita (codice catastale) | +| **Sede legale** | Indirizzo, Civico, CAP, Comune, Provincia, Paese | +| **Recapiti** | Telefono, Cellulare, E-mail, PEC, Sito web | +| **Classificazione e consensi** | Agente, Lingua, Valuta, In anagrafica dal, Informativa privacy accettata, Consenso al marketing | -Per i privati si inseriscono nome e cognome al posto della ragione sociale. Digitando il **CAP** Khaemhat propone -comune, provincia e regione; il **codice fiscale** di una persona fisica può essere calcolato dai dati anagrafici. +Per i privati si inseriscono cognome e nome al posto della ragione sociale. Digitando il **CAP** Khaemhat propone +comune e provincia (se il CAP è di più comuni li elenca e si sceglie); digitando il comune propone il CAP. Il +**codice fiscale** di un privato si calcola con il pulsante accanto al campo da cognome, nome e dati di nascita. ### Fiscale e SDI @@ -93,7 +109,8 @@ comune, provincia e regione; il **codice fiscale** di una persona fisica può es | Gruppo | Campi | |---|---| | **Fatturazione elettronica** | **Codice destinatario** *, PEC destinatario, tipo destinatario, formato (FPR12 privati / FPA12 PA), riferimento amministrazione, *Allega PDF di cortesia*, *Invia copia via e-mail all'emissione* | -| **Regime IVA e ritenute** | *Split payment* (art. 17-ter), *Reverse charge* predefinito, codice IVA predefinito, esigibilità, *Soggetto a ritenuta*, cassa previdenza, bollo (a carico del cliente o dell'azienda), regime | +| **Regime IVA** | *Scissione dei pagamenti* (art. 17-ter), *Inversione contabile*, codice IVA abituale, esigibilità (I, D, S), bollo a carico del cliente | +| **Ritenute e casse** | *Ritenuta d'acconto* con aliquota e causale, cassa previdenziale con aliquota, *ENASARCO* | | **Dichiarazione d'intento** (esportatore abituale) | Attiva, Numero, Data, Protocollo AdE, Codice IVA (non imponibile art. 8 c.1 lett. c, natura N3.5), **Plafond**, **Utilizzato**, **Residuo**, Validità | | **Identificativi** | GLN, EORI, nostro codice presso il cliente | @@ -101,21 +118,22 @@ comune, provincia e regione; il **codice fiscale** di una persona fisica può es | Controparte | Valore | |---|---| -| Azienda italiana (B2B) | 7 caratteri, comunicati dal cliente (in alternativa la PEC) | +| Azienda italiana (B2B) | 7 caratteri, comunicati dal cliente; con la sola PEC si usa `0000000` (proposto) | | Pubblica amministrazione | **codice IPA** dell'ufficio, 6 caratteri | -| Estero (UE ed extra-UE) | `XXXXXXX` | -| Privato | `0000000` | +| Estero (UE ed extra-UE) | `XXXXXXX` (proposto se vuoto) | +| Privato | `0000000` (proposto se vuoto) | **Dichiarazione d'intento**: quando il cliente è esportatore abituale, le fatture usano il codice IVA non imponibile collegato e riportano numero e protocollo della dichiarazione; l'utilizzato si aggiorna con le fatture e il residuo avvisa quando il plafond sta per esaurirsi (il mockup mostra un avviso all'80% e un blocco al 100%; le -soglie definitive saranno fissate in sviluppo). Il registro completo delle dichiarazioni ricevute ed emesse è nel +soglie si fissano con la fatturazione, M5). Una dichiarazione attiva richiede numero e plafond. Il registro completo delle dichiarazioni ricevute ed emesse è nel modulo Fatturazione elettronica (vedi [Fatturazione elettronica](Fatturazione-elettronica)). ### Condizioni di vendita (clienti) -Listino, sconti, pagamento, banca d'appoggio per le RiBa, agente, vettore, porto, deposito, **fido** e **blocco**, -raggruppamento dei DDT in fattura differita, giorno di fatturazione, invio dei documenti per e-mail o PEC. Queste +Listino, due sconti, pagamento, nostra banca d'appoggio per le RiBa, vettore, porto, deposito, **fido** e **ordini +bloccati**, raggruppamento dei DDT in fattura differita, giorno di fatturazione, invio dei documenti per e-mail o PEC +con l'indirizzo dedicato. Queste condizioni vengono proposte automaticamente nei documenti del cliente (vedi [Vendite](Vendite)). Il **fido** è l'esposizione massima ammessa: quando viene superato, o se il cliente ha scaduto, gli ordini @@ -128,13 +146,12 @@ segnalano il blocco, superabile solo da chi ha il permesso di forzarlo. | Gruppo | Campi | |---|---| -| **Condizioni di acquisto** | Pagamento, Valuta, **Lead time** (giorni), **Minimo d'ordine**, Sconto %, Porto, Registro IVA acquisti, Conto di costo predefinito | -| **Ritenute e contributi** | *Professionista (ritenuta d'acconto)*, aliquota ritenuta, causale, cassa previdenza, *Agente ENASARCO*, *Regime forfettario* (niente IVA, bollo), *Reverse charge* (es. subappalto edile) | -| **Banca e contatti** | IBAN, BIC, referente, e-mail per gli ordini | +| **Condizioni di acquisto** | Pagamento, **Tempo di consegna** (giorni), **Ordine minimo**, Sconto %, Porto, Registro IVA, Conto di costo, E-mail per gli ordini | +| **Ritenute e casse** (scheda *Fiscale e SDI*) | *Ritenuta d'acconto* con aliquota e causale, cassa previdenziale, *ENASARCO*; il tipo soggetto *Forfettario* per chi non applica l'IVA | +| **Banche** e **Contatti** | IBAN, BIC, banca, ABI e CAB; referenti | -L'intestazione del fornitore mostra il totale **acquisti** dell'anno, l'aperto, lo scaduto e gli ordini aperti; tra -le schede *Articoli forniti* elenca gli articoli che il fornitore ti vende. Il lead time viene usato per calcolare -le date di consegna previste negli ordini fornitore. +Il tempo di consegna servirà a calcolare le date previste negli ordini fornitore. Il totale **acquisti**, l'aperto, +lo scaduto e gli *Articoli forniti* del mockup arrivano con acquisti e articoli. ## Come si usa @@ -142,41 +159,54 @@ le date di consegna previste negli ordini fornitore. 1. **Anagrafiche → Clienti**, premi **Nuovo cliente** (o `Ctrl+N`). 2. Scegli il **tipo soggetto**. Il codice viene assegnato automaticamente al salvataggio (vedi più sotto). -3. Inserisci ragione sociale e partita IVA: al salvataggio Khaemhat controlla la partita IVA e, se è comunitaria, +3. Inserisci ragione sociale e partita IVA: al salvataggio Khaemhat controlla la partita IVA e, per un'impresa UE, la verifica sul servizio **VIES** (l'esito resta salvato con la data). 4. Compila la sede legale partendo dal CAP. 5. In **Fiscale e SDI** inserisci il codice destinatario o la PEC. -6. In **Condizioni commerciali** imposta pagamento, listino, agente e fido. -7. **Salva** (`Ctrl+S`). +6. In **Condizioni** imposta pagamento, listino e fido; l'agente è nei dati principali. +7. **Salva** (`Ctrl+S`). Gli errori portano alla scheda del primo campo da correggere; gli **avvisi** (ad esempio + una partita IVA già usata da un'altra anagrafica, che va bene per filiali e sedi distinte) non bloccano e compaiono + in un messaggio dopo il salvataggio. + +Un lead si crea da **Contatti → Nuovo lead**, un prospect da **Contatti → Nuovo prospect**. ### Convertire un lead o un prospect in cliente -Dalla scheda del lead o del prospect usa l'azione di conversione: il soggetto diventa **cliente**, riceve il codice -cliente secondo la maschera automatica e mantiene la propria storia (attività, opportunità). Con il modulo CRM la -conversione si avvia anche dalla maschera dei lead (vedi [CRM](CRM)). +Dalla scheda del lead o del prospect usa **Converti in cliente**: il soggetto diventa **cliente**, riceve il codice +cliente secondo la maschera automatica e conserva il vecchio come **codice precedente** (si trova ancora con la +ricerca), insieme a storico e allegati. Con il modulo CRM la conversione si avvierà anche dalla maschera dei lead +(vedi [CRM](CRM)). + +Su un **fornitore** la stessa azione lo rende anche cliente: il codice non cambia e l'anagrafica compare in entrambi +gli elenchi. ### Disabilitare invece di cancellare -Un'anagrafica che compare in almeno un documento **non si cancella**: si **disabilita** (azione **Disabilita** nel -radar o nella scheda). Un'anagrafica disabilitata non viene più proposta nei nuovi documenti né nelle ricerche -predefinite, ma resta consultabile con i suoi documenti. Si può cancellare solo un'anagrafica mai usata. +Un'anagrafica che compare in almeno un documento **non si cancella**: si **disattiva** (azione **Disattiva** nel +radar o nel menu della scheda). Un'anagrafica disattivata non viene più proposta nei nuovi documenti né nelle +ricerche predefinite, ma resta consultabile con i suoi documenti. Se si prova a eliminare un'anagrafica usata, +Khaemhat la disattiva e lo dice. Si cancella davvero solo un'anagrafica mai usata. ## Validazioni | Dato | Controllo | |---|---| -| **Partita IVA italiana** | 11 cifre con cifra di controllo | +| **Ragione sociale** | obbligatoria (per i privati cognome e nome) | +| **Partita IVA italiana** | 11 cifre con cifra di controllo; obbligatoria per un'impresa; un doppione è un avviso | | **Partita IVA UE** | verifica sul servizio VIES della Commissione europea; esito e data salvati | -| **Codice fiscale** | 16 caratteri con carattere di controllo (11 cifre per le società); calcolabile dai dati anagrafici | +| **Codice fiscale** | 16 caratteri con carattere di controllo (11 cifre per le società); per un privato senza codice fiscale un avviso | +| **Pubblica amministrazione** | serve il codice fiscale o la partita IVA | +| **Paese** | nella tabella dei paesi; un'impresa UE ha sede in un altro paese dell'Unione, impresa italiana, privato, PA e forfettario nel paese dell'azienda | | **IBAN** | struttura e controllo modulo 97 | | **Codice destinatario** | 7 caratteri; 6 per la PA (codice IPA); `XXXXXXX` estero; `0000000` privato | | **E-mail / PEC** | formato dell'indirizzo | +| **Codice** | unico fra tutte le anagrafiche | ## Codici automatici -Il codice di clienti, fornitori e lead è assegnato automaticamente secondo le maschere impostate in +Il codice di clienti, fornitori, prospect e lead è assegnato automaticamente secondo le maschere impostate in *Tabelle azienda → Preferenze e codici automatici* (vedi [Tabelle azienda](Tabelle-azienda)): `C{seq:000000}` per i -clienti, `F{seq:000000}` per i fornitori, `L{anno}-{seq:0000}` per i lead. La maschera mostra l'anteprima del +clienti, `F{seq:000000}` per i fornitori, `L{anno}-{seq:0000}` per prospect e lead. La maschera mostra l'anteprima del prossimo codice; un'impostazione decide se è ammesso scrivere un **codice manuale**. Il progressivo è assegnato in modo atomico: due utenti che salvano insieme non ottengono mai lo stesso codice. @@ -184,25 +214,31 @@ modo atomico: due utenti che salvano insieme non ottengono mai lo stesso codice. | Quando | Khaemhat propone | |---|---| -| inserisci il CAP | comune, provincia e regione | -| inserisci i dati anagrafici di una persona | il codice fiscale | +| inserisci il CAP | comune e provincia (scelta fra più comuni) | +| inserisci il comune | CAP e provincia | +| premi *Calcola* accanto al codice fiscale di un privato | il codice fiscale | | salvi una P.IVA UE | la verifica VIES | -| inserisci un IBAN | banca e BIC (tabella ABI) | -| crei un documento per il cliente | destinazione, listino, pagamento, agente | +| inserisci un IBAN | ABI, CAB e banca (dalla tabella delle banche, quando caricata) | +| lasci vuoto il codice destinatario di un privato o di un estero | `0000000` o `XXXXXXX` | +| crei un documento per il cliente | destinazione, listino, pagamento, agente (con le vendite, M5) | Le singole compilazioni si attivano o disattivano in *Tabelle azienda → Preferenze e codici automatici*. ## Permessi e licenza -Le anagrafiche fanno parte del modulo **CORE**. Il flag utente *vede solo i propri clienti* limita un agente ai -clienti a lui assegnati. Le schede *CRM* e *Scheda 360°* mostrano i dati CRM solo con il modulo **CRM** attivo; il +Le anagrafiche fanno parte del modulo **CORE**: `parties.party.read` per consultare, `parties.party.write` per +inserire, modificare, disattivare e convertire, `parties.party.delete` per eliminare. Il flag utente *vede solo i +propri clienti*, che limiterà un agente ai clienti assegnati, non è ancora attivo. Le schede *CRM* e *Scheda 360°* mostrano i dati CRM solo con il modulo **CRM** attivo; il registro delle dichiarazioni d'intento richiede **EINV**. Ogni modifica è registrata nello **Storico**. ## Domande frequenti - **Non riesco a cancellare un cliente.** Ha documenti collegati: disabilitalo. - **La verifica VIES non risponde.** Il servizio europeo può essere temporaneamente non disponibile: salva - comunque e ripeti la verifica con l'azione **VIES** più tardi. + comunque e ripeti la verifica con l'azione **Verifica VIES** più tardi. +- **Ho convertito un prospect e il vecchio codice è sparito.** È nel campo *Codice precedente* e la ricerca lo trova. +- **Un fornitore compare anche fra i clienti.** È un cliente con *È anche fornitore*: un solo soggetto, un solo + codice. - **Un cliente privato non ha codice destinatario.** È corretto: si usa `0000000` e la fattura resta disponibile nell'area riservata del cliente sul sito dell'Agenzia delle Entrate; consegnagli comunque una copia di cortesia. diff --git a/docs/wiki/Articoli-e-listini.md b/docs/wiki/Articoli-e-listini.md index f5312bf..07585b6 100644 --- a/docs/wiki/Articoli-e-listini.md +++ b/docs/wiki/Articoli-e-listini.md @@ -1,153 +1,212 @@ # Articoli e listini -> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M4) -> **Modulo di licenza:** CORE · **Permessi principali:** famiglia `items.*` (es. `items.cost.read` per vedere i costi) · **Specifica:** SPEC §11.2, §11.3 (prezzi), §11.6 +> **Stato:** completa · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (milestone M4; giacenze e costi dai movimenti con il magazzino, M6) +> **Modulo di licenza:** CORE · **Permessi principali:** `items.item.read` (consultare), `items.item.write` (inserire, modificare, disattivare, prezzi), `items.item.delete` (eliminare), `items.cost.read` (vedere costi e margini) · **Specifica:** SPEC §11.2, §11.3 (prezzi), §14 · **Decisioni:** ADR 0030 -L'**articolo** descrive ciò che l'azienda vende o compra: merci, servizi, spese, righe di solo testo e cespiti. -Nella scheda articolo stanno codici, unità di misura, IVA, conti contabili, prezzi e costi, i parametri di -**riordino** e le **giacenze** per deposito in tempo reale. I **listini** raccolgono i prezzi di vendita per gruppi di -clienti e si aggiornano anche in modo massivo. +L'**articolo** descrive ciò che l'azienda vende o compra: merci, servizi, spese, righe descrittive e cespiti. Nella +scheda articolo stanno codici, unità di misura, IVA, conti, prezzi e costi e i parametri di **riordino**. I +**listini** raccolgono i prezzi di vendita per gruppi di clienti, con una data di validità, e si aggiornano anche in +modo massivo. ## Dove si trova -Menu **Anagrafiche → Articoli** e **Anagrafiche → Listini**; le categorie articolo sono in **Anagrafiche → -Categorie**. +Menu **Anagrafiche → Articoli** e **Anagrafiche → Listini**. Le **categorie articolo**, le **intestazioni dei +listini** e le **unità di misura** sono tabelle dell'azienda (vedi [Tabelle azienda](Tabelle-azienda)). + +## L'elenco degli articoli + +L'elenco è una griglia con ricerca per codice, descrizione, codice a barre (anche alternativo) e marca, e le colonne +codice, descrizione, tipo, categoria, UM, **prezzo base**, **costo medio** (solo con il permesso di vedere i costi), +magazzino e stato. I filtri rapidi scelgono tipo, categoria, articoli a magazzino e **attivi / disattivati**. Dalla +toolbar si disattivano e riattivano gli articoli selezionati e si apre la griglia dei listini. + +![Khaemhat 0.4.0 · radar degli articoli](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/articoli-radar.png) +*Khaemhat 0.4.0 — il radar dei 120 articoli di esempio con categoria, UM, marca, tipo, costo medio e prezzo base.* ## La scheda articolo ![017 · Articolo · scheda con prezzi, riordino e giacenze](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/017-articolo-scheda.png) -*Mockup 017 — scheda articolo: azioni Movimenti, Etichette, Proposta riordino; intestazione con disponibilità e costo medio; gruppi Identità, Codici UM e fisco, Prezzi e costi, Riordino; giacenze per deposito (anteprima ridotta).* +*Mockup 017 — scheda articolo: intestazione con prezzo e costo medio; gruppi Identità, Codici UM e fisco, Prezzi e costi, Riordino; giacenze per deposito (anteprima ridotta).* -**Toolbar**: comandi standard e le azioni contestuali **Movimenti** (movimenti di magazzino dell'articolo), -**Etichette** (stampa etichette), **Proposta riordino**. +![Khaemhat 0.4.0 · scheda articolo](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/articoli-scheda.png) +*Khaemhat 0.4.0 — la scheda di un articolo di esempio con prezzo base, costo medio e margine nell'intestazione e le schede UM, codici alternativi, listini, fornitori e sostitutivi.* -**Intestazione**: a sinistra codice, avvisi (ad esempio *Sotto punto di riordino*), EAN e categoria; al centro -descrizione, UM, marca, peso, nomenclatura NC8, aliquota IVA e chip con prezzi di listino, disponibilità -(*Disp. · Imp. · Ord.*), fornitore abituale, scorta minima e punto di riordino; a destra il **costo medio** con -ultimo costo, costo standard e margine. +**Intestazione**: codice, descrizione, tipo e categoria; a destra il **prezzo base in vigore oggi** con costo medio, +ultimo costo, costo standard e **margine** (i costi solo con il permesso `items.cost.read`). -**Schede**: *Dati principali*, *UM alternative*, *Codici alternativi*, *Listini*, *Fornitori*, *Sostitutivi*, -*Movimenti*, *Immagini e allegati*. +**Schede**: + +| Scheda | Contenuto | +|---|---| +| **Dati principali** | i gruppi *Identità*, *Unità, codici e IVA*, *Prezzi e costi*, *Magazzino e riordino*, *Contabilità* | +| **UM alternative** | unità diverse da quella base con il **fattore** (una scatola da 10 pezzi ha fattore 10) e l'EAN della confezione | +| **Codici alternativi** | codici a barre dei produttori e codici dei vecchi gestionali: la ricerca li trova esattamente | +| **Listini** | i prezzi in vigore oggi in ogni listino, i prezzi di listino scritti con la loro data e i **prezzi netti dei clienti** | +| **Fornitori** | chi fornisce l'articolo, con codice e prezzo del fornitore, giorni di consegna, minimo d'ordine e il **fornitore abituale** | +| **Sostitutivi** | articoli equivalenti da proporre quando quello richiesto manca | +| **Note e allegati** | note libere e file (immagini, schede tecniche) | +| **Storico** | modifiche registrate: chi, quando, cosa | + +Una scheda con errori mostra il numero degli errori nell'etichetta, come nelle [Anagrafiche](Anagrafiche). ### Campi principali | Gruppo | Campi | |---|---| | **Identità** | Codice (automatico), Tipo, Categoria, **Descrizione** *, Descrizione estesa, Marca, Produttore | -| **Codici, UM e fisco** | UM base, EAN (con verifica della cifra di controllo), NC8 (Intrastat), IVA vendita, IVA acquisto, Peso netto, Conto ricavo, Conto costo | -| **Prezzi e costi** | prezzi dei listini principali (es. base, pubblico IVA inclusa, rivenditori), Costo standard, Ultimo costo, Medio ponderato (gli ultimi due calcolati) | -| **Riordino** | Gestito a magazzino, Deposito, **Scorta minima**, **Punto di riordino**, **Lotto di riordino**, Fornitore abituale | -| **Giacenze per deposito (tempo reale)** | per ogni deposito: Giacenza, Impegnato, Ordinato, Disponibile, Valore, con riga di totale | +| **Unità, codici e IVA** | UM base, codice a barre (EAN, con verifica della cifra di controllo), nomenclatura **NC8** (otto cifre, per Intrastat), IVA vendita, IVA acquisto, Peso netto e lordo | +| **Prezzi e costi** | Prezzo dell'articolo (vale solo se nessun listino ha un prezzo), Costo standard, Ultimo costo, Costo medio | +| **Magazzino e riordino** | Gestito a magazzino, Deposito, **Scorta minima**, **Punto di riordino**, **Lotto di riordino** | +| **Contabilità** | Conto ricavo, Conto costo | ### Tipi di articolo | Tipo | Uso | Magazzino | |---|---|---| | **Merce** | beni venduti o acquistati | sì, se *Gestito a magazzino* | -| **Servizio** | prestazioni (es. installazione, assistenza a ore) | no | +| **Servizio** | prestazioni (installazione, assistenza a ore) | no | | **Spesa** | spese accessorie in fattura (trasporto, incasso) | no | -| **Testo** | righe descrittive ricorrenti | no | -| **Cespite** | beni strumentali (collegati al registro cespiti con il modulo Cespiti) | da definire in sviluppo | +| **Descrittivo** | righe di solo testo ricorrenti | no | +| **Cespite** | beni strumentali (registro cespiti con il modulo Cespiti) | no | -### Unità di misura e codici +Solo le merci possono essere gestite a magazzino: per gli altri tipi l'opzione è spenta e Khaemhat la corregge al +salvataggio. -- **UM base** (ad esempio `PZ`, `MT`, `H`, `NR`) dalla tabella delle unità di misura, con il codice usato nell'XML - SDI; le **UM alternative** hanno un fattore di conversione (ad esempio confezione da 10 pezzi). -- **Codici alternativi**: altri codici a barre (EAN) e codici interni; nella ricerca F4 un articolo si trova anche - per EAN e per il **codice che il cliente usa** per quell'articolo (impostato nella scheda *Articoli e codici* del - cliente, vedi [Anagrafiche](Anagrafiche)). -- **Fornitori**: chi fornisce l'articolo, con codice e prezzo del fornitore; uno è il **fornitore abituale** usato - dalla proposta di riordino. -- **Sostitutivi**: articoli equivalenti proposti quando quello richiesto non è disponibile. +### Costi -### Prezzi e costi +- **Costo standard**: valore scritto a mano. +- **Ultimo costo** e **costo medio**: li aggiornano i carichi di magazzino (DDT di carico, fatture di acquisto) che + arrivano con il magazzino (M6); fino ad allora sono valorizzati solo nei dati di esempio. Il costo medio è il + criterio di valorizzazione del magazzino (vedi [Magazzino](Magazzino)). +- Il **margine** è calcolato sul prezzo: (prezzo - costo) / prezzo. +- Chi non ha il permesso `items.cost.read` non vede i costi (né nella scheda né nell'elenco né nei listini) e, + quando salva, i costi in archivio restano quelli di prima. -- I **prezzi di vendita** stanno nei listini (vedi sotto); la scheda mostra quelli dei listini principali. -- **Costo standard**: valore impostato a mano. -- **Ultimo costo** e **costo medio ponderato**: aggiornati dai carichi di magazzino (DDT di carico, fatture di - acquisto). Il costo medio è il criterio di valorizzazione del magazzino (vedi [Magazzino](Magazzino)). -- Il **margine** è mostrato solo a chi ha il permesso di vedere costi e margini. +### Giacenze e riordino -### Riordino e giacenze +Con **Gestito a magazzino** l'articolo parteciperà a movimenti, giacenze per deposito (*Giacenza, Impegnato, +Ordinato, Disponibile, Valore*) e **proposta di riordino**: questi arrivano con il magazzino (M6). Scorta minima, +punto e lotto di riordino si possono già compilare. -Con **Gestito a magazzino** attivo l'articolo partecipa ai movimenti, alle giacenze e alla **proposta di riordino**: -quando la disponibilità scende sotto il **punto di riordino** l'articolo viene proposto per un ordine al fornitore -abituale, in multipli del **lotto**. La griglia *Giacenze per deposito* mostra: +### Controlli al salvataggio -| Colonna | Significato | -|---|---| -| **Giacenza** | quantità fisicamente presente | -| **Impegnato** | quantità riservata da ordini clienti confermati | -| **Ordinato** | quantità in arrivo da ordini fornitore | -| **Disponibile** | giacenza - impegnato | -| **Valore** | giacenza x costo medio | +- Descrizione obbligatoria; categoria obbligatoria se la maschera del codice la usa. +- Codice a barre con cifra di controllo corretta (EAN-8, EAN-13, UPC). Un codice a barre già usato da un altro + articolo blocca il salvataggio se nelle preferenze è attivo *Blocca duplicati per EAN* (impostazione di + partenza), altrimenti è solo un avviso. +- NC8 di otto cifre; quantità, pesi, prezzi e costi non negativi; fattori delle UM maggiori di zero. +- Nelle schede di dettaglio: la stessa UM, lo stesso codice alternativo, lo stesso fornitore o sostitutivo non si + ripetono; un articolo non è sostitutivo di sé stesso; un prezzo netto vale per un cliente. + +### Disattivare ed eliminare + +**Disattiva** toglie l'articolo dalle ricerche dei documenti nuovi senza perdere nulla. **Elimina** cancella +l'articolo solo se nessun altro dato lo usa (ad esempio se è sostitutivo di un altro articolo, e da M5 se compare +nei documenti); altrimenti Khaemhat lo **disattiva** al posto dell'eliminazione e lo dice. + +## Codici articolo + +Il codice segue la maschera `{categoria}-{seq:0000}` con progressivo **per categoria** (categoria `VALV` → +`VALV-0013`). Maschera, codice manuale e blocco dei duplicati per EAN si impostano in *Tabelle azienda → +Preferenze e codici automatici* (vedi [Tabelle azienda](Tabelle-azienda)). Il codice si assegna al primo +salvataggio. + +I **codici che un cliente o un fornitore usa** per i tuoi articoli si scrivono nella scheda *Articoli e codici* +dell'anagrafica (vedi [Anagrafiche](Anagrafiche)): nei documenti di quel cliente la ricerca F4 trova l'articolo +anche con il suo codice. ## Listini ![018 · Listini](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/png/018-listini.png) -*Mockup 018 — griglia listino x articolo: costo medio, LIST01 Base, LIST02 Pubblico, LIST03 Rivenditori, prezzi netti di un cliente e margine; cella modificata evidenziata e scheda con pallino di modifica.* +*Mockup 018 — griglia listino x articolo: costo medio, listini base, pubblico e rivenditori, prezzi netti di un cliente e margine; cella modificata evidenziata.* -La maschera **Listini** è una **griglia articoli x listini**: per ogni articolo (codice, descrizione, UM, costo -medio) una colonna per ciascun listino, più eventuali colonne di **prezzi netti per cliente** e il **margine**. +![Khaemhat 0.4.0 · griglia dei listini](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/listini-griglia.png) +*Khaemhat 0.4.0 — la griglia articoli x listini sui 120 articoli di esempio: listino base, Pubblico e Rivenditori derivati (in corsivo i prezzi calcolati), costo medio e margine.* -- Filtri: ricerca, **Categoria**, **Listino**, **Validità** (la data a cui leggere i prezzi, ad esempio *Oggi*), - chip *Mostra margine*. -- I prezzi si modificano direttamente nelle celle; le modifiche restano evidenziate e la scheda mostra il pallino - arancione finché non salvi. Il piede riporta il numero di articoli, le modifiche non salvate e la data di validità - dei nuovi prezzi. -- Azioni: **Aggiornamento massivo**, **Nuovo listino**; icone per salvare, annullare, stampare, esportare, - applicare una variazione percentuale, ripristinare, duplicare. +Un **listino** ha codice, descrizione, valuta, *IVA inclusa*, validità e, se è derivato, il listino da cui +**deriva**, il **ricarico %** (anche negativo, come uno sconto) e il **passo di arrotondamento**. Le intestazioni si +gestiscono nella tabella *Listini* dell'azienda; uno solo è il **listino base** (in partenza `BASE`). -Ogni listino ha una **validità** (i prezzi nuovi valgono da una data, i vecchi restano per i documenti precedenti), -può essere **derivato** da un altro listino (ad esempio pubblico = base + 40%) e ha le proprie regole di -**arrotondamento**. +### La griglia dei listini + +**Anagrafiche → Listini** è una griglia **articoli x listini**: per ogni articolo codice, descrizione, UM, costo +medio (con il permesso) e una colonna per ciascun listino attivo. + +- In alto: ricerca, **Listino** (tutti o uno solo), **Validità** (la data a cui leggere e scrivere i prezzi, oggi + in partenza), **Prezzi netti di** un cliente (aggiunge la colonna dei suoi prezzi netti) e **Mostra margine**. +- I prezzi si scrivono nelle celle (vuoto toglie il prezzo a quella data). Le celle cambiate restano **evidenziate + da salvare**; il piede riporta articoli, modifiche non salvate e data di validità dei nuovi prezzi. **Salva** + scrive tutto insieme, **Annulla modifiche** torna ai prezzi salvati. +- Le celle in *corsivo* sono **calcolate** da un listino derivato che non ha un prezzo proprio per l'articolo: il + suggerimento dice da quale listino. Scrivere un prezzo nella cella lo rende proprio di quel listino. +- Con modifiche non salvate non si cambiano validità o cliente: prima salva o annulla. +- **Nuovo listino** apre la tabella dei listini. + +### Validità dei prezzi + +Ogni prezzo vale **dalla sua data** fino al prezzo successivo dello stesso listino (o dello stesso cliente). +Scrivere un prezzo con una data nuova **aggiunge** un prezzo e lascia quello vecchio ai documenti datati prima; +scriverlo con la stessa data lo corregge. I documenti già fatti conservano sempre il prezzo di allora. + +### Listini derivati + +Un listino derivato senza un proprio prezzo per un articolo prende il prezzo del listino di partenza alla stessa +data, applica il ricarico e arrotonda al passo (al centesimo se il passo è zero). Esempio dei dati di esempio: +*Pubblico* = base + 45% arrotondato a 0,10; *Rivenditori* = base - 10%. Un prezzo scritto nel listino derivato vince +su quello calcolato. ### Aggiornamento massivo 1. Premi **Aggiornamento massivo**. -2. Scegli **che cosa** aggiornare: un listino, una categoria o le righe selezionate. -3. Scegli la **variazione**: percentuale (anche negativa) oppure a partire da un altro listino. -4. Scegli l'**arrotondamento**: a 0,10, 0,50 o 1,00, per eccesso o per difetto. -5. Indica la **data di validità** dei nuovi prezzi. -6. Controlla le righe aggiornate (restano evidenziate) e **Salva**. +2. Scegli il **listino da aggiornare** e da dove **calcolare**: i prezzi attuali dello stesso listino o un altro + listino. +3. Scrivi la **variazione %** (anche negativa). +4. Scegli l'**arrotondamento** (0,01, 0,10, 0,50, 1,00) e il **verso** (al più vicino, per eccesso, per difetto). +5. Indica la data da cui valgono i nuovi prezzi (**Valido dal**). +6. Scegli gli **articoli**: tutti, quelli di una categoria o solo i selezionati. +7. Premi **Calcola i prezzi**: le celle calcolate restano evidenziate; controllale e **Salva**. -L'aggiornamento listini è disponibile anche come procedura pianificabile (vedi [Automazioni](Automazioni)). +Il calcolo non scrive nulla finché non salvi; gli articoli il cui prezzo non cambia sono esclusi. ## Come viene scelto il prezzo in un documento -Quando inserisci un articolo in una riga di vendita, Khaemhat cerca il prezzo in quest'ordine e si ferma al primo -che trova: +Quando inserisci un articolo in una riga di vendita (da M5), Khaemhat cerca il prezzo valido alla data del documento +in quest'ordine e si ferma al primo che trova: | Ordine | Fonte | Esempio | |---|---|---| | 1 | **prezzo netto cliente-articolo** | prezzo concordato con Rossi Impianti per quella valvola | -| 2 | **listino del cliente** | il cliente usa LIST03 Rivenditori | -| 3 | **listino base** | LIST01 Base | -| 4 | **prezzo dell'articolo** | prezzo indicato nella scheda | +| 2 | **listino del documento o del cliente** | il cliente usa il listino *Rivenditori* | +| 3 | **listino base** | *Base* | +| 4 | **prezzo dell'articolo** | prezzo scritto nella scheda | -La riga ricorda **da dove viene il prezzo** (la fonte), così è sempre possibile capire perché è stato proposto -quel valore. Sul prezzo si applicano poi gli sconti del cliente e della riga (anche a cascata, come `5+2`). Se è -attiva la compilazione automatica *Ultimo prezzo praticato al cliente*, Khaemhat lo mostra come riferimento. - -## Codici automatici - -Il codice articolo segue la maschera `{categoria}-{seq:0000}` con progressivo **per categoria** (ad esempio -categoria `VALV` → `VALV-0013`); la maschera, l'eventuale codice manuale e il blocco dei **duplicati per EAN** si -impostano in *Tabelle azienda → Preferenze e codici automatici* (vedi [Tabelle azienda](Tabelle-azienda)). +La riga ricorda **da dove viene il prezzo** (la fonte). Sul prezzo di listino si propongono gli sconti del cliente a +cascata (come `10+5`); su un **prezzo netto** non si applicano sconti. ## Permessi e licenza -Articoli e listini sono nel modulo **CORE**. I costi e i margini sono visibili solo agli utenti con il permesso -`items.cost.read` (flag *vede costi e margini*). Il collegamento ai cespiti richiede il modulo **ASSET**; i conti -contabili sono usati con il modulo **ACCT**. +Articoli e listini sono nel modulo **CORE**. Per scrivere i prezzi nella griglia serve `items.item.write`; i costi +e i margini richiedono `items.cost.read` (il ruolo *Magazzino* gestisce gli articoli ma non vede i costi). Il +collegamento ai cespiti richiede il modulo **ASSET**; i conti contabili sono usati con il modulo **ACCT**. + +## Dati di esempio + +I dati di esempio (vedi [Dati di base e di esempio](Dati-di-base-e-esempio)) creano 120 articoli fittizi di un +grossista termoidraulico in dieci categorie (valvolame, raccorderia, tubi, caldaie, sanitari, consumabili, pompe, +utensili, servizi, spese), i listini *Pubblico* e *Rivenditori* derivati dal base, prezzi dell'anno precedente per +lo storico, fornitori abituali, UM alternative, codici alternativi, sostitutivi e i prezzi netti e i codici di +Rossi Impianti. I codici a barre di esempio iniziano con `200`, prefisso riservato all'uso interno. ## Domande frequenti - **Ho cambiato un prezzo di listino ma la fattura di ieri non cambia.** È corretto: i documenti conservano il - prezzo con cui sono stati fatti; la validità del listino vale per i documenti nuovi. -- **Perché il prezzo proposto non è quello del listino?** Probabilmente esiste un prezzo netto per quel cliente: - la fonte del prezzo è indicata nella riga. -- **Un articolo di servizio non compare nelle giacenze.** I servizi e le spese non sono gestiti a magazzino. + prezzo con cui sono stati fatti; i prezzi nuovi valgono dalla loro data. +- **Ho scritto un prezzo con la data sbagliata.** Imposta quella data in *Validità*, svuota la cella e salva: il + prezzo a quella data viene tolto. +- **Perché il prezzo proposto non è quello del listino?** Probabilmente esiste un prezzo netto per quel cliente: la + fonte del prezzo è indicata nella riga. +- **Non vedo il costo medio.** Serve il permesso di vedere costi e margini (`items.cost.read`). +- **Un servizio non si può mettere a magazzino.** È voluto: solo le merci vanno a magazzino. ## Pagine correlate diff --git a/docs/wiki/Changelog.md b/docs/wiki/Changelog.md index bdb114d..25d6fbc 100644 --- a/docs/wiki/Changelog.md +++ b/docs/wiki/Changelog.md @@ -1,6 +1,6 @@ # Changelog -> **Stato:** completa per 0.3.0 · **Ultima revisione:** 2026-11-11 +> **Stato:** completa per 0.4.0 · **Ultima revisione:** 2026-11-12 Le novità di ogni versione sono nel file [`CHANGELOG.md`](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/src/branch/main/CHANGELOG.md) del repository @@ -11,6 +11,7 @@ Le novità di ogni versione sono nel file | Versione | Data | Contenuto | |---|---|---| +| 0.4.0 | 2026-11-12 | M4 — Tabelle, anagrafiche, articoli: pacchetto fiscale italiano, profilo azienda, esercizi e cambi, 26 tabelle azienda con province, comuni e CAP, clienti, fornitori e contatti con controlli e VIES, articoli e listini con prezzi a validità, codici automatici, import/export guidato (anche del piano dei conti, per ora solo verifica) e dati di esempio. | | 0.3.0 | 2026-11-11 | M3 — Framework UI: la finestra di Khaemhat con menu, schede e barra di stato, la dashboard a widget, *Il mio profilo* con temi e colori, ricerca globale, aiuto in app, notifiche, componenti per maschere e liste, allegati e anteprima di stampa (provati su un documento di prova, le maschere gestionali arrivano da 0.4.0). | | 0.2.0 | 2026-11-11 | M2 — Sistema e sicurezza: avvio da variabili d'ambiente, super utente e prima azienda, accesso con password e verifica in due passaggi, utenti, ruoli e permessi, licenze e moduli con codici di prova, log per sezioni, attività programmate. | | 0.1.0 | 2026-11-11 | M1 — Strato dati: accesso ai database SQLite e PostgreSQL, migrazioni dello schema, registro delle aziende, cifratura dei dati riservati. Nessuna funzione visibile nell'interfaccia. | diff --git a/docs/wiki/Dati-di-base-e-esempio.md b/docs/wiki/Dati-di-base-e-esempio.md index dad873e..fef72f5 100644 --- a/docs/wiki/Dati-di-base-e-esempio.md +++ b/docs/wiki/Dati-di-base-e-esempio.md @@ -1,6 +1,6 @@ # Dati di base e di esempio -> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M4; dati di esempio completi in M9) +> **Stato:** completa per M4 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (dati di esempio di documenti e contabilità con i moduli, completi in M9) > **Modulo di licenza:** CORE · **Livello richiesto:** amministratore (rimozione dati di esempio: super utente) · **Specifica:** SPEC §6, §12.11, §14 ## A cosa serve @@ -21,26 +21,26 @@ alto a destra, es. *Database: khaemhat_demo*). *Mockup 089 — riepilogo di tabelle di base, dati di esempio, documenti reali e utenti demo con i pulsanti **Aggiorna tabelle di base**, **Carica dati di esempio**, **Rimuovi dati di esempio**, **Anteprima differenze**; a destra le -ultime migrazioni; sotto, i **pacchetti di dati di base** della versione `IT 2026.2` con contenuto, righe e stato +ultime migrazioni; sotto, i **pacchetti di dati di base** della versione `IT 2026.3` con contenuto, righe e stato (anteprima ridotta)* Il riepilogo mostra: | Voce | Esempio | |---|---| -| **Tabelle di base** | versione del pacchetto (`IT 2026.2`), righe, data dell'ultimo aggiornamento | +| **Tabelle di base** | versione del pacchetto (`IT 2026.3`), righe, data dell'ultimo aggiornamento | | **Dati di esempio** | *presenti* con i conteggi (clienti, fornitori, articoli, documenti, registrazioni, cespiti, lead) oppure *assenti* | | **Documenti reali** | numero di documenti non dimostrativi (0 in un'azienda demo) | | **Utenti demo** | utenti dimostrativi e relativa password | ## Le tabelle di base -Sono raccolte in **pacchetti** con una **versione** (oggi `IT 2026.2`, salvata nelle impostazioni dell'azienda). +Sono raccolte in **pacchetti** con una **versione** (oggi `IT 2026.3`, salvata nelle impostazioni dell'azienda). Il pacchetto italiano fa parte del pacchetto fiscale Italia (vedi [Fiscalità italiana](Fiscalita-italiana)). | Pacchetto | Contenuto | |---|---| -| **Paesi e comuni** | paesi ISO, province, comuni con CAP e codice catastale | +| **Paesi e comuni** | paesi ISO, province, comuni con codice catastale, codice ISTAT e CAP | | **Valute e unità di misura** | valute, unità di misura | | **Codici IVA e nature** | aliquote 22, 10, 5, 4; esenti (ESE10 N4); non imponibili (NI8 N3.1, NI41 N3.2, NI71 N3.3, NI8C N3.5); fuori campo (FC7 N2.1, altre N2.2); escluse (ESC15 N1); reverse charge (RC17 N6.x); split payment; non soggette; indetraibili 50% e 100%; forfettari | | **Modalità e condizioni di pagamento** | modalità `MP01`-`MP23`, condizioni di pagamento | @@ -56,6 +56,32 @@ Il pacchetto italiano fa parte del pacchetto fiscale Italia (vedi [Fiscalità it | **CRM** | pipeline e fasi, modelli e-mail | | **Sistema** | ruoli predefiniti, regole di automazione predefinite, attività programmate di sistema | +### Cosa c'è oggi + +Dalla versione 0.4.0 il caricamento di base contiene: paesi ISO con appartenenza all'UE, le 30 valute dei cambi BCE, +unità di misura, codici IVA e nature, modalità `MP01`-`MP23` e condizioni di pagamento con le rate, tipi documento +con codice TD, numeratori, causali di magazzino, deposito principale, porti, trasporto a cura, causali di trasporto, +aspetto dei beni, rese, categorie, listino base e l'esercizio dell'anno in corso con i suoi mesi. Le righe fiscali +vengono dal pacchetto del paese dell'azienda. + +**Province e comuni** (dalla versione `IT 2026.3`) vengono dall'elenco ISTAT dei codici dei comuni aggiornato al +26/02/2026: 110 province con sigla e regione, 7.894 comuni con codice catastale, provincia, regione e codice ISTAT. +Il **codice** di un comune è il suo codice catastale (es. `H501` per Roma), lo stesso del codice fiscale. +I **CAP** vengono dall'elenco dei codici postali di GeoNames e ci sono per 7.750 comuni: un CAP, una lista o un +intervallo come `10121-10156` per le città con più CAP. + +> Fonti: ISTAT, *Codici statistici delle unità amministrative territoriali*, e GeoNames +> ([www.geonames.org](https://www.geonames.org)), entrambi con licenza +> [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/deed.it). + +Ai comuni rinominati o nati da fusioni recenti (ad esempio Sanremo) il CAP può mancare: si completa a mano nella +tabella *Comuni* o con l'**Importa CSV** (colonne `Code` e `PostalCodes`, più CAP separati da virgola). La +compilazione dal CAP propone solo i comuni che hanno il CAP scritto. Le **banche ABI/CAB** non sono ancora incluse: banca e BIC dall'IBAN vengono da un conto +dell'azienda presso la stessa banca. Un comune soppresso per fusione resta nella tabella finché non lo disattivi. + +Le altre voci dell'elenco (piano dei conti, causali contabili, registri IVA, cespiti, codici tributo, CRM) arrivano con i +moduli che le usano. + ### Aggiorna tabelle di base Ogni nuova versione di Khaemhat può portare un pacchetto aggiornato (nuovi codici IVA, nuovi tipi documento SDI, @@ -64,8 +90,12 @@ nuovi codici tributo…). 1. Premi **Anteprima differenze** per vedere cosa cambierebbe. 2. Premi **Aggiorna tabelle di base**. -L'aggiornamento è **idempotente** (rieseguirlo non duplica nulla) e **aggiunge solo i codici mancanti senza -toccare le righe che l'azienda ha modificato**. +L'aggiornamento è **idempotente** (rieseguirlo non duplica nulla) e **aggiunge solo i codici mancanti**: una riga +già presente non viene mai modificata né cancellata, anche se l'azienda non l'ha mai toccata. Se una nuova versione +corregge un codice esistente (ad esempio un riferimento normativo), il [CHANGELOG](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/src/branch/main/CHANGELOG.md) +lo segnala e la correzione si fa nella tabella. La versione caricata è salvata nelle impostazioni dell'azienda. + +Lo stesso aggiornamento si avvia dal menu `…` di ogni tabella con **Aggiorna da tabelle base**. Le tabelle di base si caricano anche automaticamente alla creazione di un'azienda, se la variabile `KHAEMHAT_SEED_BASE` non è `false` (predefinito `true`). @@ -94,6 +124,16 @@ reale. Contiene: | Log | voci di log di esempio in tutte le sezioni | Tutte le righe dimostrative sono marcate come tali (`is_demo`), così si possono rimuovere senza toccare il resto. + +**Oggi (M4)** i dati di esempio contengono 3 agenti e **21 anagrafiche**: 12 clienti che coprono tutti i tipi +soggetto (fra cui un comune con split payment, un cliente bloccato, uno disattivato, uno che è anche fornitore e +uno con dichiarazione d'intento), 5 fornitori (professionista con ritenuta, agente ENASARCO, fornitore UE), +2 prospect e 2 lead. Partite IVA, codici fiscali e IBAN sono numeri inventati ma formalmente validi, perché passino +i controlli; non si verificano sul VIES (ADR 0029). Gli agenti di esempio non sono marcati e si rimuovono a mano. +Ci sono poi **120 articoli** in dieci categorie con i listini *Pubblico* e *Rivenditori* derivati dal base, prezzi +dell'anno precedente, fornitori abituali, UM e codici alternativi, sostitutivi e i prezzi netti e i codici di un +cliente (ADR 0030, vedi [Articoli e listini](Articoli-e-listini)). I codici a barre di esempio iniziano con `200`, +prefisso riservato all'uso interno. Il resto della tabella arriva con le milestone dei rispettivi moduli. I dati sono costruiti con gli stessi motori del programma (documenti, contabilità): ogni quadratura torna, e lo stesso caricamento è usato come prova automatica di correttezza. @@ -125,14 +165,29 @@ esempio. ## Da riga di comando -Lo script `scripts/seed.sh` esegue le stesse operazioni fuori dall'interfaccia (utile in sviluppo): +Lo script `scripts/seed.sh` aggiunge le tabelle di base e i dati di esempio fuori dall'interfaccia. Esegue la sequenza di avvio +(migrazioni, prima azienda) senza servire pagine, poi lavora su un'azienda o su tutte quelle attive e stampa le righe +aggiunte per tabella. Usa le stesse variabili `KHAEMHAT_*` del servizio. + +Nel container (lo script è in `/app/scripts/`): ``` -scripts/seed.sh --base -scripts/seed.sh --demo [--scale N] [--company CODICE] +docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --base +docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --base --company DEMO +docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --demo --company DEMO +docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --demo --scale 10 --company PROVA ``` -`--scale N` moltiplica i volumi dei dati di esempio (usato per le prove di prestazione). +In sviluppo, dalla cartella del repository: `scripts/seed.sh --base|--demo [--scale N] [--company CODICE]`. + +| Opzione | Effetto | +|---|---| +| `--base` | aggiunge i codici di base mancanti | +| `--demo` | prima i dati di base, poi i dati di esempio; ogni gruppo (anagrafiche, articoli) si carica solo nell'azienda che non ne ha ancora | +| `--scale N` | solo con `--demo`: ripete il catalogo articoli N volte (da 1 a 100), per le prove di prestazione | +| `--company CODICE` | lavora solo su quell'azienda invece che su tutte quelle attive | + +I dati di esempio si caricano anche al primo avvio con `KHAEMHAT_SEED_DEMO=true`. ## Migrazioni diff --git a/docs/wiki/Fiscalita-italiana.md b/docs/wiki/Fiscalita-italiana.md index dcd1807..1451cab 100644 --- a/docs/wiki/Fiscalita-italiana.md +++ b/docs/wiki/Fiscalita-italiana.md @@ -1,13 +1,13 @@ # Fiscalità italiana -> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M4-M10) +> **Stato:** bozza · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.4.0 (codici e regole di base; il resto con M5-M10) > **Modulo di licenza:** CORE, ACCT, EINV, INTRA · **Specifica:** SPEC §11.1, §11.3-§11.9, §14 Questa pagina raccoglie in un solo posto i **codici e le regole fiscali italiane** che Khaemhat usa: tipi documento SDI, nature IVA, modalità e condizioni di pagamento, regimi fiscali, codici tributo F24 e scadenze. Serve come riferimento rapido mentre si compilano anagrafiche, codici IVA e documenti. -Tutte queste tabelle sono **caricate dai dati di base** (pacchetto dati, per esempio `IT 2026.2`) e si aggiornano da +Tutte queste tabelle sono **caricate dai dati di base** (pacchetto dati, per esempio `IT 2026.3`) e si aggiornano da **Amministrazione → Dati di base e di esempio** con **Aggiorna tabelle di base**. Le descrizioni ufficiali complete sono quelle delle *specifiche tecniche della fattura elettronica* dell'Agenzia delle Entrate, caricate nel seed: in caso di dubbio fa fede il testo mostrato dal programma, non questa pagina. @@ -58,6 +58,9 @@ caso di dubbio fa fede il testo mostrato dal programma, non questa pagina. | TD28 | Acquisti da San Marino con IVA (fattura cartacea) | acquisti | | TD29 | Comunicazione per omessa o irregolare fatturazione | regolarizzazione (introdotto con le specifiche v1.9) | +Versione delle specifiche tecniche seguita: **1.9.1** (pubblicata dall'Agenzia il 31 marzo 2026, in vigore dal +15 maggio 2026; non cambia le code list della 1.9, che ha introdotto TD29 e ridefinito TD20). + Formati di trasmissione: **FPR12** (verso privati), **FPA12** (verso pubbliche amministrazioni), **FSM10** (fattura semplificata). Nome del file: `IT_.xml`. @@ -70,7 +73,7 @@ codice IVA sulla riga del documento la natura viene compilata da sola. |---|---|---| | N1 | Escluse ex art. 15 DPR 633/72 | `ESC15` | | N2.1 | Non soggette ad IVA ai sensi degli artt. da 7 a 7-septies DPR 633/72 | `FC7` | -| N2.2 | Non soggette - altri casi | fuori campo altre (anche fatture da forfettari) | +| N2.2 | Non soggette - altri casi | `NS`, `FORF` (operazioni in regime forfettario) | | N3.1 | Non imponibili - esportazioni | `NI8` | | N3.2 | Non imponibili - cessioni intracomunitarie | `NI41` | | N3.3 | Non imponibili - cessioni verso San Marino | `NI71` | @@ -79,11 +82,25 @@ codice IVA sulla riga del documento la natura viene compilata da sola. | N3.6 | Non imponibili - altre operazioni che non concorrono alla formazione del plafond | — | | N4 | Esenti | `ESE10` | | N5 | Regime del margine / IVA non esposta in fattura | — (regime del margine previsto in fase 2) | -| N6.1 … N6.9 | Inversione contabile (reverse charge): rottami (N6.1), oro e argento (N6.2), subappalto edile (N6.3), cessione di fabbricati (N6.4), telefoni cellulari (N6.5), prodotti elettronici (N6.6), prestazioni comparto edile e connessi (N6.7), settore energetico (N6.8), altri casi (N6.9) | `RC17` (varianti per sotto-codice) | +| N6.1 … N6.9 | Inversione contabile (reverse charge): rottami (N6.1), oro e argento (N6.2), subappalto edile (N6.3), cessione di fabbricati (N6.4), telefoni cellulari (N6.5), prodotti elettronici (N6.6), prestazioni comparto edile e connessi (N6.7), settore energetico (N6.8), altri casi (N6.9) | `RC74` (N6.1), `RC17O` (N6.2), `RC17A` (N6.3), `RC17F` (N6.4), `RC17B` (N6.5), `RC17C` (N6.6), `RC17E` (N6.7), `RC17N` (N6.8), `RC17` (N6.9) | | N7 | IVA assolta in altro stato UE | — | -Altri codici IVA di base: aliquote **22**, **10**, **5**, **4**; **SPLIT** (scissione dei pagamenti), **NS**, -**indetraibili 50% e 100%**, codici per **forfettari**. +Altri codici IVA di base: aliquote **22**, **10**, **5**, **4**; **22SP** e **10SP** (scissione dei pagamenti, +esigibilità S); **22I50** e **22I100** (IVA 22% indetraibile al 50% e al 100%). + +I codici N2, N3 e N6 senza sotto-codice non sono più accettati dallo SDI: Khaemhat li riconosce nei documenti vecchi +ma non li lascia scegliere su un codice IVA nuovo. + +**Controlli sul codice IVA.** Salvando un codice IVA Khaemhat verifica che: + +- un'aliquota maggiore di zero non abbia natura e un'aliquota zero ce l'abbia; +- la natura esista e sia ancora valida; +- la scissione dei pagamenti abbia un'aliquota; +- l'inversione contabile (N6.x) abbia esigibilità immediata; +- la percentuale di indetraibilità sia fra 0 e 100. + +Sono solo **avvisi** (il codice si salva) un'aliquota diversa da 4, 5, 10 e 22 (per esempio le percentuali di +compensazione agricole) e la mancanza del riferimento normativo, che va stampato in fattura quando c'è la natura. **Esigibilità** (campo del codice IVA): **I** immediata, **D** differita, **S** scissione dei pagamenti (split payment). @@ -181,12 +198,13 @@ Khaemhat propone il codice tributo e prepara i **dati F24** da passare a interme | Adempimento | Regola | Note in Khaemhat | |---|---|---| | Liquidazione IVA mensile | versamento entro il **16 del mese successivo** | la conferma della liquidazione **blocca il periodo** | -| Liquidazione IVA trimestrale | versamento entro il 16 del secondo mese successivo al trimestre (per il secondo trimestre vale la proroga estiva di agosto), con **interessi dell'1%**; il quarto trimestre si versa con il saldo annuale | interessi calcolati in automatico | +| Liquidazione IVA trimestrale | versamento entro il 16 del secondo mese successivo al trimestre (per il secondo trimestre vale la proroga estiva di agosto), con **interessi dell'1%**; il quarto trimestre si versa con il saldo annuale entro il 16 marzo | interessi calcolati in automatico | +| Scadenze in agosto e nei festivi | i versamenti fra il 1° e il 20 agosto slittano al **20 agosto**; una scadenza di sabato, domenica o festivo slitta al primo giorno lavorativo | festivi nazionali, Pasquetta e, dal 2026, il 4 ottobre | | Versamento minimo | importo fino a **€ 25,82** non versato e riportato al periodo successivo | valore della specifica; da verificare in sviluppo rispetto alla norma vigente | | Acconto IVA | entro il **27 dicembre**; metodo **storico**, **previsionale** o **analitico** | scelta del metodo nella liquidazione di dicembre | | LIPE | 1° trimestre entro 31 maggio, 2° entro 16 settembre, 3° entro 30 novembre, 4° entro fine febbraio (o nella dichiarazione annuale) | XML LIPE generato dalla liquidazione | | Ritenute d'acconto operate | versamento entro il **16 del mese successivo** al pagamento della parcella (1040/1038) | la ritenuta nasce al pagamento della fattura | -| Imposta di bollo | **€ 2,00** se le operazioni esenti, non imponibili o fuori campo superano **€ 77,47** | applicato in automatico; addebito al cliente o a carico azienda | +| Imposta di bollo | **€ 2,00** se le operazioni esenti, non imponibili o fuori campo superano **€ 77,47** | contano le nature N1, N2.1, N2.2, N3.5, N3.6, N4, N5; non contano esportazioni (N3.1), cessioni intracomunitarie (N3.2), San Marino (N3.3), operazioni assimilate (N3.4), inversione contabile (N6.x) e N7 | | Bollo virtuale | versamento trimestrale: 1° trimestre entro 31 maggio, 2° entro 30 settembre, 3° entro 30 novembre, 4° entro fine febbraio; con importi bassi i primi trimestri possono slittare (soglia di € 5.000) | elenco da confrontare con quello proposto dall'Agenzia | | Autofatture e integrazioni (TD16-TD19) | XML da trasmettere **entro il 15 del mese successivo** | promemoria nella dashboard | | Fattura differita (TD24) | emissione entro il 15 del mese successivo a quello delle consegne documentate da DDT | procedura **Fatturazione differita** | diff --git a/docs/wiki/Home.md b/docs/wiki/Home.md index 117ccd7..9970cb0 100644 --- a/docs/wiki/Home.md +++ b/docs/wiki/Home.md @@ -1,6 +1,6 @@ # Khaemhat -> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** 0.0.1 (M0, pagina "in costruzione"; sviluppo in corso) +> **Stato:** bozza · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (M4; sviluppo in corso) ![Khaemhat](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/assets/icon-v1.0-128.png) @@ -12,8 +12,8 @@ Docker** e gestisce più aziende sulla stessa installazione. Il nome viene da uno scriba dell'antico Egitto che sovrintendeva ai granai del regno: vedi [Origine del nome](Origine-del-nome). -> Il software è **in fase di progettazione**: questa wiki descrive ciò che verrà costruito, milestone dopo -> milestone. Ogni pagina indica nel riquadro iniziale lo stato (*bozza* finché la funzione non è consegnata) e la +> Il software è **in sviluppo** (versioni 0.x): questa wiki descrive ciò che è già consegnato e ciò che verrà +> costruito, milestone dopo milestone. Ogni pagina indica nel riquadro iniziale lo stato (*bozza* finché la funzione non è consegnata) e la > milestone in cui arriva. Vedi la [Roadmap](Roadmap). ## Per iniziare diff --git a/docs/wiki/Import-Export.md b/docs/wiki/Import-Export.md index 8d09698..385c906 100644 --- a/docs/wiki/Import-Export.md +++ b/docs/wiki/Import-Export.md @@ -1,103 +1,169 @@ # Import/Export -> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M4; saldi e partite di apertura in M12) -> **Modulo di licenza:** CORE (piano dei conti, saldi e partite: ACCT/FIN) · **Livello richiesto:** amministratore · **Specifica:** SPEC §11.7, §12.12 +> **Stato:** completa per M4 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (scrittura di giacenze iniziali in M6, piano dei conti in M7; saldi e partite di apertura in M7 e M9) +> **Modulo di licenza:** CORE (piano dei conti: ACCT) · **Livello richiesto:** amministratore, oppure permesso di scrittura o di export dell'entità · **Specifica:** SPEC §11.7, §12.12 · **Decisione:** ADR 0031 ## A cosa serve La procedura guidata di **Import/Export** porta in Khaemhat i dati che arrivano da un altro gestionale o da un foglio di calcolo e li esporta in formati aperti. È lo strumento per l'**avviamento** di un'azienda: anagrafiche, -articoli, listini, giacenze iniziali, piano dei conti, saldi iniziali e partite aperte. +articoli, prezzi, giacenze iniziali e piano dei conti. ## Dove si trova -**Amministrazione → Import/Export** (titolo: *Import / export dati*). Ogni importazione si apre in una scheda -propria (es. *Import clienti*). +**Amministrazione → Import / export dati** (indirizzo `/amministrazione/import-export`). Il tasto **F1** apre questa +pagina. ## Schermata ![077 · Import/Export · procedura guidata CSV/XLSX/JSON](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/077-import-export-wizard.png) *Mockup 077 — a sinistra i quattro passi della procedura guidata (Origine, Mappatura colonne, Validazione, -Importazione) e le opzioni; a destra l'**Anteprima e validazione** con l'esito riga per riga; in alto **Scarica report -errori** e **Importa N righe** (anteprima ridotta)* +Importazione), le opzioni e il riquadro **Esporta e modelli**; a destra la mappatura o l'**Anteprima e validazione** +con l'esito riga per riga; in alto **Scarica report errori** e **Importa N righe*** + +![Khaemhat 0.4.0 · mappatura colonne](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/import-export-mappatura.png) +*Khaemhat 0.4.0 — il passo Mappatura colonne con un CSV di clienti: le dieci colonne si abbinano da sole, anche *P.IVA*, *Città* e *Prov*.* + +![Khaemhat 0.4.0 · anteprima e validazione](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/import-export-anteprima.png) +*Khaemhat 0.4.0 — l'anteprima dello stesso file: un comune dedotto dal CAP (avviso), un cliente nuovo e tre righe escluse (partita IVA mancante ed e-mail non valida, codice ripetuto, pagamento inesistente).* ## Formati -| Formato | Uso | +| Formato | Lettura | Scrittura (export e modelli) | +|---|---|---| +| **CSV** (`.csv`, `.txt`) | separatore `;`, `,` o tabulazione (dedotto dalla riga di intestazione); UTF-8 con o senza BOM, altrimenti Windows-1252 | `;`, UTF-8 con BOM, numeri con la virgola, date `gg/mm/aaaa`, sì/no come `VERO`/`FALSO` | +| **XLSX** | il primo foglio, intestazioni nella prima riga | un foglio con le intestazioni bloccate | +| **JSON** | un elenco di oggetti con le colonne come chiavi; per il piano dei conti anche `khaemhat-coa.json` | lo stesso elenco (numeri e sì/no come valori JSON) | + +La prima riga contiene sempre le **intestazioni**. Le righe vuote si saltano. Al massimo **50.000 righe** e **25 MB** +per file. + +**Valori accettati in tutte le colonne:** + +- **numeri** all'italiana (`1.234,56`, `€ 12,5`, `22 %`) o con il punto decimale (`1234.56`, come li scrivono Excel e + JSON); +- **date** `gg/mm/aaaa` (anche `g/m/aa`, `gg-mm-aaaa`, `gg.mm.aaaa`), `aaaa-mm-gg`, `aaaammgg` o il numero di serie + di una cella data di Excel; +- **sì/no** come `sì`, `si`, `x`, `1`, `VERO`, `true` oppure `no`, `0`, `FALSO`, `false`; +- le **parole di una scelta** (es. `tipo_soggetto`) senza badare a maiuscole, accenti, spazi e punteggiatura + (`Extra UE` = `extra-ue`, `P.A.` = `pa`). + +## Entità e colonne + +Le intestazioni si abbinano da sole quando sono uguali ai nomi qui sotto o a un nome simile (es. `P.IVA`, +`Partita IVA`, `piva` → `partita_iva`; `Città` → `comune`). Le colonne con **\*** servono per un record nuovo. + +### Clienti e fornitori + +`codice`, `ragione_sociale`, `nome`, `cognome`, `tipo_soggetto`, `partita_iva`, `codice_fiscale`, `rea`, `indirizzo`, +`civico`, `cap`, `comune`, `provincia`, `nazione`, `telefono`, `email`, `pec`, `sito`, `codice_destinatario`, +`categoria`; per i **clienti** anche `agente`, `pagamento`, `listino`, `sconto1`, `sconto2`, `fido`, `iban`, `note`; +per i **fornitori** `pagamento`, `iban`, `note`. + +| Colonna | Valori | |---|---| -| **CSV** | testo con separatore `;` e codifica UTF-8 (formato più comune per gli scambi) | -| **XLSX** | foglio Excel con le stesse colonne del CSV | -| **JSON** | scambio completo fra installazioni Khaemhat (es. piano dei conti con voci di bilancio e causali) | +| `tipo_soggetto` | `impresa`, `privato`, `pa`, `ue`, `extra-ue`, `forfettario` (vuoto: impresa; con solo cognome e nome: privato) | +| `nazione` | codice ISO a due lettere (`IT`, `DE`...) | +| `categoria`, `agente`, `pagamento`, `listino` | il **codice** della tabella (vedi [Tabelle azienda](Tabelle-azienda)) | +| `iban` | aggiunge il conto se non c'è già (il primo diventa predefinito) | -## Entità importabili +Ragione sociale (o cognome e nome per un privato), partita IVA e gli altri controlli sono quelli della scheda (vedi +[Anagrafiche](Anagrafiche)). -| Entità | Note | +### Articoli + +`codice`, `descrizione`\*, `descrizione_estesa`, `tipo`, `categoria`, `um`, `iva_vendite`, `iva_acquisti`, `ean`, +`nc8`, `marca`, `produttore`, `peso_netto`, `peso_lordo`, `a_magazzino`, `magazzino`, `scorta_minima`, +`punto_riordino`, `lotto_riordino`, `prezzo`, `costo_standard`, `conto_ricavo`, `conto_costo`, `note`. + +| Colonna | Valori | |---|---| -| **Anagrafiche** (clienti, fornitori) | verifica partita IVA (VIES per i soggetti UE), comune da CAP | -| **Articoli** | | -| **Listini** | | -| **Giacenze iniziali** | quantità di apertura per deposito | -| **Piano dei conti** | tracciato descritto sotto; verifica della coerenza gerarchica | -| **Saldi iniziali** | saldi di apertura dei conti | -| **Partite di apertura** | crediti e debiti aperti verso clienti e fornitori, con scadenze | +| `tipo` | `merce`, `servizio`, `spesa`, `descrittivo`, `cespite` (vuoto: merce) | +| `categoria`, `um`, `iva_vendite`, `iva_acquisti`, `magazzino` | il **codice** della tabella (`PZ`, `22`, il codice del deposito) | +| `a_magazzino` | sì/no; un articolo che non è merce non è mai a magazzino | +| `prezzo` | il prezzo dell'articolo; i prezzi di listino si importano con l'entità *Prezzi* | -Le colonne disponibili per ogni entità corrispondono ai campi della relativa scheda (vedi [Anagrafiche](Anagrafiche), -[Articoli e listini](Articoli-e-listini), [Magazzino](Magazzino), [Contabilità](Contabilita), -[Scadenzario](Scadenzario)); i tracciati completi saranno pubblicati con i rispettivi moduli. +Il codice generato usa la regola degli articoli, di solito `{categoria}-{seq:0000}`: in quel caso la categoria è +obbligatoria. Unità alternative, codici alternativi, fornitori e sostitutivi restano quelli della scheda (vedi +[Articoli e listini](Articoli-e-listini)). + +### Prezzi di listino e netti cliente + +`articolo`\*, `listino`, `cliente`, `prezzo`\*, `valido_dal`. Ogni riga ha **il listino oppure il cliente** (prezzo +netto), non entrambi. Stesso articolo, listino o cliente e data: il prezzo si sostituisce; una data nuova aggiunge +un prezzo che vale da quel giorno, come nella griglia dei listini. Le righe senza errori si scrivono tutte insieme. + +### Giacenze iniziali (solo verifica fino a M6) + +`articolo`\*, `deposito` (vuoto: il deposito dell'articolo), `quantita`\* (maggiore di zero), `costo_unitario`. +L'articolo deve essere merce gestita a magazzino. Il controllo serve a preparare il file: la scrittura del movimento +di apertura arriva con il [Magazzino](Magazzino). + +### Piano dei conti (solo verifica fino a M7) + +Vedi il tracciato più sotto. ## Come si importa ### 1. Origine -1. Scegli l'**Entità** (es. *Clienti*). -2. Carica il file. Khaemhat riconosce numero di righe, codifica e separatore (es. *clienti.csv · 1.284 righe · - UTF-8 · separatore ;*). -3. Imposta le opzioni: +1. Scegli l'**Entità**. +2. Imposta le opzioni: -| Opzione | Valori | -|---|---| -| **Se il codice esiste** | *Aggiorna* il record esistente oppure lo salta (valori esatti definiti in sviluppo) | -| **Codici mancanti** | *Genera automatici* secondo le regole dei codici automatici (vedi [Tabelle azienda](Tabelle-azienda)) | -| **Verifica P.IVA (VIES per UE)** | controlla le partite IVA | -| **Compila comune da CAP** | completa comune e provincia dal CAP | +| Opzione | Valori | Entità | +|---|---|---| +| **Se il codice esiste** | *Aggiorna* (le celle piene cambiano il record, le vuote lasciano ciò che c'è) oppure *Salta la riga* (avviso) | clienti, fornitori, articoli, prezzi | +| **Codice mancante** | *Genera automatico* con le regole dei codici automatici (vedi [Tabelle azienda](Tabelle-azienda)) oppure *Errore sulla riga* | clienti, fornitori, articoli | +| **Verifica P.IVA su VIES (UE)** | controlla su VIES le partite IVA dei soggetti UE durante l'import (più lento) | clienti, fornitori | +| **Completa comune da CAP** | completa comune e provincia da un CAP con un solo comune, o il CAP da un comune con un solo CAP (avviso) | clienti, fornitori | + +3. Scegli il **file**. Il passo mostra nome, righe e dimensione (es. *clienti_2026.csv · 1.284 righe · 37 KB*). + +Un codice scritto nel file per un record nuovo deve essere ammesso dalla regola dei codici (**codice manuale**): per +mantenere i codici del gestionale precedente lascia attiva quell'opzione nella regola. Un codice già presente in una +riga precedente del file è un errore; il codice di un'anagrafica di altro tipo (un fornitore fra i clienti) anche. ### 2. Mappatura colonne -Khaemhat abbina le colonne del file ai campi dell'entità (es. *12 di 14 colonne abbinate*). Controlla gli -abbinamenti proposti, correggi quelli sbagliati e indica le colonne da ignorare. +Khaemhat abbina le colonne del file ai campi dell'entità (es. *14 di 16 colonne abbinate*) e mostra per ognuna il +valore della prima riga. Correggi gli abbinamenti con l'elenco **Campo**; scegli *Ignora* per le colonne da +tralasciare. Un campo va su una sola colonna. Un avviso elenca i campi obbligatori non abbinati. Premi **Verifica le +righe**. ### 3. Validazione -Ogni riga viene controllata come se fosse inserita a mano. L'**Anteprima e validazione** mostra le prime righe con -l'**Esito**: +Ogni riga viene controllata come se fosse inserita a mano nella scheda. L'**Anteprima e validazione** mostra fino a +500 righe con l'**Esito** e il motivo accanto; le celle con un problema sono evidenziate. | Esito | Significato | Esempio | |---|---|---| -| **OK** | riga importabile | | -| **Avviso** | riga importabile con una correzione proposta | *CAP mancante: proposto 12100* | -| **Errore** | riga non importabile | *P.IVA non valida* | +| **Nuovo** / **Aggiorna** | riga importabile | | +| **Avviso** | riga importabile con una correzione proposta o una nota | *Comune: dedotto dal CAP (Forlì)* | +| **Errore** | riga esclusa | *Partita IVA non valida*, *Il codice XX non esiste* | -Il filtro **Tutte / Solo problemi** mostra solo le righe con avvisi o errori. **Scarica report errori** scarica -l'elenco delle righe problematiche con il motivo: correggile nel file di origine e reimportale. +Il filtro **Tutte / Solo problemi** mostra solo le righe con avvisi o errori. **Scarica report errori** scarica un CSV +con riga, codice, colonna, esito e messaggio: correggi il file di origine e reimportalo. **Mappatura** torna al passo +precedente. ### 4. Importazione -Il riepilogo indica quante righe verranno **create** e quante **aggiornate**. Premi **Importa N righe**: le righe con -errori vengono escluse, le altre importate. L'esito finisce nel [Log](Log) e ogni record creato ha il suo storico. +**Importa N righe** chiede conferma e scrive le righe senza errori, una alla volta come un salvataggio della scheda +(i prezzi tutti insieme). Il riepilogo indica creati, aggiornati, saltati e righe con errori; ogni record ha il suo +storico e l'esito finisce nel [Log](Log) (sezione *Sistema*). **Nuova importazione** ricomincia. **Consiglio:** prova l'importazione su un'azienda clonata (vedi [Istanza e database](Istanza-e-database)) prima di -farla sull'azienda reale, soprattutto per saldi e partite di apertura. +farla sull'azienda reale. ## Tracciato del piano dei conti In Italia non esiste uno standard per lo scambio del piano dei conti, perciò Khaemhat definisce il proprio -tracciato. Il piano standard per PMI è già **precaricato** con le tabelle di base; l'importazione serve a chi vuole -usare il piano del proprio commercialista o del gestionale precedente. +tracciato. Il piano standard per PMI sarà **precaricato** con la contabilità (M7); l'importazione serve a chi vuole +usare il piano del proprio commercialista o del gestionale precedente. Fino a M7 il file si **verifica** soltanto. ### CSV e XLSX -Separatore `;`, una riga per conto, con le colonne: +Una riga per conto, con le colonne: ``` codice;descrizione;livello;padre;natura;tipo;voce_cee;riclassifica;flag @@ -105,54 +171,78 @@ codice;descrizione;livello;padre;natura;tipo;voce_cee;riclassifica;flag | Colonna | Contenuto | |---|---| -| `codice` | codice gerarchico nella forma `MM.CC.SSS` (mastro, conto, sottoconto) | -| `descrizione` | descrizione del conto | -| `livello` | livello nella gerarchia (mastro, conto, sottoconto) | -| `padre` | codice del conto padre (vuoto per i mastri) | -| `natura` | natura del conto (es. patrimoniale/economico; valori ammessi definiti in sviluppo) | -| `tipo` | tipo del conto (valori ammessi definiti in sviluppo) | +| `codice`\* | da 1 a 3 parti separate da punto: mastro, conto, sottoconto (`01`, `01.10`, `01.10.001`) | +| `descrizione`\* | descrizione del conto | +| `livello` | 1, 2 o 3: il numero di parti del codice (se indicato deve corrispondere) | +| `padre` | il codice senza l'ultima parte (se indicato deve corrispondere); deve essere nel file | +| `natura` | `attivo`, `passivo`, `costo`, `ricavo`, `ordine`; obbligatoria sui mastri, ereditata dai sottoconti e uguale a quella del padre | +| `tipo` | `generico` (vuoto), `clienti`, `fornitori`, `banca`, `cassa`, `iva`, `erario` | | `voce_cee` | voce dello schema di bilancio CEE (artt. 2424/2425 c.c.) | | `riclassifica` | voce del bilancio riclassificato | -| `flag` | indicatori del conto (partitario clienti/fornitori, rilevante IVA, chiusura automatica, movimentabile, attivo; codifica definita in sviluppo) | +| `flag` | lettere: `M` movimentabile, `I` rilevante IVA, `P` con partitario clienti/fornitori, `C` chiusura automatica, `X` disattivato | -Esempio di righe (valori indicativi): +Esempio: ``` codice;descrizione;livello;padre;natura;tipo;voce_cee;riclassifica;flag -01;Immobilizzazioni;1;;…;…;;; -01.01;Immobilizzazioni immateriali;2;01;…;…;…;…; -01.01.001;Software;3;01.01;…;…;…;…;… +01;Attivo;1;;attivo;;;; +01.10;Crediti verso clienti;2;01;;;;; +01.10.001;Clienti Italia;3;01.10;;clienti;CII1;;MP +01.20;Disponibilità liquide;2;01;;;;; +01.20.001;Banca;3;01.20;;banca;CIV1;;M ``` Il file **XLSX** usa le stesse colonne, nella prima riga del primo foglio. ### JSON (`khaemhat-coa.json`) -Per l'export e l'import **completo** fra installazioni Khaemhat: contiene **conti**, **voci di bilancio**, **causali -contabili** e **mappature**. È il formato da usare per copiare il piano dei conti da un'azienda all'altra. +Per lo scambio **completo** fra installazioni Khaemhat: -### Controlli in importazione +```json +{ + "format": "khaemhat-coa", + "version": 1, + "accounts": [ { "codice": "01", "descrizione": "Attivo", "natura": "attivo" } ], + "statementLines": [], + "journalTemplates": [], + "mappings": [] +} +``` -- **Coerenza gerarchica**: ogni conto deve avere un padre esistente e un livello coerente con il codice. -- Gli altri controlli (ad esempio codici duplicati o voci CEE inesistenti) seguono le regole del piano dei conti e - saranno precisati in sviluppo. +`accounts` ha le stesse colonne del CSV. Voci di bilancio (`statementLines`), causali (`journalTemplates`) e +mappature (`mappings`) si contano già nella mappatura e si importano con la contabilità (M7). -## Export +### Controlli -I dati si esportano negli stessi formati: +- codice di 1-3 parti, livello e padre coerenti con il codice, padre presente nel file; +- natura indicata sui mastri e uguale a quella del padre; +- **solo i conti senza sottoconti** sono movimentabili (`M` su un conto con sottoconti è un errore; un sottoconto + senza `M` è un avviso); +- lettere di `flag` sconosciute e codici ripetuti sono errori. -- dalla procedura guidata, per le entità sopra elencate (l'obiettivo è che un file esportato si possa reimportare - con lo stesso tracciato; dettagli definiti in sviluppo); -- dalle griglie e dai report (CSV/XLSX/PDF), dal pulsante **Genera file/esporta**; -- il piano dei conti completo in `khaemhat-coa.json`. +## Export e modelli -Gli export richiedono il flag utente **Può esportare dati** (vedi [Utenti e permessi](Utenti-e-permessi)). +Il riquadro **Esporta e modelli** usa l'entità scelta in alto: + +- **Formato**: CSV, XLSX o JSON; +- **Scarica modello**: il file con le sole intestazioni (in JSON un oggetto con i valori vuoti; per il piano dei conti + l'oggetto `khaemhat-coa`); +- **Esporta**: tutti i record con le **stesse colonne dell'import**, così il file si corregge e si reimporta + (nome `clienti-2026-11-12.csv`). I codici delle tabelle sono esportati come codici. + +L'export richiede il flag utente **Può esportare dati** e il permesso di export dell'entità (per le anagrafiche +*Esportare anagrafiche*) (vedi [Utenti e permessi](Utenti-e-permessi)). Giacenze e piano dei conti hanno per ora solo +il modello. Le griglie esportano anche dal proprio menu (CSV/XLSX). ## Domande frequenti -- **Il file ha la virgola come separatore.** Usa il separatore `;` (standard per i CSV in italiano, dove la virgola è - il separatore decimale) oppure salva in XLSX. -- **Le lettere accentate appaiono sbagliate.** Salva il CSV in UTF-8. +- **Il file ha la virgola come separatore.** Va bene: il separatore si deduce dalla riga di intestazione. +- **Le lettere accentate appaiono sbagliate.** Khaemhat legge UTF-8 e, in alternativa, Windows-1252 (il CSV di Excel + per l'Italia); con altre codifiche salva in UTF-8 o in XLSX. +- **Il codice del vecchio gestionale viene rifiutato.** La regola dei codici di quell'archivio non ammette il codice + manuale: abilitalo in *Preferenze azienda → Codici automatici* (`/tabelle/preferenze`), oppure scegli *Genera automatico* e togli la colonna. +- **Ho importato con errori: devo rifare tutto?** No: correggi solo le righe del report e reimportale; con *Aggiorna* + le righe già importate si aggiornano senza doppioni. - **Posso importare documenti (fatture, DDT) da un altro gestionale?** Non con questa procedura: le fatture elettroniche di acquisto si importano dall'XML SDI (vedi [Acquisti](Acquisti) e [Fatturazione elettronica](Fatturazione-elettronica)). @@ -160,4 +250,4 @@ Gli export richiedono il flag utente **Può esportare dati** (vedi [Utenti e per ## Pagine correlate [Dati di base e di esempio](Dati-di-base-e-esempio) · [Contabilità](Contabilita) · [Anagrafiche](Anagrafiche) · -[Articoli e listini](Articoli-e-listini) · [Scadenzario](Scadenzario) · [Tabelle azienda](Tabelle-azienda) · [Primi passi](Primi-passi) +[Articoli e listini](Articoli-e-listini) · [Magazzino](Magazzino) · [Tabelle azienda](Tabelle-azienda) · [Primi passi](Primi-passi) diff --git a/docs/wiki/Roadmap.md b/docs/wiki/Roadmap.md index 48dc99c..dc05874 100644 --- a/docs/wiki/Roadmap.md +++ b/docs/wiki/Roadmap.md @@ -1,6 +1,6 @@ # Roadmap -> **Stato:** bozza · **Ultima revisione:** 2026-11-11 · **Specifica:** SPEC §20 +> **Stato:** bozza · **Ultima revisione:** 2026-11-12 · **Specifica:** SPEC §20 Khaemhat si costruisce in **15 milestone**. Ogni milestone si chiude con un tag di versione, un'immagine Docker nel registro pacchetti di Gitea e la wiki delle funzioni consegnate portata da *bozza* a *completa*. @@ -10,7 +10,10 @@ Il lavoro di dettaglio è nelle issue di Gitea, raggruppate per [progetti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/projects) *Khaemhat 1.0 — Sviluppo* e *Khaemhat 1.1+ — Fase 2*. -**Completate:** M0 (0.0.1), M1 (0.1.0), M2 (0.2.0), M3 (0.3.0). **In corso:** M4. +Finché il prodotto è in sviluppo le versioni restano **0.x**, anche dopo M13: la **1.0.0** sarà pubblicata solo +quando verrà deciso esplicitamente. + +**Completate:** M0 (0.0.1), M1 (0.1.0), M2 (0.2.0), M3 (0.3.0), M4 (0.4.0). **In corso:** M5. | # | Milestone | Contenuto principale | Versione | |---|---|---|---| @@ -27,8 +30,8 @@ Il lavoro di dettaglio è nelle issue di Gitea, raggruppate per | M10 | Cespiti, Intrastat, chiusura, bilancio | Registro cespiti, Intrastat, dichiarazioni d'intento, ratei e risconti, chiusura e apertura, bilancio CEE | 0.10.0 | | M11 | CRM | Lead, pipeline, opportunità, attività e agenda, campagne, ticket, scheda 360° | 0.11.0 | | M12 | Amministrazione, automazioni, API | Gestione database, backup e ripristino (anche S3 e WebDAV), attività programmate, impostazioni, stato sistema e aggiornamenti, API REST, MCP, webhook, regole e procedure | 0.12.0 | -| M13 | Consolidamento e rilascio | Sicurezza, prestazioni, accessibilità, wiki completa, PWA, prova su Unraid | **1.0.0** | -| M14 | Fase 2 | Servizi (contratti e interventi), canali e-commerce, EN 16931/Peppol, XBRL, regime del margine, ventilazione, IVA per cassa completa, SFTP | 1.1.0+ | +| M13 | Consolidamento e rilascio | Sicurezza, prestazioni, accessibilità, wiki completa, PWA, prova su Unraid | 0.13.0 | +| M14 | Fase 2 | Servizi (contratti e interventi), canali e-commerce, EN 16931/Peppol, XBRL, regime del margine, ventilazione, IVA per cassa completa, SFTP | 0.14.0+ | ## Stato attuale diff --git a/docs/wiki/Stato-sistema.md b/docs/wiki/Stato-sistema.md index 0aa4e0a..a65a6c1 100644 --- a/docs/wiki/Stato-sistema.md +++ b/docs/wiki/Stato-sistema.md @@ -63,7 +63,7 @@ Il riquadro **Versione** riporta: | **Motore DB** | PostgreSQL 17 · minima 16 | | **Cache** | Redis (opzionale) o memoria | | **Fuso orario** | `Europe/Rome` | -| **Pacchetto fiscale** | Italia · dati `IT 2026.2` | +| **Pacchetto fiscale** | Italia · dati `IT 2026.3` | | **Istanza** | nome host e numero di aziende | La stessa versione compare nella barra superiore (solo `major.minor`), nella barra di stato (completa) e diff --git a/docs/wiki/Tabelle-azienda.md b/docs/wiki/Tabelle-azienda.md index db9dfd8..92d7be3 100644 --- a/docs/wiki/Tabelle-azienda.md +++ b/docs/wiki/Tabelle-azienda.md @@ -1,7 +1,7 @@ # Tabelle azienda -> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M4) -> **Modulo di licenza:** CORE · **Permessi principali:** famiglia `company.*` (codici esatti definiti in sviluppo) · **Specifica:** SPEC §11.1, §11.12 (codici automatici, compilazione, preferenze), §14 +> **Stato:** completa · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (milestone M4) +> **Modulo di licenza:** CORE · **Permessi principali:** `company.settings.read` (consultare), `company.settings.write` (modificare) · **Specifica:** SPEC §11.1, §11.12 (codici automatici, compilazione, preferenze), §14 Le **tabelle azienda** sono i dati di configurazione su cui si appoggia tutto il resto: il **profilo dell'azienda**, gli **esercizi e i periodi**, i **codici IVA**, i pagamenti, le banche, i depositi, i numeratori dei documenti, i @@ -10,20 +10,50 @@ dati di base italiani (vedi [Dati di base e di esempio](Dati-di-base-e-esempio)) ## Dove si trova -Menu **Tabelle azienda** → *Profilo azienda*, *Codici IVA*, *Pagamenti*, *Numeratori*, *Depositi*, *Valute*, -*Trasporti*, *Preferenze e codici automatici*; le altre tabelle sono raggiungibili dallo stesso menu e dalla ricerca -globale (`Ctrl+K`). Esercizi e periodi sono in *Tabelle azienda → Esercizi*. +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*, *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* è a `/tabelle/preferenze`. -Ogni tabella ha la propria maschera, costruita come il radar dei clienti e la maschera dei codici IVA: elenco con -ricerca e filtri, dettaglio sotto o in scheda, **import ed export CSV**. +![Khaemhat 0.4.0 · Tabelle azienda](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/tabelle-indice.png) +*Khaemhat 0.4.0 — l'indice delle tabelle azienda per gruppi, con il sottomenu delle voci più usate.* + +## Come si usa una tabella + +Tutte le tabelle codificate hanno la stessa maschera: + +- **Elenco** con ricerca, filtro rapido *Attive / Disattivate / Tutte* (all'apertura si vedono solo le attive) e + colonne principali; un clic sceglie la riga, doppio clic o `Invio` la apre. +- **Dettaglio** sotto l'elenco: *Codice*, *Descrizione*, *Disattivata* e i campi propri della tabella. Gli errori + compaiono accanto al campo e nel riepilogo; gli **avvisi** (ad esempio un codice IVA senza riferimento normativo) + non bloccano il salvataggio. +- **Barra comandi**: *Nuovo*, *Salva* (`Ctrl+S`), *Annulla modifiche*, *Elimina*. Una riga usata altrove non si può + eliminare: Khaemhat propone di **disattivarla**, così resta nei documenti già fatti ma non si propone più. +- Menu `…`: **Esporta CSV**, **Importa CSV** e **Aggiorna da tabelle base**. +- Uscendo con modifiche non salvate viene chiesta conferma. + +**Importa CSV** (file fino a 20 MB, separatore `;`, `,` o tabulazione, prima riga con i nomi delle colonne come nell'export): le +righe con un codice già presente vengono aggiornate, le altre aggiunte. È **tutto o niente**: se una riga ha un +errore non viene importato nulla e la finestra elenca riga, campo e motivo. + +**Aggiorna da tabelle base** aggiunge i codici di base mancanti senza modificare le righe che ci sono già (vedi +[Dati di base e di esempio](Dati-di-base-e-esempio)). + +Le **condizioni di pagamento** hanno anche le **rate**: giorni, fine mese, giorno fisso e percentuale; la somma delle +percentuali deve fare 100 e le rate si salvano tutte insieme. ## Profilo azienda ![075 · Profilo azienda](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/075-profilo-azienda.png) *Mockup 075 — profilo azienda: schede Dati societari, Fiscale e SDI, Banche, Logo e stampe, Esercizi e periodicità, Trasmittente/intermediario (anteprima ridotta).* +Indirizzo: `/tabelle/profilo-azienda`. Al salvataggio partita IVA, codice fiscale, codice destinatario e regime +fiscale sono controllati dal pacchetto fiscale del paese; se un errore è in un'altra scheda, Khaemhat si sposta +sulla scheda del primo errore. Il logo per le stampe arriva con i modelli di stampa dei documenti. + Il profilo è una scheda unica (una sola per azienda). In alto a destra un badge indica la versione del **pacchetto -fiscale** in uso (es. *IT 2026.2*). +fiscale** in uso (es. *IT 2026.3*). | Scheda / gruppo | Campi | |---|---| @@ -49,6 +79,10 @@ sblocca. **Periodi** (mesi o trimestri secondo la periodicità IVA): stato *aperto*, *liquidato* o *bloccato*, esito della liquidazione IVA (*provvisoria*, *confermata*), registrazioni, interruttore **Blocco**. +Indirizzo: `/tabelle/esercizi`. **Nuovo esercizio** crea l'anno successivo all'ultimo con i suoi dodici mesi. Il +pulsante **Blocca** di un mese impedisce nuove registrazioni con date in quel mese; **Sblocca** chiede conferma. Un +mese *liquidato* si sblocca solo annullando la liquidazione IVA (M7). + Regola fondamentale: **si possono registrare documenti e movimenti contabili solo con data in un periodo aperto**. Un periodo bloccato rifiuta ogni registrazione con data al suo interno; la conferma della liquidazione IVA blocca il periodo (vedi [IVA](IVA)) e la chiusura dell'esercizio lo rende di sola lettura (vedi [Contabilità](Contabilita)). @@ -58,8 +92,8 @@ periodo (vedi [IVA](IVA)) e la chiusura dell'esercizio lo rende di sola lettura | Tabella | Contenuto | |---|---| | **Paesi** | codici ISO 3166-1, appartenenza all'UE, codice SDI per l'estero (`XXXXXXX`) | -| **Province** e **Comuni** | CAP e codice catastale: servono per la compilazione da CAP e per il calcolo del codice fiscale | -| **Valute** e **Cambi** | valute con i cambi giornalieri della BCE | +| **Province** e **Comuni** | Sigla, regione, codice catastale (il codice del comune), codice ISTAT e CAP: servono per la compilazione da CAP e per il calcolo del codice fiscale. Province, comuni e CAP arrivano con i dati di base (elenco ISTAT, CAP da GeoNames); i pochi CAP mancanti si completano a mano o con l'Importa CSV, vedi [Dati di base e di esempio](Dati-di-base-e-esempio) | +| **Valute** e **Cambi** | valute con i cambi giornalieri della BCE; in *Cambi* (`/tabelle/cambi`) si vedono i cambi per data e origine e si inserisce un cambio manuale | | **Unità di misura** | codici interni e codice usato nell'XML SDI | | **Codici IVA** | aliquota, natura SDI, riferimento normativo, esigibilità, tipo, indetraibilità, conti IVA, validità (vedi sotto) | | **Metodi di pagamento** | codici SDI `MP01`…`MP23` (es. MP01 contanti, MP02 assegno, MP05 bonifico, MP08 carta di pagamento, MP12 RiBa, MP19 SEPA Direct Debit) | @@ -77,8 +111,8 @@ periodo (vedi [IVA](IVA)) e la chiusura dell'esercizio lo rende di sola lettura | **Depositi** | magazzini, anche mobili (es. furgone) | | **Categorie articolo** | su tre livelli | | **Categorie controparte** | classificazione di clienti e fornitori | -| **Listini** | intestazioni dei listini (i prezzi sono in [Articoli e listini](Articoli-e-listini)) | -| **Politiche di sconto** | regole di sconto riutilizzabili (struttura definita in sviluppo) | +| **Listini** | intestazioni dei listini: valuta, IVA inclusa, validità, **Listino base** (uno solo, in partenza `BASE`), **Derivato da** con ricarico % e arrotondamento (i prezzi sono in [Articoli e listini](Articoli-e-listini)) | +| **Politiche di sconto** | sconti in cascata con un codice, come formula (`10+5`), da richiamare nelle condizioni | | **Tipi documento** | catalogo dei documenti con numeratore, causale di magazzino, causale contabile, registro IVA, codice TD, modello di stampa | | **Centri di costo** | per l'analisi dei costi e dei ricavi | | **Commesse** | progetti o cantieri a cui imputare costi e ricavi | @@ -88,6 +122,9 @@ periodo (vedi [IVA](IVA)) e la chiusura dell'esercizio lo rende di sola lettura ![076 · Codici IVA con nature SDI](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/076-codici-iva.png) *Mockup 076 — elenco dei codici IVA con aliquota, tipo, natura SDI, esigibilità, indetraibilità e conti, con il dettaglio del codice RC17 (anteprima ridotta).* +![Khaemhat 0.4.0 · codici IVA](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/tabelle-codici-iva.png) +*Khaemhat 0.4.0 — l'elenco dei codici IVA di base con il dettaglio del codice 22SP (scissione dei pagamenti).* + Ogni codice IVA ha: **codice**, **descrizione**, **aliquota**, **tipo** (IVA, esente, non imponibile, fuori campo, escluso, reverse charge), **natura SDI** per le operazioni senza imposta, **riferimento normativo** (stampato in fattura e riportato nell'XML), **esigibilità** (`I` immediata, `D` differita, `S` scissione dei pagamenti), @@ -112,19 +149,26 @@ sotto-codice scelto in riga), `SPLIT` (split payment), indetraibili 50% e 100%, ## Numeratori -Ogni **tipo documento** usa un numeratore per **sezionale** e **anno**, con un **formato** che di predefinito è -`{prefix}/{anno}/{number:D6}`, ad esempio `FT/2026/000419`. Il numero è assegnato in modo atomico **alla conferma**; -per fatture, note di credito e registrazioni contabili definitive **non sono ammessi buchi** nella numerazione. Il -protocollo IVA degli acquisti ha il proprio formato (es. `ACQ/{anno}/…`) e i progressivi si azzerano a ogni -esercizio (impostazione *Reset progressivi*). +Ogni **tipo documento** usa un numeratore per **sezionale** e **anno**, con un **formato** composto dai segnaposto +`{prefix}`, `{year}`, `{section}` e `{number}` (con `{number:D6}` il numero ha sei cifre con gli zeri davanti). Il +formato deve contenere `{number}`. Esempi dei numeratori di base: fatture `{number}/{year}` (`419/2026`), ordini +clienti `OC-{year}-{number:D4}` (`OC-2026-0042`), autofatture `{number}/AF/{year}` nel sezionale `AF`. + +Il numero è assegnato in modo atomico **alla conferma** del documento (da M5); per fatture, note di credito, +protocollo acquisti e registrazioni contabili **non sono ammessi buchi** nella numerazione (opzione *Ammessi buchi di numerazione* +spenta). I numeratori sono per anno: il caricamento di base crea quelli dell'anno in corso. ## Preferenze e codici automatici ![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*. +![Khaemhat 0.4.0 · codici automatici](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/wiki/img/tabelle-codici-automatici.png) +*Khaemhat 0.4.0 — le maschere dei codici automatici con l'anteprima del prossimo codice; le maschere dei moduli non attivi restano pronte.* + +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 @@ -142,40 +186,58 @@ 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 -| Scheda | Contenuto | -|---|---| -| **Arrotondamenti e controlli** | arrotondamenti di prezzi e totali, controlli bloccanti o di avviso (fido, scaduto, date) | -| **Default documenti** | sezionali, depositi, causali e condizioni proposti per tipo documento | -| **Modelli e-mail** | testi per l'invio di documenti, solleciti, notifiche | -| **Testi di stampa** | diciture e note in calce ai documenti | +In 0.4.0 le preferenze azienda hanno le schede *Codici automatici* e *Compilazione automatica*. Arriveranno con i +moduli che le usano: -La periodicità IVA e le numerazioni fanno parte delle preferenze aziendali e si impostano nel profilo e nei -numeratori. Il dettaglio di ogni opzione sarà completato in sviluppo. +| Scheda | Contenuto | Con | +|---|---|---| +| **Arrotondamenti e controlli** | arrotondamenti di prezzi e totali, controlli bloccanti o di avviso (fido, scaduto, date) | documenti (M5) | +| **Default documenti** | sezionali, depositi, causali e condizioni proposti per tipo documento | documenti (M5) | +| **Modelli e-mail** | testi per l'invio di documenti, solleciti, notifiche | e-mail (M5) | +| **Testi di stampa** | diciture e note in calce ai documenti | stampe (M5) | + +La periodicità IVA e le numerazioni si impostano nel profilo azienda e nei numeratori. ## Permessi e licenza @@ -188,8 +250,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/docs/wiki/img/anagrafiche-radar.png b/docs/wiki/img/anagrafiche-radar.png new file mode 100644 index 0000000..1f5ec5f Binary files /dev/null and b/docs/wiki/img/anagrafiche-radar.png differ diff --git a/docs/wiki/img/anagrafiche-scheda.png b/docs/wiki/img/anagrafiche-scheda.png new file mode 100644 index 0000000..6f79f4f Binary files /dev/null and b/docs/wiki/img/anagrafiche-scheda.png differ diff --git a/docs/wiki/img/articoli-radar.png b/docs/wiki/img/articoli-radar.png new file mode 100644 index 0000000..3ee2937 Binary files /dev/null and b/docs/wiki/img/articoli-radar.png differ diff --git a/docs/wiki/img/articoli-scheda.png b/docs/wiki/img/articoli-scheda.png new file mode 100644 index 0000000..1d1132f Binary files /dev/null and b/docs/wiki/img/articoli-scheda.png differ diff --git a/docs/wiki/img/import-export-anteprima.png b/docs/wiki/img/import-export-anteprima.png new file mode 100644 index 0000000..ab8aaa4 Binary files /dev/null and b/docs/wiki/img/import-export-anteprima.png differ diff --git a/docs/wiki/img/import-export-mappatura.png b/docs/wiki/img/import-export-mappatura.png new file mode 100644 index 0000000..43fcb77 Binary files /dev/null and b/docs/wiki/img/import-export-mappatura.png differ diff --git a/docs/wiki/img/listini-griglia.png b/docs/wiki/img/listini-griglia.png new file mode 100644 index 0000000..6dfdad5 Binary files /dev/null and b/docs/wiki/img/listini-griglia.png differ diff --git a/docs/wiki/img/tabelle-codici-automatici.png b/docs/wiki/img/tabelle-codici-automatici.png new file mode 100644 index 0000000..3e94bd7 Binary files /dev/null and b/docs/wiki/img/tabelle-codici-automatici.png differ diff --git a/docs/wiki/img/tabelle-codici-iva.png b/docs/wiki/img/tabelle-codici-iva.png new file mode 100644 index 0000000..707c482 Binary files /dev/null and b/docs/wiki/img/tabelle-codici-iva.png differ diff --git a/docs/wiki/img/tabelle-indice.png b/docs/wiki/img/tabelle-indice.png new file mode 100644 index 0000000..197f3fc Binary files /dev/null and b/docs/wiki/img/tabelle-indice.png differ diff --git a/scripts/seed.sh b/scripts/seed.sh index 7fd5256..bb82fdc 100755 --- a/scripts/seed.sh +++ b/scripts/seed.sh @@ -1,9 +1,17 @@ #!/usr/bin/env bash -# Loads base tables and demo data into a company database (SPEC §15). -# scripts/seed.sh --base | --demo [--scale N] [--company CODE] -# Stub: completed in milestone M4 (SPEC §20). Until then it explains what it will do and exits with an error. +# Adds the missing base tables to the company databases (SPEC §14, ADR 0026), and with --demo the demo data to the +# tables still empty (--scale N repeats the demo catalogues N times). Rows already there are never changed. +# scripts/seed.sh --base [--company CODE] +# scripts/seed.sh --demo [--scale N] [--company CODE] +# In the container (shipped as /app/scripts/seed.sh, same KHAEMHAT_* variables as the service): +# docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --base +# On a development machine it runs the project with the variables already set in the shell (see scripts/run-dev.sh). set -euo pipefail -echo "seed.sh: non ancora disponibile, arriva con la milestone M4." >&2 -echo "Uso previsto: scripts/seed.sh --base | --demo [--scale N] [--company CODE]" >&2 -exit 1 +if [[ -f /app/Khaemhat.Web.dll ]]; then + # The entrypoint prepares the user and waits for the database, then runs "dotnet Khaemhat.Web.dll seed ...". + exec /app/entrypoint.sh seed "$@" +fi + +root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +exec dotnet run --project "$root/src/Khaemhat.Web" -- seed "$@" diff --git a/src/Khaemhat.Application/ImportExport/CheckOnlyImportTargets.cs b/src/Khaemhat.Application/ImportExport/CheckOnlyImportTargets.cs new file mode 100644 index 0000000..108a6b3 --- /dev/null +++ b/src/Khaemhat.Application/ImportExport/CheckOnlyImportTargets.cs @@ -0,0 +1,332 @@ +using Khaemhat.Application.Modules; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Accounting; +using Khaemhat.Core.Items; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.ImportExport; + +/// An account of the chart read from a file. +/// The code, parts separated by points (01.02.003). +/// The description. +/// The level, 1 to 3: the number of parts of the code. +/// The code without its last part. +/// The nature. +/// The use. +/// Postings go on it (only leaves). +/// Relevant for VAT. +/// With a sub-ledger of customers or suppliers. +/// Closed by the year end. +/// Not used any more. +public sealed record ImportedAccount( + string Code, string Description, int Level, string? ParentCode, AccountNature Nature, AccountType Type, bool Postable, bool VatRelevant, bool SubLedger, + bool ClosesAutomatically, bool Disabled); + +/// +/// The checks of a chart of accounts from a file (SPEC §12.12, ADR 0031): codes of one to three parts separated by +/// points, each account under the account whose code is its own without the last part, with the same nature; only +/// leaves are postable. Pure, so that M7 writes what this checks. +/// +public static class ChartOfAccountsImportValidator +{ + /// The words of natura, in the order of . + public static readonly IReadOnlyList NatureWords = ["attivo", "passivo", "costo", "ricavo", "ordine"]; + + /// The words of tipo, in the order of . + public static readonly IReadOnlyList TypeWords = ["generico", "clienti", "fornitori", "banca", "cassa", "iva", "erario"]; + + /// The flag letters: postable, VAT relevant, sub-ledger, automatic closing, disabled. + public const string FlagLetters = "MIPCX"; + + /// The deepest level. + public const int MaxLevel = 3; + + /// The columns of the chart. + public static IReadOnlyList Fields { get; } = + [ + new("codice", ImportFieldKind.Code, Required: true, Aliases: ["conto", "codice_conto", "cod_conto"]), + new("descrizione", Required: true, Aliases: ["descr", "denominazione"]), + new("livello", ImportFieldKind.Number, Aliases: ["liv"]), + new("padre", ImportFieldKind.Code, Aliases: ["conto_padre", "mastro"]), + new("natura", ImportFieldKind.Choice, Aliases: ["sezione"], Choices: NatureWords), + new("tipo", ImportFieldKind.Choice, Aliases: ["tipo_conto"], Choices: TypeWords), + new("voce_cee", Aliases: ["cee", "voce_bilancio"]), + new("riclassifica", Aliases: ["riclassificazione"]), + new("flag", Aliases: ["flags", "attributi"]), + ]; + + /// Checks the rows of a chart. + /// The rows. + /// A result per row, and the accounts without errors. + public static (IReadOnlyList Results, IReadOnlyList Accounts) Check(IReadOnlyList rows) + { + ArgumentNullException.ThrowIfNull(rows); + + // First pass: every code with its nature as written, to check parents wherever they are in the file. + var natures = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var row in rows) + { + if (row["codice"] is { } code) + { + natures.TryAdd(code, Choice(row["natura"], NatureWords) is { } n ? (AccountNature)n : null); + } + } + + var parents = natures.Keys.Select(ParentOf).Where(p => p is not null).ToHashSet(StringComparer.OrdinalIgnoreCase); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + var results = new List(rows.Count); + var accounts = new List(); + foreach (var row in rows) + { + var messages = new List(); + var cells = new CellReader(row, messages); + var code = row["codice"]; + messages.AddRange(Fields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required))); + if (code is null) + { + results.Add(new(row.Line, row["descrizione"] ?? string.Empty, ImportAction.Skip, messages)); + continue; + } + + if (!seen.Add(code)) + { + results.Add(new(row.Line, code, ImportAction.Skip, [new("codice", ImportErrors.CodeRepeated, Value: code)])); + continue; + } + + var parts = code.Split('.'); + var level = parts.Length; + if (level > MaxLevel || parts.Any(p => p.Length == 0 || !p.All(char.IsAsciiLetterOrDigit))) + { + messages.Add(new("codice", ImportErrors.AccountLevel, Value: code)); + } + else if (cells.Number("livello") is { } written && written != level) + { + messages.Add(new("livello", ImportErrors.AccountLevel, Value: level.ToString(System.Globalization.CultureInfo.InvariantCulture))); + } + + var parent = ParentOf(code); + if (row["padre"] is { } named && !string.Equals(named, parent, StringComparison.OrdinalIgnoreCase)) + { + messages.Add(new("padre", ImportErrors.AccountParent, Value: parent ?? string.Empty)); + } + else if (parent is not null && !natures.ContainsKey(parent)) + { + messages.Add(new("padre", ImportErrors.AccountParent, Value: parent)); + } + + var nature = NatureOf(code, natures); + if (nature is null) + { + messages.Add(new("natura", cells.Has("natura") ? ImportErrors.Choice : ImportErrors.Required, Value: cells.Has("natura") ? string.Join(", ", NatureWords) : null)); + } + else if (parent is not null && natures.ContainsKey(parent) && NatureOf(parent, natures) is { } parentNature && parentNature != nature) + { + messages.Add(new("natura", ImportErrors.AccountNature, Value: NatureWords[(int)parentNature])); + } + + var type = cells.Choice(Fields[5]) is { } t ? (AccountType)t : AccountType.Generic; + var flags = (row["flag"] ?? string.Empty).ToUpperInvariant().Where(c => !char.IsWhiteSpace(c) && c is not ',' and not ';').ToList(); + if (flags.FirstOrDefault(c => !FlagLetters.Contains(c, StringComparison.Ordinal)) is var bad && bad != default) + { + messages.Add(new("flag", ImportErrors.AccountFlag, Value: bad.ToString())); + } + + var postable = flags.Contains('M'); + var leaf = !parents.Contains(code); + if (postable && !leaf) + { + messages.Add(new("flag", ImportErrors.AccountPostable)); + } + else if (!postable && leaf && level > 1) + { + messages.Add(new("flag", ImportErrors.AccountLeaf, IsWarning: true)); + } + + if (messages.All(m => m.IsWarning) && nature is { } valid) + { + accounts.Add(new(code, row["descrizione"] ?? string.Empty, level, parent, valid, type, postable, flags.Contains('I'), flags.Contains('P'), flags.Contains('C'), + flags.Contains('X'))); + } + + results.Add(new(row.Line, code, messages.Any(m => !m.IsWarning) ? ImportAction.Skip : ImportAction.Create, messages)); + } + + return (results, accounts); + } + + /// The code without its last part, or for a first level account. + /// The code. + /// The parent code. + public static string? ParentOf(string code) + { + ArgumentNullException.ThrowIfNull(code); + var point = code.LastIndexOf('.'); + return point <= 0 ? null : code[..point]; + } + + // The nature written on the account, else the one of the nearest ancestor that has one. + private static AccountNature? NatureOf(string code, Dictionary natures) + { + for (var current = code; current is not null; current = ParentOf(current)) + { + if (natures.TryGetValue(current, out var nature) && nature is not null) + { + return nature; + } + } + + return null; + } + + private static int? Choice(string? text, IReadOnlyList words) => text is null ? null : ImportValues.Choice(text, words) is var i and >= 0 ? i : null; +} + +/// +/// The chart of accounts (piano-dei-conti): CSV, XLSX or khaemhat-coa.json. Until the ledger exists (M7) +/// the file is only checked; M7 writes the accounts this check accepts. +/// +/// Checks the permission. +public sealed class ChartOfAccountsImportTarget(PermissionService permissions) : IImportTarget +{ + /// The permission to change the chart of accounts. + public const string WritePermission = "ledger.account.write"; + + /// + public string Key => "piano-dei-conti"; + + /// + public string ModuleCode => ModuleCodes.Accounting; + + /// + public string Permission => WritePermission; + + /// + public string ExportPermission => "ledger.account.read"; + + /// + public bool CanApply => false; + + /// + public bool CanExport => false; + + /// + public IReadOnlyList Fields => ChartOfAccountsImportValidator.Fields; + + /// + public async Task> CheckAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false); + return ChartOfAccountsImportValidator.Check(rows).Results; + } + + /// + public Task> ApplyAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) => + throw new InvalidOperationException(ImportErrors.CheckOnly); + + /// + public Task>> ExportAsync(ImportContext context, CancellationToken cancellationToken) => + Task.FromResult>>([]); +} + +/// +/// The opening stock (giacenze-iniziali): item, warehouse, quantity and unit cost. Until the stock entries exist +/// (M6) the file is only checked; M6 writes the opening entry from the rows this check accepts. +/// +/// Opens the company databases. +/// Checks the permission. +public sealed class OpeningStockImportTarget(IUnitOfWorkFactory factory, PermissionService permissions) : IImportTarget +{ + private static readonly ImportField[] StockFields = + [ + new("articolo", ImportFieldKind.Code, Required: true, Aliases: ["codice_articolo", "codice", "cod_articolo", "sku"]), + new("deposito", ImportFieldKind.Code, Aliases: ["magazzino", "codice_magazzino"]), + new("quantita", ImportFieldKind.Number, Required: true, Aliases: ["qta", "qty", "giacenza", "esistenza"]), + new("costo_unitario", ImportFieldKind.Number, Aliases: ["costo", "valore_unitario", "prezzo_acquisto"]), + ]; + + /// + public string Key => "giacenze-iniziali"; + + /// + public string ModuleCode => ModuleCodes.Core; + + /// + public string Permission => "inventory.entry.write"; + + /// + public string ExportPermission => "inventory.stock.read"; + + /// + public bool CanApply => false; + + /// + public bool CanExport => false; + + /// + public IReadOnlyList Fields => StockFields; + + /// + public async Task> CheckAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(rows); + var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false); + await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var items = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items; + var codes = new CodeIndex(items.Select(i => (i.Code, i.Id))); + var byId = items.ToDictionary(i => i.Id); + var warehouses = await CodeIndex.LoadAsync(uow, cancellationToken).ConfigureAwait(false); + var seen = new HashSet<(long, long)>(); + var results = new List(rows.Count); + foreach (var row in rows) + { + var messages = new List(); + var cells = new CellReader(row, messages); + messages.AddRange(StockFields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required))); + var item = cells.Code("articolo", codes) is { } id ? byId[id] : null; + var warehouse = cells.Code("deposito", warehouses) ?? (cells.Has("deposito") ? null : item?.WarehouseId); + if (item is not null && (item.Kind != ItemKind.Goods || !item.Stocked)) + { + messages.Add(new("articolo", ImportErrors.NotStocked, Value: item.Code)); + } + + if (item is not null && warehouse is null && !cells.Has("deposito")) + { + messages.Add(new("deposito", ImportErrors.Required)); + } + + if (cells.Number("quantita") is <= 0) + { + messages.Add(new("quantita", ImportErrors.Positive)); + } + + if (cells.Number("costo_unitario") is < 0) + { + messages.Add(new("costo_unitario", Items.ItemService.NotNegative)); + } + + var label = row["articolo"] ?? string.Empty; + if (item is not null && warehouse is { } w && !seen.Add((item.Id, w))) + { + messages.Add(new("articolo", ImportErrors.CodeRepeated, Value: label)); + } + + results.Add(new(row.Line, label, messages.Any(m => !m.IsWarning) ? ImportAction.Skip : ImportAction.Create, messages)); + } + + return results; + } + + /// + public Task> ApplyAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) => + throw new InvalidOperationException(ImportErrors.CheckOnly); + + /// + public Task>> ExportAsync(ImportContext context, CancellationToken cancellationToken) => + Task.FromResult>>([]); +} diff --git a/src/Khaemhat.Application/ImportExport/ImportFileReader.cs b/src/Khaemhat.Application/ImportExport/ImportFileReader.cs new file mode 100644 index 0000000..17673e7 --- /dev/null +++ b/src/Khaemhat.Application/ImportExport/ImportFileReader.cs @@ -0,0 +1,255 @@ +using System.Globalization; +using System.Text; +using System.Text.Json; +using Khaemhat.Infrastructure.Files; + +namespace Khaemhat.Application.ImportExport; + +/// A file the import cannot use; is one of the import.file.* codes. +public sealed class ImportFileException : Exception +{ + /// Creates the exception. + public ImportFileException() + { + Code = ImportErrors.FileUnreadable; + } + + /// Creates the exception. + /// What went wrong. + public ImportFileException(string message) + : base(message) + { + Code = ImportErrors.FileUnreadable; + } + + /// Creates the exception. + /// What went wrong. + /// The cause. + public ImportFileException(string message, Exception innerException) + : base(message, innerException) + { + Code = ImportErrors.FileUnreadable; + } + + /// Creates the exception with a code. + /// The text code. + /// What went wrong. + /// The cause. + public ImportFileException(string code, string message, Exception? innerException) + : base(message, innerException) + { + Code = code; + } + + /// The text code. + public string Code { get; } +} + +/// +/// Reads the files of the guided import (SPEC §12.12): CSV (UTF-8 with or without byte order mark, else Windows-1252; +/// separator ;, , or tab guessed from the header), XLSX (first sheet) and JSON (an array of objects, or the +/// object of khaemhat-coa.json with its accounts). The first row holds the headers. +/// +public static class ImportFileReader +{ + /// The most data rows an import takes. + public const int MaxRows = 50_000; + + /// The format name written in khaemhat-coa.json. + public const string ChartFormat = "khaemhat-coa"; + + private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); + + /// The format of a file from its name. + /// The name. + /// The format, or when not supported. + public static TransferFormat? FormatOf(string? fileName) => Path.GetExtension(fileName ?? string.Empty).ToUpperInvariant() switch + { + ".CSV" or ".TXT" => TransferFormat.Csv, + ".XLSX" => TransferFormat.Xlsx, + ".JSON" => TransferFormat.Json, + _ => null, + }; + + /// Reads a file. + /// The name, which gives the format. + /// The content. + /// Cancellation. + /// The file with headers and rows. + /// The format is not supported, or the file is empty, damaged or too large. + public static async Task ReadAsync(string fileName, Stream content, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(fileName); + ArgumentNullException.ThrowIfNull(content); + var format = FormatOf(fileName) ?? throw new ImportFileException(ImportErrors.FileFormat, "Not CSV, XLSX or JSON: " + fileName, null); + using var buffer = new MemoryStream(); + await content.CopyToAsync(buffer, cancellationToken).ConfigureAwait(false); + buffer.Position = 0; + return format switch + { + TransferFormat.Xlsx => await ReadXlsxAsync(fileName, buffer, cancellationToken).ConfigureAwait(false), + TransferFormat.Json => ReadJson(fileName, buffer.ToArray()), + _ => ReadCsv(fileName, buffer.ToArray()), + }; + } + + /// Reads CSV bytes. + /// The name. + /// The content. + /// The file. + /// Empty or too large. + public static ImportFile ReadCsv(string fileName, byte[] bytes) + { + ArgumentNullException.ThrowIfNull(bytes); + string text; + string encoding; + var start = bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF ? 3 : 0; + try + { + text = StrictUtf8.GetString(bytes, start, bytes.Length - start); + encoding = "UTF-8"; + } + catch (DecoderFallbackException) + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + text = Encoding.GetEncoding(1252).GetString(bytes); + encoding = "Windows-1252"; + } + + var separator = Guess(text); + var lines = CsvReader.Parse(text, separator); + return Build(fileName, TransferFormat.Csv, encoding, separator, lines, null); + } + + private static async Task ReadXlsxAsync(string fileName, Stream content, CancellationToken cancellationToken) + { + try + { + var rows = await XlsxReader.ReadAsync(content, cancellationToken).ConfigureAwait(false); + return Build(fileName, TransferFormat.Xlsx, null, null, rows, null); + } + catch (XlsxReadException ex) + { + throw new ImportFileException(ImportErrors.FileUnreadable, ex.Message, ex); + } + } + + private static ImportFile ReadJson(string fileName, byte[] bytes) + { + JsonDocument document; + try + { + document = JsonDocument.Parse(bytes, new JsonDocumentOptions { MaxDepth = 16, AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip }); + } + catch (JsonException ex) + { + throw new ImportFileException(ImportErrors.FileUnreadable, ex.Message, ex); + } + + using (document) + { + var root = document.RootElement; + Dictionary? sections = null; + JsonElement records; + if (root.ValueKind == JsonValueKind.Array) + { + records = root; + } + else if (root.ValueKind == JsonValueKind.Object && root.TryGetProperty("accounts", out var accounts) && accounts.ValueKind == JsonValueKind.Array) + { + records = accounts; + sections = new Dictionary(StringComparer.Ordinal); + foreach (var property in root.EnumerateObject()) + { + if (property.Name != "accounts" && property.Value.ValueKind == JsonValueKind.Array) + { + sections[property.Name] = property.Value.GetArrayLength(); + } + } + } + else + { + throw new ImportFileException(ImportErrors.FileUnreadable, "Neither an array of objects nor a chart of accounts.", null); + } + + var headers = new List(); + var index = new Dictionary(StringComparer.Ordinal); + var objects = new List>(); + foreach (var element in records.EnumerateArray()) + { + if (element.ValueKind != JsonValueKind.Object) + { + throw new ImportFileException(ImportErrors.FileUnreadable, "An entry is not an object.", null); + } + + var values = new Dictionary(StringComparer.Ordinal); + foreach (var property in element.EnumerateObject()) + { + if (index.TryAdd(property.Name, headers.Count)) + { + headers.Add(property.Name); + } + + values[property.Name] = Cell(property.Value); + } + + objects.Add(values); + } + + var rows = new List> { headers }; + rows.AddRange(objects.Select(o => (IReadOnlyList)[.. headers.Select(h => o.GetValueOrDefault(h, string.Empty))])); + return Build(fileName, TransferFormat.Json, "UTF-8", null, rows, sections); + } + } + + private static string Cell(JsonElement value) => value.ValueKind switch + { + JsonValueKind.String => value.GetString() ?? string.Empty, + JsonValueKind.Number => value.GetRawText(), + JsonValueKind.True => "true", + JsonValueKind.False => "false", + JsonValueKind.Null or JsonValueKind.Undefined => string.Empty, + _ => value.GetRawText(), + }; + + private static ImportFile Build(string fileName, TransferFormat format, string? encoding, char? separator, IReadOnlyList> lines, + IReadOnlyDictionary? sections) + { + if (lines.Count == 0 || lines[0].All(string.IsNullOrWhiteSpace)) + { + throw new ImportFileException(ImportErrors.FileEmpty, "No header.", null); + } + + if (lines.Count - 1 > MaxRows) + { + throw new ImportFileException(ImportErrors.FileTooLarge, "More than " + MaxRows.ToString(CultureInfo.InvariantCulture) + " rows.", null); + } + + var headers = lines[0].Select((h, i) => string.IsNullOrWhiteSpace(h) ? "colonna_" + (i + 1).ToString(CultureInfo.InvariantCulture) : h.Trim()).ToList(); + var rows = new List>(lines.Count - 1); + foreach (var line in lines.Skip(1)) + { + if (line.All(string.IsNullOrWhiteSpace)) + { + continue; + } + + rows.Add([.. Enumerable.Range(0, headers.Count).Select(i => i < line.Count ? Unprotect(line[i]) : string.Empty)]); + } + + return new ImportFile(Path.GetFileName(fileName), format, encoding, separator, headers, rows, sections); + } + + // The apostrophe the export puts before text that a spreadsheet would read as a formula (CsvWriter). + private static string Unprotect(string cell) => + cell.Length > 1 && cell[0] == '\'' && cell[1] is '=' or '+' or '-' or '@' ? cell[1..].Trim() : cell.Trim(); + + private static char Guess(string text) + { + var end = text.IndexOfAny(['\r', '\n']); + var first = end < 0 ? text : text[..end]; + return Separators.OrderByDescending(s => first.Count(c => c == s)).First(); + } + + private static readonly char[] Separators = [';', ',', '\t']; +} diff --git a/src/Khaemhat.Application/ImportExport/ImportModel.cs b/src/Khaemhat.Application/ImportExport/ImportModel.cs new file mode 100644 index 0000000..dcda65b --- /dev/null +++ b/src/Khaemhat.Application/ImportExport/ImportModel.cs @@ -0,0 +1,197 @@ +using Khaemhat.Application.Security; + +namespace Khaemhat.Application.ImportExport; + +/// The formats of the guided import and export (SPEC §12.12). +public enum TransferFormat +{ + /// Text with ;, UTF-8 (other separators and Windows-1252 are recognized when reading). + Csv = 0, + + /// Excel workbook, first sheet, headers in the first row. + Xlsx = 1, + + /// JSON: an array of objects keyed by column, or the object of khaemhat-coa.json. + Json = 2, +} + +/// The kind of value of a column, for reading and writing it. +public enum ImportFieldKind +{ + /// Free text. + Text = 0, + + /// A code of another archive or table. + Code = 1, + + /// A decimal number (Italian or invariant notation). + Number = 2, + + /// A date (dd/MM/yyyy, ISO or a spreadsheet serial). + Date = 3, + + /// Yes or no. + Boolean = 4, + + /// One of a list of words. + Choice = 5, +} + +/// A column an entity accepts. +/// The column name used in files and templates (partita_iva). +/// The kind of value. +/// Whether a new record needs it. +/// Other headers recognized by the automatic mapping, already normalized. +/// The words accepted for . +public sealed record ImportField(string Key, ImportFieldKind Kind = ImportFieldKind.Text, bool Required = false, IReadOnlyList? Aliases = null, + IReadOnlyList? Choices = null); + +/// A file read for the import. +/// The file name. +/// The format. +/// The text encoding (CSV), such as UTF-8. +/// The separator (CSV). +/// The headers of the columns. +/// The rows under the headers, each as long as the headers. +/// For khaemhat-coa.json: the other sections with their number of entries. +public sealed record ImportFile(string Name, TransferFormat Format, string? Encoding, char? Separator, IReadOnlyList Headers, + IReadOnlyList> Rows, IReadOnlyDictionary? Sections = null) +{ + /// The number of data rows. + public int Count => Rows.Count; +} + +/// What happens to a row whose code is already in the archive. +public enum ExistingCodeAction +{ + /// The record is updated with the non empty cells of the row. + Update = 0, + + /// The row is skipped. + Skip = 1, +} + +/// What happens to a row without a code. +public enum MissingCodeAction +{ + /// The code comes from the automatic code rules. + Generate = 0, + + /// The row is an error. + Refuse = 1, +} + +/// The options of an import (mockup 077, step 1). +public sealed record ImportOptions +{ + /// Rows whose code exists. + public ExistingCodeAction Existing { get; init; } = ExistingCodeAction.Update; + + /// Rows without a code. + public MissingCodeAction Missing { get; init; } = MissingCodeAction.Generate; + + /// Check the VAT numbers of EU parties on VIES while importing. + public bool VerifyVat { get; init; } + + /// Fill the city from the postal code (and the postal code from the city) when one is missing. + public bool FillFromPostalCode { get; init; } = true; +} + +/// Who imports, where and how: what a target needs besides the rows. +/// Who imports. +/// The company. +/// The options. +public sealed record ImportContext(Actor Actor, string CompanyCode, ImportOptions Options); + +/// A row of the file with the cells of the mapped columns by field key. +/// The line in the file, counting the header as line 1. +/// The trimmed cells by field key; empty cells are left out. +public sealed record ImportRow(int Line, IReadOnlyDictionary Values) +{ + /// The cell of a field, or when empty or not mapped. + /// The field. + /// The text. + public string? this[string key] => Values.TryGetValue(key, out var value) ? value : null; +} + +/// The outcome of a row in the preview (mockup 077: OK, avviso, errore). +public enum ImportOutcome +{ + /// Importable. + Ok = 0, + + /// Importable, with a correction proposed or a remark. + Warning = 1, + + /// Not importable. + Error = 2, +} + +/// What the import does with a row. +public enum ImportAction +{ + /// A new record. + Create = 0, + + /// An existing record changes. + Update = 1, + + /// Nothing (existing code to skip, or an error). + Skip = 2, +} + +/// A remark on a row: a text code with the field it concerns. +/// The field key, or empty for the whole row. +/// The text code (an error code of the services or import.*). +/// A warning instead of an error. +/// A value to show in the text ({0}), such as the code not found or the city proposed. +public sealed record ImportMessage(string Field, string Code, bool IsWarning = false, string? Value = null); + +/// The check of a row. +/// The line in the file. +/// The code or description that identifies the row in the preview. +/// What the import will do. +/// The remarks. +public sealed record ImportRowResult(int Line, string Key, ImportAction Action, IReadOnlyList Messages) +{ + /// The outcome from the remarks. + public ImportOutcome Outcome => + Messages.Any(m => !m.IsWarning) ? ImportOutcome.Error : Messages.Count > 0 ? ImportOutcome.Warning : ImportOutcome.Ok; +} + +/// The preview of an import (mockup 077, steps 3 and 4). +/// The entity. +/// The checked rows, in file order. +/// Whether the entity can be written now (opening stock and chart of accounts only check, until M6 and M7). +public sealed record ImportPreview(string Target, IReadOnlyList Rows, bool CanApply) +{ + /// Rows that will create a record. + public int Creates => Rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Create); + + /// Rows that will update a record. + public int Updates => Rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Update); + + /// Rows skipped on purpose. + public int Skips => Rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Skip); + + /// Rows with errors. + public int Errors => Rows.Count(r => r.Outcome == ImportOutcome.Error); + + /// Rows with warnings only. + public int Warnings => Rows.Count(r => r.Outcome == ImportOutcome.Warning); + + /// Rows the import writes. + public int Importable => Creates + Updates; +} + +/// The result of an import. +/// The entity. +/// Records created. +/// Records updated. +/// Rows skipped on purpose. +/// Every row with its final outcome; rows refused while writing carry their errors. +public sealed record ImportReport(string Target, int Created, int Updated, int Skipped, IReadOnlyList Rows) +{ + /// Rows not imported because of errors. + public int Failed => Rows.Count(r => r.Outcome == ImportOutcome.Error); +} diff --git a/src/Khaemhat.Application/ImportExport/ImportService.cs b/src/Khaemhat.Application/ImportExport/ImportService.cs new file mode 100644 index 0000000..ed29dca --- /dev/null +++ b/src/Khaemhat.Application/ImportExport/ImportService.cs @@ -0,0 +1,375 @@ +using System.Text.Json; +using Khaemhat.Application.Licensing; +using Khaemhat.Application.Security; +using Khaemhat.Core.Logging; +using Khaemhat.Infrastructure.Files; +using Microsoft.Extensions.Logging; + +namespace Khaemhat.Application.ImportExport; + +/// +/// The guided import and export (SPEC §11.7, §12.12, mockup 077, ADR 0031): the entities the licence allows, the +/// automatic mapping of the columns, the preview that checks every row as if typed in its record, the import of the +/// rows without errors, the error report, the export with the same columns and the empty templates. +/// +public sealed partial class ImportService +{ + private static readonly JsonWriterOptions JsonOptions = new() { Indented = true }; + + private readonly IReadOnlyList _targets; + private readonly ILicenseGate _license; + private readonly PermissionService _permissions; + private readonly ILogger _logger; + + /// Creates the service. + /// The entities. + /// The licence. + /// The permissions and the user flags. + /// The log. + public ImportService(IEnumerable targets, ILicenseGate license, PermissionService permissions, ILogger logger) + { + ArgumentNullException.ThrowIfNull(targets); + ArgumentNullException.ThrowIfNull(license); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(logger); + _targets = [.. targets]; + _license = license; + _permissions = permissions; + _logger = logger; + } + + /// The entities whose module is licensed, in the order of the screen. + public IReadOnlyList Targets => [.. _targets.Where(t => _license.IsModuleActive(t.ModuleCode))]; + + /// A licensed entity by key. + /// The key. + /// The entity. + /// Unknown or not licensed (). + public IImportTarget Target(string key) => + Targets.FirstOrDefault(t => string.Equals(t.Key, key, StringComparison.OrdinalIgnoreCase)) + ?? throw new ImportFileException(ImportErrors.TargetUnknown, "Unknown import: " + key, null); + + /// + /// The field of each column of a file, by name or alias ignoring case, accents and punctuation; a field goes to one + /// column only. + /// + /// The entity. + /// The headers. + /// The field key per column, or for columns to ignore. + public static IReadOnlyList SuggestMapping(IImportTarget target, IReadOnlyList headers) + { + ArgumentNullException.ThrowIfNull(target); + ArgumentNullException.ThrowIfNull(headers); + var taken = new HashSet(StringComparer.Ordinal); + var mapping = new string?[headers.Count]; + for (var pass = 0; pass < 2; pass++) + { + for (var i = 0; i < headers.Count; i++) + { + if (mapping[i] is not null) + { + continue; + } + + var header = ImportValues.Normalize(headers[i]); + var field = target.Fields.FirstOrDefault(f => !taken.Contains(f.Key) + && (pass == 0 ? f.Key == header : (f.Aliases ?? []).Any(a => ImportValues.Normalize(a) == header))); + if (field is not null) + { + mapping[i] = field.Key; + taken.Add(field.Key); + } + } + } + + return mapping; + } + + /// The rows of a file with the cells of the mapped columns. + /// The file. + /// The field key per column, or . + /// The rows, line numbers counting the header as line 1. + public static IReadOnlyList Rows(ImportFile file, IReadOnlyList mapping) + { + ArgumentNullException.ThrowIfNull(file); + ArgumentNullException.ThrowIfNull(mapping); + var rows = new List(file.Count); + for (var r = 0; r < file.Count; r++) + { + var values = new Dictionary(StringComparer.Ordinal); + var cells = file.Rows[r]; + for (var c = 0; c < mapping.Count && c < cells.Count; c++) + { + if (mapping[c] is { } key && !string.IsNullOrWhiteSpace(cells[c])) + { + values.TryAdd(key, cells[c].Trim()); + } + } + + rows.Add(new ImportRow(r + 2, values)); + } + + return rows; + } + + /// Checks a file without writing (steps 2 and 3 of the screen). + /// Who imports. + /// The company. + /// The entity. + /// The file. + /// The field per column. + /// The options. + /// Cancellation. + /// The preview. + public async Task PreviewAsync(Actor actor, string companyCode, string targetKey, ImportFile file, IReadOnlyList mapping, ImportOptions options, + CancellationToken cancellationToken = default) + { + var target = Target(targetKey); + var context = new ImportContext(actor, companyCode, options ?? new ImportOptions()); + var rows = await target.CheckAsync(context, Rows(file, mapping), cancellationToken).ConfigureAwait(false); + return new ImportPreview(target.Key, rows, target.CanApply); + } + + /// Imports the rows without errors (step 4); rows with errors are left out and reported. + /// Who imports. + /// The company. + /// The entity. + /// The file. + /// The field per column. + /// The options. + /// Cancellation. + /// What was done. + /// The entity is only checked for now (). + public async Task ImportAsync(Actor actor, string companyCode, string targetKey, ImportFile file, IReadOnlyList mapping, ImportOptions options, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(file); + var target = Target(targetKey); + if (!target.CanApply) + { + throw new ImportFileException(ImportErrors.CheckOnly, "Only checked for now: " + target.Key, null); + } + + var context = new ImportContext(actor, companyCode, options ?? new ImportOptions()); + var rows = await target.ApplyAsync(context, Rows(file, mapping), cancellationToken).ConfigureAwait(false); + var report = new ImportReport( + target.Key, + rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Create), + rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Update), + rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Skip), + rows); + using (_logger.BeginScope(LogSections.Scope(LogSection.System))) + { + LogImported(_logger, target.Key, file.Name, companyCode, actor.UserName, report.Created, report.Updated, report.Skipped, report.Failed); + } + + return report; + } + + /// Writes the rows with errors and warnings as CSV (button Scarica report errori). + /// The checked rows. + /// The text of a remark, in the language of the user. + /// The headers: line, key, column, outcome, message. + /// Where to write. + /// Cancellation. + /// A task. + public static async Task WriteErrorReportAsync(IReadOnlyList rows, Func text, + IReadOnlyList labels, Stream output, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(rows); + ArgumentNullException.ThrowIfNull(text); + ArgumentNullException.ThrowIfNull(labels); + await using var csv = new CsvWriter(output, CsvOptions.Italian, leaveOpen: true); + await csv.WriteRowAsync(labels, cancellationToken).ConfigureAwait(false); + foreach (var row in rows) + { + foreach (var message in row.Messages) + { + var (outcome, line) = text(row, message); + await csv.WriteRowAsync([row.Line, row.Key, message.Field, outcome, line], cancellationToken).ConfigureAwait(false); + } + } + + await csv.FlushAsync(cancellationToken).ConfigureAwait(false); + } + + /// Exports an entity with the columns of its import, so that the file can be imported again. + /// Who exports: needs the export permission of the entity and the can export flag. + /// The company. + /// The entity. + /// The format. + /// Where to write. + /// Cancellation. + /// The number of records written. + /// The user cannot export. + public async Task ExportAsync(Actor actor, string companyCode, string targetKey, TransferFormat format, Stream output, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var target = Target(targetKey); + if (!(await _permissions.GetAsync(actor, cancellationToken).ConfigureAwait(false)).Flags.CanExport) + { + throw new AccessDeniedException(SecurityErrors.PermissionDenied, "The user cannot export."); + } + + var rows = target.CanExport + ? await target.ExportAsync(new ImportContext(actor, companyCode, new ImportOptions()), cancellationToken).ConfigureAwait(false) + : []; + await WriteAsync(target, format, rows, output, cancellationToken).ConfigureAwait(false); + using (_logger.BeginScope(LogSections.Scope(LogSection.System))) + { + LogExported(_logger, target.Key, format, companyCode, actor.UserName, rows.Count); + } + + return rows.Count; + } + + /// Writes the empty template of an entity: the headers only (for JSON, one object with empty values). + /// The entity. + /// The format. + /// Where to write. + /// Cancellation. + /// A task. + public static Task WriteTemplateAsync(IImportTarget target, TransferFormat format, Stream output, CancellationToken cancellationToken = default) => + WriteAsync(target, format, [], output, cancellationToken); + + /// The name of an export or template file (clienti-2026-11-12.csv, modello-clienti.xlsx). + /// The entity. + /// The format. + /// The day of an export, or for a template. + /// The file name. + public static string FileName(string targetKey, TransferFormat format, DateOnly? date) + { + var extension = format switch + { + TransferFormat.Xlsx => ".xlsx", + TransferFormat.Json => ".json", + _ => ".csv", + }; + return date is { } day + ? targetKey + "-" + day.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture) + extension + : "modello-" + targetKey + extension; + } + + /// The media type of a format. + /// The format. + /// The media type. + public static string MediaType(TransferFormat format) => format switch + { + TransferFormat.Xlsx => XlsxWriter.MediaType, + TransferFormat.Json => "application/json", + _ => "text/csv", + }; + + private static async Task WriteAsync(IImportTarget target, TransferFormat format, IReadOnlyList> rows, Stream output, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(target); + ArgumentNullException.ThrowIfNull(output); + var headers = target.Fields.Select(f => f.Key).ToList(); + switch (format) + { + case TransferFormat.Xlsx: + await using (var xlsx = await XlsxWriter.CreateAsync(output, leaveOpen: true, cancellationToken: cancellationToken).ConfigureAwait(false)) + { + await xlsx.StartSheetAsync(target.Key, [.. target.Fields.Select(Column)], cancellationToken).ConfigureAwait(false); + foreach (var row in rows) + { + await xlsx.WriteRowAsync(row, cancellationToken).ConfigureAwait(false); + } + + await xlsx.CompleteAsync(cancellationToken).ConfigureAwait(false); + } + + break; + case TransferFormat.Json: + await WriteJsonAsync(target, headers, rows, output, cancellationToken).ConfigureAwait(false); + break; + default: + await using (var csv = new CsvWriter(output, CsvOptions.Italian, leaveOpen: true)) + { + await csv.WriteRowAsync(headers, cancellationToken).ConfigureAwait(false); + foreach (var row in rows) + { + await csv.WriteRowAsync(row, cancellationToken).ConfigureAwait(false); + } + + await csv.FlushAsync(cancellationToken).ConfigureAwait(false); + } + + break; + } + } + + private static XlsxColumn Column(ImportField field) => new(field.Key, field.Kind switch + { + ImportFieldKind.Text => 28, + ImportFieldKind.Number or ImportFieldKind.Date => 14, + _ => 16, + }); + + private static async Task WriteJsonAsync(IImportTarget target, List headers, IReadOnlyList> rows, Stream output, + CancellationToken cancellationToken) + { + await using var json = new Utf8JsonWriter(output, JsonOptions); + var chart = target is ChartOfAccountsImportTarget; + if (chart) + { + json.WriteStartObject(); + json.WriteString("format", ImportFileReader.ChartFormat); + json.WriteNumber("version", 1); + json.WritePropertyName("accounts"); + } + + json.WriteStartArray(); + IEnumerable> objects = rows.Count > 0 ? rows : [new object?[headers.Count]]; + foreach (var row in objects) + { + json.WriteStartObject(); + for (var i = 0; i < headers.Count; i++) + { + var value = i < row.Count ? row[i] : null; + switch (value) + { + case null: + json.WriteString(headers[i], string.Empty); + break; + case decimal number: + json.WriteNumber(headers[i], number); + break; + case bool flag: + json.WriteBoolean(headers[i], flag); + break; + case DateOnly day: + json.WriteString(headers[i], day.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture)); + break; + default: + json.WriteString(headers[i], Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture)); + break; + } + } + + json.WriteEndObject(); + } + + json.WriteEndArray(); + if (chart) + { + foreach (var section in new[] { "statementLines", "journalTemplates", "mappings" }) + { + json.WriteStartArray(section); + json.WriteEndArray(); + } + + json.WriteEndObject(); + } + + await json.FlushAsync(cancellationToken).ConfigureAwait(false); + } + + [LoggerMessage(EventId = 7101, Level = LogLevel.Information, + Message = "Import {Target} from {File} in {Company} by {User}: {Created} created, {Updated} updated, {Skipped} skipped, {Failed} with errors")] + private static partial void LogImported(ILogger logger, string target, string file, string company, string user, int created, int updated, int skipped, int failed); + + [LoggerMessage(EventId = 7102, Level = LogLevel.Information, Message = "Export {Target} as {Format} from {Company} by {User}: {Count} records")] + private static partial void LogExported(ILogger logger, string target, TransferFormat format, string company, string user, int count); +} diff --git a/src/Khaemhat.Application/ImportExport/ImportTarget.cs b/src/Khaemhat.Application/ImportExport/ImportTarget.cs new file mode 100644 index 0000000..ccd0664 --- /dev/null +++ b/src/Khaemhat.Application/ImportExport/ImportTarget.cs @@ -0,0 +1,442 @@ +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.ImportExport; + +/// +/// An entity of the guided import and export (SPEC §12.12): its columns, the check of the rows as if typed in its +/// record, the writing through its own service, and the export with the same columns so that a file exported can be +/// imported again. +/// +public interface IImportTarget +{ + /// The key in addresses and texts (clienti, piano-dei-conti). + string Key { get; } + + /// The licence module the entity belongs to. + string ModuleCode { get; } + + /// The permission to import it (the write permission of its record). + string Permission { get; } + + /// The permission to export it (besides the can export flag of the user). + string ExportPermission { get; } + + /// Whether rows can be written now; otherwise the file is only checked (opening stock until M6, chart of accounts until M7). + bool CanApply { get; } + + /// Whether there are records to export now. + bool CanExport { get; } + + /// The columns, in the order of templates and exports. + IReadOnlyList Fields { get; } + + /// Checks the rows without writing. + /// Who, where, how. + /// The rows. + /// Cancellation. + /// A result per row, in order. + Task> CheckAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken); + + /// Writes the rows without errors, each like a save of its record. + /// Who, where, how. + /// The rows. + /// Cancellation. + /// A result per row, in order, with what was done. + Task> ApplyAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken); + + /// The records as rows of cells in the order of . + /// Who, where. + /// Cancellation. + /// The rows. + Task>> ExportAsync(ImportContext context, CancellationToken cancellationToken); +} + +/// Reads the cells of a row as values, adding a remark for every cell that is not what its field wants. +/// The row. +/// Where the remarks go. +public sealed class CellReader(ImportRow row, List messages) +{ + /// The row. + public ImportRow Row => row; + + /// The remarks so far. + public List Messages => messages; + + /// Whether the cell has a value. + /// The field. + /// when not empty. + public bool Has(string key) => row[key] is not null; + + /// The text of a cell. + /// The field. + /// The text, or . + public string? Text(string key) => row[key]; + + /// A number. + /// The field. + /// The number, or when empty or wrong (with a remark). + public decimal? Number(string key) + { + if (row[key] is not { } text) + { + return null; + } + + if (ImportValues.TryNumber(text, out var value)) + { + return value; + } + + messages.Add(new(key, ImportErrors.Number, Value: text)); + return null; + } + + /// A date. + /// The field. + /// The date, or when empty or wrong (with a remark). + public DateOnly? Date(string key) + { + if (row[key] is not { } text) + { + return null; + } + + if (ImportValues.TryDate(text, out var value)) + { + return value; + } + + messages.Add(new(key, ImportErrors.Date, Value: text)); + return null; + } + + /// Yes or no. + /// The field. + /// The value, or when empty or wrong (with a remark). + public bool? Boolean(string key) + { + if (row[key] is not { } text) + { + return null; + } + + if (ImportValues.TryBoolean(text, out var value)) + { + return value; + } + + messages.Add(new(key, ImportErrors.Boolean, Value: text)); + return null; + } + + /// One of the words of a field. + /// The field with its choices. + /// The position of the word, or when empty or unknown (with a remark). + public int? Choice(ImportField field) + { + ArgumentNullException.ThrowIfNull(field); + if (row[field.Key] is not { } text) + { + return null; + } + + var choices = field.Choices ?? []; + var index = ImportValues.Choice(text, choices); + if (index >= 0) + { + return index; + } + + messages.Add(new(field.Key, ImportErrors.Choice, Value: string.Join(", ", choices))); + return null; + } + + /// The id of a code of another archive or table. + /// The field. + /// The codes. + /// The id, or when empty or unknown (with a remark). + public long? Code(string key, CodeIndex index) + { + ArgumentNullException.ThrowIfNull(index); + if (row[key] is not { } code) + { + return null; + } + + if (index.Find(code) is { } id) + { + return id; + } + + messages.Add(new(key, ImportErrors.CodeUnknown, Value: code)); + return null; + } +} + +/// The ids of the records of an archive or table by code, ignoring case. +public sealed class CodeIndex +{ + private readonly Dictionary _ids = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _codes = []; + + /// Creates an index. + /// The codes with their ids. + public CodeIndex(IEnumerable<(string Code, long Id)> entries) + { + ArgumentNullException.ThrowIfNull(entries); + foreach (var (code, id) in entries) + { + _ids.TryAdd(code, id); + _codes[id] = code; + } + } + + /// The number of codes. + public int Count => _ids.Count; + + /// Loads the codes of a table of the company. + /// The table. + /// The unit of work. + /// Cancellation. + /// The index. + public static async Task LoadAsync(IUnitOfWork uow, CancellationToken cancellationToken) + where T : CodedEntity, new() + { + ArgumentNullException.ThrowIfNull(uow); + var rows = await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false); + return new CodeIndex(rows.Items.Select(r => (r.Code, r.Id))); + } + + /// The id of a code. + /// The code. + /// The id, or . + public long? Find(string? code) => code is not null && _ids.TryGetValue(code.Trim(), out var id) ? id : null; + + /// The code of an id. + /// The id. + /// The code, or . + public string? CodeOf(long? id) => id is { } key && _codes.TryGetValue(key, out var code) ? code : null; + + /// Adds a code written meanwhile. + /// The code. + /// The id. + public void Add(string code, long id) + { + ArgumentNullException.ThrowIfNull(code); + _ids[code] = id; + _codes[id] = code; + } +} + +/// +/// The common steps of the entities written as records (parties, items): each row becomes a record, new or read by its +/// code, checked by the service of the record and saved by it, so the import obeys the same rules as the screen. +/// +/// The record. +/// What is loaded once per check or import (codes of tables and archives). +public abstract class RecordImportTarget : IImportTarget + where TRecord : class +{ + /// + public abstract string Key { get; } + + /// + public abstract string ModuleCode { get; } + + /// + public abstract string Permission { get; } + + /// + public abstract string ExportPermission { get; } + + /// + public bool CanApply => true; + + /// + public bool CanExport => true; + + /// + public abstract IReadOnlyList Fields { get; } + + /// The column with the code of the record. + protected virtual string CodeField => "codice"; + + /// + public Task> CheckAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) => + RunAsync(context, rows, write: false, cancellationToken); + + /// + public Task> ApplyAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) => + RunAsync(context, rows, write: true, cancellationToken); + + /// + public abstract Task>> ExportAsync(ImportContext context, CancellationToken cancellationToken); + + /// Loads what every row needs, checking a permission. + /// Who, where, how. + /// The permission demanded (to import or to export). + /// Cancellation. + /// The state. + protected abstract Task LoadAsync(ImportContext context, string permission, CancellationToken cancellationToken); + + /// The id of an existing record with a code, or ; a remark refuses the code (another kind). + /// The state. + /// The code. + /// Where remarks go. + /// The id. + protected abstract long? Existing(TState state, string code, List messages); + + /// A new record, or an existing one read by id. + /// Who, where. + /// The id, or for a new record. + /// Cancellation. + /// The record. + protected abstract Task OpenAsync(ImportContext context, long? id, CancellationToken cancellationToken); + + /// Copies the cells of a row into the record; a code given for a new record is set too. + /// Who, where, how. + /// The state. + /// The record. + /// The row with its remarks. + /// Whether the record is new. + /// Cancellation. + /// A task. + protected abstract Task FillAsync(ImportContext context, TState state, TRecord record, CellReader cells, bool isNew, CancellationToken cancellationToken); + + /// Checks a record with the rules of its service. + /// Who, where. + /// The record. + /// Whether the record is new (its code is checked against the code rules). + /// Cancellation. + /// The problems. + protected abstract Task> ValidateAsync(ImportContext context, TRecord record, bool isNew, CancellationToken cancellationToken); + + /// Saves a record with its service. + /// Who, where, how. + /// The record. + /// Cancellation. + /// The code and id given by the save. + protected abstract Task<(string Code, long Id)> SaveAsync(ImportContext context, TRecord record, CancellationToken cancellationToken); + + /// What identifies the row in the preview (code, else description). + /// The row. + /// The text. + protected abstract string Label(ImportRow row); + + /// Records a code saved, so that later rows find it. + /// The state. + /// The code. + /// The id. + protected abstract void Remember(TState state, string code, long id); + + /// The column of a field of the service (VatNumber, Fiscal.RecipientCode); empty for the row. + /// The field named by the service. + /// The column key. + protected abstract string ColumnOf(string serviceField); + + private async Task> RunAsync(ImportContext context, IReadOnlyList rows, bool write, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(rows); + var state = await LoadAsync(context, Permission, cancellationToken).ConfigureAwait(false); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + var results = new List(rows.Count); + foreach (var row in rows) + { + cancellationToken.ThrowIfCancellationRequested(); + var messages = new List(); + var cells = new CellReader(row, messages); + var code = row[CodeField]; + long? id = null; + if (code is not null) + { + if (!seen.Add(code)) + { + messages.Add(new(CodeField, ImportErrors.CodeRepeated, Value: code)); + results.Add(new(row.Line, Label(row), ImportAction.Skip, messages)); + continue; + } + + id = Existing(state, code, messages); + if (messages.Count > 0) + { + results.Add(new(row.Line, Label(row), ImportAction.Skip, messages)); + continue; + } + + if (id is not null && context.Options.Existing == ExistingCodeAction.Skip) + { + results.Add(new(row.Line, Label(row), ImportAction.Skip, [new(CodeField, ImportErrors.CodeExists, IsWarning: true, Value: code)])); + continue; + } + } + else if (context.Options.Missing == MissingCodeAction.Refuse) + { + messages.Add(new(CodeField, ImportErrors.CodeMissing)); + results.Add(new(row.Line, Label(row), ImportAction.Skip, messages)); + continue; + } + + var isNew = id is null; + var action = isNew ? ImportAction.Create : ImportAction.Update; + var record = await OpenAsync(context, id, cancellationToken).ConfigureAwait(false); + if (record is null) + { + messages.Add(new(CodeField, ImportErrors.WriteFailed, Value: code)); + results.Add(new(row.Line, Label(row), ImportAction.Skip, messages)); + continue; + } + + await FillAsync(context, state, record, cells, isNew, cancellationToken).ConfigureAwait(false); + if (isNew) + { + messages.AddRange(Fields.Where(f => f.Required && !cells.Has(f.Key) && messages.All(m => m.Field != f.Key)) + .Select(f => new ImportMessage(f.Key, ImportErrors.Required))); + } + + if (messages.All(m => m.IsWarning)) + { + messages.AddRange((await ValidateAsync(context, record, isNew, cancellationToken).ConfigureAwait(false)) + .Select(p => new ImportMessage(ColumnOf(p.Field), p.Code, p.IsWarning))); + } + + if (write && messages.All(m => m.IsWarning)) + { + try + { + var (savedCode, savedId) = await SaveAsync(context, record, cancellationToken).ConfigureAwait(false); + Remember(state, savedCode, savedId); + } + catch (ValidationFailedException ex) + { + messages.AddRange(ex.Errors.Select(TableErrors.Split).Select(e => new ImportMessage(ColumnOf(e.Field), e.Code))); + } + catch (Core.Common.ConcurrencyException) + { + messages.Add(new(string.Empty, ImportErrors.WriteFailed)); + } + } + + results.Add(new(row.Line, Label(row), messages.Any(m => !m.IsWarning) ? ImportAction.Skip : action, messages)); + } + + return results; + } +} + +/// Splits the Field:code errors of . +internal static class TableErrors +{ + /// Splits an error. + /// The error. + /// The field (empty for the record) and the code. + public static (string Field, string Code) Split(string error) + { + var colon = error.LastIndexOf(':'); + return colon < 0 ? (string.Empty, error) : (error[..colon], error[(colon + 1)..]); + } +} diff --git a/src/Khaemhat.Application/ImportExport/ImportValues.cs b/src/Khaemhat.Application/ImportExport/ImportValues.cs new file mode 100644 index 0000000..3c65a97 --- /dev/null +++ b/src/Khaemhat.Application/ImportExport/ImportValues.cs @@ -0,0 +1,274 @@ +using System.Globalization; +using System.Text; + +namespace Khaemhat.Application.ImportExport; + +/// The text codes of the import remarks (import.*), shown by the screen with the field and the value. +public static class ImportErrors +{ + /// The file is not CSV, XLSX or JSON. + public const string FileFormat = "import.file.format"; + + /// The file has no header or no rows. + public const string FileEmpty = "import.file.empty"; + + /// The file cannot be read (damaged spreadsheet, invalid JSON). + public const string FileUnreadable = "import.file.unreadable"; + + /// The file has more rows than an import takes. + public const string FileTooLarge = "import.file.too-large"; + + /// The entity is unknown or not licensed. + public const string TargetUnknown = "import.target.unknown"; + + /// The entity is only checked for now (opening stock until M6, chart of accounts until M7). + public const string CheckOnly = "import.target.check-only"; + + /// A required column of a new record is empty or not mapped. + public const string Required = "import.value.required"; + + /// Not a number. + public const string Number = "import.value.number"; + + /// Not a date. + public const string Date = "import.value.date"; + + /// Not yes or no. + public const string Boolean = "import.value.boolean"; + + /// Not one of the words accepted ({0} lists them). + public const string Choice = "import.value.choice"; + + /// A code of another archive or table that does not exist ({0}). + public const string CodeUnknown = "import.value.code-unknown"; + + /// The row has no code and the options do not generate it. + public const string CodeMissing = "import.code.missing"; + + /// The same code is on an earlier row of the file. + public const string CodeRepeated = "import.code.repeated"; + + /// The code exists and the options skip existing codes (a remark, not an error). + public const string CodeExists = "import.code.exists"; + + /// The code belongs to a party of another kind (a supplier among the customers). + public const string OtherKind = "import.party.other-kind"; + + /// The city was filled from the postal code ({0}). + public const string CityFilled = "import.filled.city"; + + /// The postal code was filled from the city ({0}). + public const string PostalCodeFilled = "import.filled.postal-code"; + + /// A price row names both a list and a customer, or neither. + public const string PriceTarget = "import.price.target"; + + /// Opening stock of an item that is not stocked goods. + public const string NotStocked = "import.stock.not-stocked"; + + /// The quantity must be more than zero. + public const string Positive = "import.value.positive"; + + /// The record could not be written (someone changed it meanwhile, or an unexpected rule). + public const string WriteFailed = "import.write.failed"; + + /// The level of an account is not 1 to 3, or not the number of parts of its code. + public const string AccountLevel = "import.coa.level"; + + /// The parent of an account is not the code without its last part, or is not in the file ({0}). + public const string AccountParent = "import.coa.parent"; + + /// An account has a nature other than its parent's. + public const string AccountNature = "import.coa.nature"; + + /// An account with sub-accounts is marked as postable. + public const string AccountPostable = "import.coa.postable"; + + /// A leaf account is not marked as postable (a remark). + public const string AccountLeaf = "import.coa.leaf"; + + /// A flag letter is not M, I, P, C or X ({0}). + public const string AccountFlag = "import.coa.flag"; +} + +/// The cells of the import as values, and the values of the export as cells. +public static class ImportValues +{ + private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT"); + + private static readonly string[] DateFormats = + ["dd/MM/yyyy", "d/M/yyyy", "dd/MM/yy", "d/M/yy", "dd-MM-yyyy", "d-M-yyyy", "dd.MM.yyyy", "yyyy-MM-dd", "yyyy/MM/dd", "yyyyMMdd", "yyyy-MM-ddTHH:mm:ss"]; + + private static readonly HashSet Yes = new(StringComparer.Ordinal) { "si", "s", "yes", "y", "x", "1", "true", "vero", "v" }; + + private static readonly HashSet No = new(StringComparer.Ordinal) { "no", "n", "0", "false", "falso", "f", "-" }; + + private static readonly DateTime Epoch = new(1899, 12, 30, 0, 0, 0, DateTimeKind.Unspecified); + + /// + /// A header or a word as compared by the mapping and the choices: lower case, no accents, every run of other + /// characters as one underscore (Partita IVA and partita-iva both give partita_iva). + /// + /// The text. + /// The normalized text. + public static string Normalize(string? text) + { + if (string.IsNullOrWhiteSpace(text)) + { + return string.Empty; + } + + var builder = new StringBuilder(text.Length); + var underscore = false; + foreach (var c in text.Trim().Normalize(NormalizationForm.FormD)) + { + if (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.NonSpacingMark) + { + continue; + } + + if (char.IsAsciiLetterOrDigit(c)) + { + if (underscore && builder.Length > 0) + { + builder.Append('_'); + } + + builder.Append(char.ToLowerInvariant(c)); + underscore = false; + } + else + { + underscore = true; + } + } + + return builder.ToString(); + } + + /// + /// Reads a number written the Italian way (1.234,56, € 12,5) or the machine way (1234.56): + /// with both marks the last one is the decimal one; a single point alone is the decimal mark (as spreadsheets and JSON + /// write it), several points alone group thousands; percent signs, currency signs and spaces are ignored. + /// + /// The cell. + /// The number. + /// when the cell is a number. + public static bool TryNumber(string? text, out decimal value) + { + value = 0; + if (string.IsNullOrWhiteSpace(text)) + { + return false; + } + + var clean = new StringBuilder(text.Length); + foreach (var c in text) + { + if (char.IsAsciiDigit(c) || c is ',' or '.' or '-' or '+' or 'e' or 'E') + { + clean.Append(c); + } + else if (!char.IsWhiteSpace(c) && c is not ('€' or '%' or '\'' or ' ' or ' ')) + { + return false; + } + } + + var s = clean.ToString(); + var comma = s.LastIndexOf(','); + var point = s.LastIndexOf('.'); + if (comma >= 0 && point >= 0) + { + s = comma > point ? s.Replace(".", string.Empty, StringComparison.Ordinal).Replace(',', '.') : s.Replace(",", string.Empty, StringComparison.Ordinal); + } + else if (comma >= 0) + { + s = s.Count(c => c == ',') > 1 ? s.Replace(",", string.Empty, StringComparison.Ordinal) : s.Replace(',', '.'); + } + else if (point >= 0 && s.Count(c => c == '.') > 1) + { + s = s.Replace(".", string.Empty, StringComparison.Ordinal); + } + + return decimal.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out value); + } + + /// Reads a date: dd/MM/yyyy and its variants, ISO, or a spreadsheet serial number. + /// The cell. + /// The date. + /// when the cell is a date. + public static bool TryDate(string? text, out DateOnly value) + { + value = default; + if (string.IsNullOrWhiteSpace(text)) + { + return false; + } + + var s = text.Trim(); + if (s.Length > 10 && s[10] is ' ' or 'T') + { + s = s[..10]; + } + + if (DateTime.TryParseExact(s, DateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out var day)) + { + value = DateOnly.FromDateTime(day); + return true; + } + + if (s.All(char.IsAsciiDigit) && s.Length <= 5 && int.TryParse(s, NumberStyles.None, CultureInfo.InvariantCulture, out var serial) && serial > 0) + { + value = DateOnly.FromDateTime(Epoch.AddDays(serial)); + return true; + } + + return false; + } + + /// Reads yes or no: sì, x, 1, VERO, true... and no, 0, FALSO... + /// The cell. + /// The value. + /// when the cell is yes or no. + public static bool TryBoolean(string? text, out bool value) + { + var word = Normalize(text); + value = Yes.Contains(word); + return value || No.Contains(word); + } + + /// Finds a word among the choices of a field, ignoring case, accents, spaces and punctuation (P.A. is pa). + /// The cell. + /// The words accepted, in the order of the values they stand for. + /// The position of the word, or -1. + public static int Choice(string? text, IReadOnlyList choices) + { + ArgumentNullException.ThrowIfNull(choices); + var word = Normalize(text).Replace("_", string.Empty, StringComparison.Ordinal); + for (var i = 0; i < choices.Count; i++) + { + if (Normalize(choices[i]).Replace("_", string.Empty, StringComparison.Ordinal) == word) + { + return i; + } + } + + return -1; + } + + /// A number for a text cell of the export, the Italian way without thousands marks (1234,5). + /// The number. + /// The text, or . + public static string? Text(decimal? value) => value?.ToString("0.############", Italian); + + /// A date for a text cell of the export (dd/MM/yyyy). + /// The date. + /// The text, or . + public static string? Text(DateOnly? value) => value?.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture); + + /// Yes or no for a text cell of the export. + /// The value. + /// sì or no. + public static string Text(bool value) => value ? "sì" : "no"; +} diff --git a/src/Khaemhat.Application/ImportExport/ItemsImportTarget.cs b/src/Khaemhat.Application/ImportExport/ItemsImportTarget.cs new file mode 100644 index 0000000..1ba8c8c --- /dev/null +++ b/src/Khaemhat.Application/ImportExport/ItemsImportTarget.cs @@ -0,0 +1,274 @@ +using Khaemhat.Application.Items; +using Khaemhat.Application.Modules; +using Khaemhat.Application.Querying; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Items; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.ImportExport; + +/// +/// The items (SPEC §12.12): each row is an item read by its code, or a new one with the values proposed by the record, +/// filled with the cells of the row, checked and saved by . Empty cells keep the values of an +/// existing item; units, bar codes, prices and suppliers of the record are left as they are. +/// +/// The items. +/// The automatic codes. +/// Opens the company databases (codes of the tables). +/// Checks the permission to import. +public sealed class ItemsImportTarget(ItemService items, CodeRuleService codes, IUnitOfWorkFactory factory, PermissionService permissions) + : RecordImportTarget +{ + /// The words of tipo, in the order of . + public static readonly IReadOnlyList KindWords = ["merce", "servizio", "spesa", "descrittivo", "cespite"]; + + private static readonly ImportField[] ItemFields = + [ + new("codice", ImportFieldKind.Code, Aliases: ["cod", "codice_articolo", "cod_articolo", "sku", "code"]), + new("descrizione", Required: true, Aliases: ["descr", "description", "nome"]), + new("descrizione_estesa", Aliases: ["descrizione_lunga", "note_descrizione"]), + new("tipo", ImportFieldKind.Choice, Aliases: ["tipologia", "tipo_articolo"], Choices: KindWords), + new("categoria", ImportFieldKind.Code, Aliases: ["famiglia", "categoria_merceologica"]), + new("um", ImportFieldKind.Code, Aliases: ["unita_misura", "unita_di_misura", "u_m"]), + new("iva_vendite", ImportFieldKind.Code, Aliases: ["iva", "aliquota_iva", "codice_iva"]), + new("iva_acquisti", ImportFieldKind.Code), + new("ean", Aliases: ["barcode", "codice_a_barre", "ean13", "gtin"]), + new("nc8", Aliases: ["nomenclatura", "codice_doganale", "taric"]), + new("marca", Aliases: ["brand"]), + new("produttore", Aliases: ["fabbricante", "manufacturer"]), + new("peso_netto", ImportFieldKind.Number), + new("peso_lordo", ImportFieldKind.Number, Aliases: ["peso"]), + new("a_magazzino", ImportFieldKind.Boolean, Aliases: ["gestito_a_magazzino", "movimenta_magazzino"]), + new("magazzino", ImportFieldKind.Code, Aliases: ["deposito"]), + new("scorta_minima", ImportFieldKind.Number, Aliases: ["scorta"]), + new("punto_riordino", ImportFieldKind.Number), + new("lotto_riordino", ImportFieldKind.Number), + new("prezzo", ImportFieldKind.Number, Aliases: ["prezzo_vendita", "prezzo_base", "price"]), + new("costo_standard", ImportFieldKind.Number, Aliases: ["costo"]), + new("conto_ricavo", Aliases: ["conto_ricavi"]), + new("conto_costo", Aliases: ["conto_costi"]), + new("note", Aliases: ["annotazioni", "notes"]), + ]; + + private static readonly Dictionary Columns = new(StringComparer.Ordinal) + { + ["Code"] = "codice", + ["Description"] = "descrizione", + ["ExtendedDescription"] = "descrizione_estesa", + ["Kind"] = "tipo", + ["CategoryId"] = "categoria", + ["UnitOfMeasureId"] = "um", + ["SalesTaxCodeId"] = "iva_vendite", + ["PurchaseTaxCodeId"] = "iva_acquisti", + ["Barcode"] = "ean", + ["CustomsCode"] = "nc8", + ["Brand"] = "marca", + ["Manufacturer"] = "produttore", + ["NetWeight"] = "peso_netto", + ["GrossWeight"] = "peso_lordo", + ["Stocked"] = "a_magazzino", + ["WarehouseId"] = "magazzino", + ["MinimumStock"] = "scorta_minima", + ["ReorderPoint"] = "punto_riordino", + ["ReorderLot"] = "lotto_riordino", + ["Price"] = "prezzo", + ["StandardCost"] = "costo_standard", + ["RevenueAccountCode"] = "conto_ricavo", + ["CostAccountCode"] = "conto_costo", + ["Notes"] = "note", + }; + + /// + public override string Key => "articoli"; + + /// + public override string ModuleCode => ModuleCodes.Core; + + /// + public override string Permission => ItemService.WritePermission; + + /// + public override string ExportPermission => ItemService.ReadPermission; + + /// + public override IReadOnlyList Fields => ItemFields; + + /// + public override async Task>> ExportAsync(ImportContext context, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + var state = await LoadAsync(context, ExportPermission, cancellationToken).ConfigureAwait(false); + var rows = new List>(); + var offset = 0; + while (true) + { + var page = await items.ListAsync(context.Actor, context.CompanyCode, new ListQuery { Offset = offset, Limit = 500, Sort = [new ListSort("code")] }, cancellationToken) + .ConfigureAwait(false); + foreach (var row in page.Items) + { + if (await items.GetAsync(context.Actor, context.CompanyCode, row.Id, cancellationToken).ConfigureAwait(false) is { } record) + { + rows.Add(Cells(state, record.Item)); + } + } + + offset += page.Items.Count; + if (page.Items.Count == 0 || offset >= page.Total) + { + break; + } + } + + return rows; + } + + /// + protected override async Task LoadAsync(ImportContext context, string permission, CancellationToken cancellationToken) + { + var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, permission, cancellationToken).ConfigureAwait(false); + await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var all = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items; + return new State + { + Items = new CodeIndex(all.Select(i => (i.Code, i.Id))), + Categories = await CodeIndex.LoadAsync(uow, cancellationToken).ConfigureAwait(false), + Units = await CodeIndex.LoadAsync(uow, cancellationToken).ConfigureAwait(false), + TaxCodes = await CodeIndex.LoadAsync(uow, cancellationToken).ConfigureAwait(false), + Warehouses = await CodeIndex.LoadAsync(uow, cancellationToken).ConfigureAwait(false), + }; + } + + /// + protected override long? Existing(State state, string code, List messages) + { + ArgumentNullException.ThrowIfNull(state); + return state.Items.Find(code); + } + + /// + protected override async Task OpenAsync(ImportContext context, long? id, CancellationToken cancellationToken) => + id is { } key + ? await items.GetAsync(context.Actor, context.CompanyCode, key, cancellationToken).ConfigureAwait(false) + : await items.NewAsync(context.Actor, context.CompanyCode, cancellationToken).ConfigureAwait(false); + + /// + protected override Task FillAsync(ImportContext context, State state, ItemRecord record, CellReader cells, bool isNew, CancellationToken cancellationToken) + { + var item = record.Item; + if (isNew && cells.Text("codice") is { } code) + { + item.Code = code; + } + + if (cells.Choice(ItemFields[3]) is { } kind) + { + item.Kind = (ItemKind)kind; + if (isNew && item.Kind != ItemKind.Goods) + { + item.Stocked = false; + } + } + + Set(cells, "descrizione", v => item.Description = v); + Set(cells, "descrizione_estesa", v => item.ExtendedDescription = v); + Set(cells, "ean", v => item.Barcode = v); + Set(cells, "nc8", v => item.CustomsCode = v); + Set(cells, "marca", v => item.Brand = v); + Set(cells, "produttore", v => item.Manufacturer = v); + Set(cells, "conto_ricavo", v => item.RevenueAccountCode = v); + Set(cells, "conto_costo", v => item.CostAccountCode = v); + Set(cells, "note", v => item.Notes = v); + item.CategoryId = cells.Code("categoria", state.Categories) ?? item.CategoryId; + item.UnitOfMeasureId = cells.Code("um", state.Units) ?? item.UnitOfMeasureId; + item.SalesTaxCodeId = cells.Code("iva_vendite", state.TaxCodes) ?? item.SalesTaxCodeId; + item.PurchaseTaxCodeId = cells.Code("iva_acquisti", state.TaxCodes) ?? item.PurchaseTaxCodeId; + item.WarehouseId = cells.Code("magazzino", state.Warehouses) ?? item.WarehouseId; + item.Stocked = cells.Boolean("a_magazzino") ?? item.Stocked; + item.NetWeight = cells.Number("peso_netto") ?? item.NetWeight; + item.GrossWeight = cells.Number("peso_lordo") ?? item.GrossWeight; + item.MinimumStock = cells.Number("scorta_minima") ?? item.MinimumStock; + item.ReorderPoint = cells.Number("punto_riordino") ?? item.ReorderPoint; + item.ReorderLot = cells.Number("lotto_riordino") ?? item.ReorderLot; + item.Price = cells.Number("prezzo") ?? item.Price; + item.StandardCost = cells.Number("costo_standard") ?? item.StandardCost; + return Task.CompletedTask; + } + + /// + protected override async Task> ValidateAsync(ImportContext context, ItemRecord record, bool isNew, CancellationToken cancellationToken) + { + var problems = (await items.ValidateAsync(context.Actor, context.CompanyCode, record, cancellationToken).ConfigureAwait(false)).ToList(); + if (isNew && record.Item.Code.Length > 0) + { + var rule = await codes.RuleAsync(context.CompanyCode, ItemService.CodeRule, cancellationToken).ConfigureAwait(false); + if (CodeRuleService.CheckManual(rule, record.Item.Code) is { } manual) + { + problems.Add(new(nameof(Item.Code), manual)); + } + } + + return problems; + } + + /// + protected override async Task<(string Code, long Id)> SaveAsync(ImportContext context, ItemRecord record, CancellationToken cancellationToken) + { + var saved = await items.SaveAsync(context.Actor, context.CompanyCode, record, cancellationToken).ConfigureAwait(false); + return (saved.Item.Code, saved.Item.Id); + } + + /// + protected override string Label(ImportRow row) + { + ArgumentNullException.ThrowIfNull(row); + return row["codice"] ?? row["descrizione"] ?? string.Empty; + } + + /// + protected override void Remember(State state, string code, long id) + { + ArgumentNullException.ThrowIfNull(state); + state.Items.Add(code, id); + } + + /// + protected override string ColumnOf(string serviceField) => Columns.GetValueOrDefault(serviceField ?? string.Empty, string.Empty); + + private static void Set(CellReader cells, string key, Action set) + { + if (cells.Text(key) is { } value) + { + set(value); + } + } + + private static object?[] Cells(State state, Item item) => + [ + item.Code, item.Description, item.ExtendedDescription, KindWords[(int)item.Kind], state.Categories.CodeOf(item.CategoryId), state.Units.CodeOf(item.UnitOfMeasureId), + state.TaxCodes.CodeOf(item.SalesTaxCodeId), state.TaxCodes.CodeOf(item.PurchaseTaxCodeId), item.Barcode, item.CustomsCode, item.Brand, item.Manufacturer, + item.NetWeight, item.GrossWeight, item.Stocked, state.Warehouses.CodeOf(item.WarehouseId), item.MinimumStock, item.ReorderPoint, item.ReorderLot, item.Price, + item.StandardCost, item.RevenueAccountCode, item.CostAccountCode, item.Notes, + ]; + + /// What a check or an import of items loads once. + public sealed class State + { + /// The items. + public required CodeIndex Items { get; init; } + + /// The categories. + public required CodeIndex Categories { get; init; } + + /// The units of measure. + public required CodeIndex Units { get; init; } + + /// The VAT codes. + public required CodeIndex TaxCodes { get; init; } + + /// The warehouses. + public required CodeIndex Warehouses { get; init; } + } +} diff --git a/src/Khaemhat.Application/ImportExport/PartiesImportTarget.cs b/src/Khaemhat.Application/ImportExport/PartiesImportTarget.cs new file mode 100644 index 0000000..a9a83ee --- /dev/null +++ b/src/Khaemhat.Application/ImportExport/PartiesImportTarget.cs @@ -0,0 +1,429 @@ +using System.Globalization; +using Khaemhat.Application.Parties; +using Khaemhat.Application.Querying; +using Khaemhat.Application.Tables; +using Khaemhat.Application.Modules; +using Khaemhat.Application.Security; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.ImportExport; + +/// +/// The customers or the suppliers (SPEC §12.12): each row is a party read by its code, or a new one, filled with the +/// cells of the row, checked and saved by , so the import obeys the rules of the record +/// (fiscal checks, automatic codes, duplicates). Empty cells keep the values of an existing party. +/// +/// Customers or suppliers. +/// The parties. +/// The automatic codes. +/// The places by postal code. +/// Opens the company databases (codes of the tables). +/// Checks the permission to import. +public sealed class PartiesImportTarget( + PartyKind kind, PartyService parties, CodeRuleService codes, AutoFillService autoFill, IUnitOfWorkFactory factory, PermissionService permissions) + : RecordImportTarget +{ + /// The words of tipo_soggetto, in the order of . + public static readonly IReadOnlyList SubjectWords = ["impresa", "privato", "pa", "ue", "extra-ue", "forfettario"]; + + private static readonly ImportField[] Common = + [ + new("codice", ImportFieldKind.Code, Aliases: ["cod", "codice_cliente", "codice_fornitore", "code"]), + new("ragione_sociale", Aliases: ["denominazione", "nome_ditta", "ragione", "rag_sociale", "name"]), + new("nome", Aliases: ["first_name"]), + new("cognome", Aliases: ["last_name"]), + new("tipo_soggetto", ImportFieldKind.Choice, Aliases: ["tipo", "soggetto"], Choices: SubjectWords), + new("partita_iva", Aliases: ["p_iva", "piva", "partitaiva", "vat", "vat_number"]), + new("codice_fiscale", Aliases: ["cf", "c_f", "cod_fiscale", "codicefiscale"]), + new("rea", Aliases: ["numero_rea"]), + new("indirizzo", Aliases: ["via", "address"]), + new("civico", Aliases: ["numero_civico", "n_civico"]), + new("cap", Aliases: ["c_a_p", "codice_postale", "postal_code"]), + new("comune", Aliases: ["citta", "localita", "city"]), + new("provincia", Aliases: ["prov", "pr", "sigla_provincia"]), + new("nazione", Aliases: ["paese", "stato", "country", "codice_nazione"]), + new("telefono", Aliases: ["tel", "phone"]), + new("email", Aliases: ["e_mail", "mail"]), + new("pec", Aliases: ["email_pec", "posta_certificata"]), + new("sito", Aliases: ["sito_web", "web", "website"]), + new("codice_destinatario", Aliases: ["codice_sdi", "sdi", "codice_univoco"]), + new("categoria", ImportFieldKind.Code), + ]; + + private static readonly ImportField[] CustomerFields = + [ + .. Common, + new("agente", ImportFieldKind.Code, Aliases: ["venditore"]), + new("pagamento", ImportFieldKind.Code, Aliases: ["condizioni_pagamento", "cod_pagamento"]), + new("listino", ImportFieldKind.Code), + new("sconto1", ImportFieldKind.Number, Aliases: ["sconto", "sconto_1"]), + new("sconto2", ImportFieldKind.Number, Aliases: ["sconto_2"]), + new("fido", ImportFieldKind.Number, Aliases: ["limite_fido", "fido_massimo"]), + new("iban", Aliases: ["codice_iban"]), + new("note", Aliases: ["annotazioni", "notes"]), + ]; + + private static readonly ImportField[] SupplierFields = + [ + .. Common, + new("pagamento", ImportFieldKind.Code, Aliases: ["condizioni_pagamento", "cod_pagamento"]), + new("iban", Aliases: ["codice_iban"]), + new("note", Aliases: ["annotazioni", "notes"]), + ]; + + private static readonly Dictionary Columns = new(StringComparer.Ordinal) + { + ["Code"] = "codice", + ["Name"] = "ragione_sociale", + ["FirstName"] = "nome", + ["LastName"] = "cognome", + ["SubjectType"] = "tipo_soggetto", + ["VatNumber"] = "partita_iva", + ["TaxCode"] = "codice_fiscale", + ["Rea"] = "rea", + ["Address"] = "indirizzo", + ["StreetNumber"] = "civico", + ["PostalCode"] = "cap", + ["City"] = "comune", + ["Province"] = "provincia", + ["CountryCode"] = "nazione", + ["Phone"] = "telefono", + ["Email"] = "email", + ["Pec"] = "pec", + ["Website"] = "sito", + ["CategoryId"] = "categoria", + ["SalespersonId"] = "agente", + ["Notes"] = "note", + ["Fiscal.RecipientCode"] = "codice_destinatario", + ["Sales.PaymentTermId"] = "pagamento", + ["Purchase.PaymentTermId"] = "pagamento", + ["Sales.PriceListId"] = "listino", + ["Sales.Discount1"] = "sconto1", + ["Sales.Discount2"] = "sconto2", + ["Sales.CreditLimit"] = "fido", + }; + + /// + public override string Key => kind == PartyKind.Supplier ? "fornitori" : "clienti"; + + /// + public override string ModuleCode => ModuleCodes.Core; + + /// + public override string Permission => PartyService.WritePermission; + + /// + public override string ExportPermission => "parties.party.export"; + + /// + public override IReadOnlyList Fields => kind == PartyKind.Supplier ? SupplierFields : CustomerFields; + + private bool IsCustomer => kind != PartyKind.Supplier; + + /// + public override async Task>> ExportAsync(ImportContext context, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + var state = await LoadAsync(context, ExportPermission, cancellationToken).ConfigureAwait(false); + var archive = IsCustomer ? PartyArchive.Customers : PartyArchive.Suppliers; + var rows = new List>(); + var offset = 0; + while (true) + { + var page = await parties.ListAsync(context.Actor, context.CompanyCode, archive, new ListQuery { Offset = offset, Limit = 500, Sort = [new ListSort("code")] }, + cancellationToken).ConfigureAwait(false); + foreach (var row in page.Items.Where(r => r.Kind == kind)) + { + if (await parties.GetAsync(context.Actor, context.CompanyCode, row.Id, cancellationToken).ConfigureAwait(false) is { } record) + { + rows.Add(Cells(state, record)); + } + } + + offset += page.Items.Count; + if (page.Items.Count == 0 || offset >= page.Total) + { + break; + } + } + + return rows; + } + + /// + protected override async Task LoadAsync(ImportContext context, string permission, CancellationToken cancellationToken) + { + var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, permission, cancellationToken).ConfigureAwait(false); + await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var all = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items; + return new State + { + Kinds = all.GroupBy(p => p.Code, StringComparer.OrdinalIgnoreCase).ToDictionary(g => g.Key, g => (g.First().Id, g.First().Kind), StringComparer.OrdinalIgnoreCase), + Categories = await CodeIndex.LoadAsync(uow, cancellationToken).ConfigureAwait(false), + Salespeople = await CodeIndex.LoadAsync(uow, cancellationToken).ConfigureAwait(false), + PaymentTerms = await CodeIndex.LoadAsync(uow, cancellationToken).ConfigureAwait(false), + PriceLists = await CodeIndex.LoadAsync(uow, cancellationToken).ConfigureAwait(false), + }; + } + + /// + protected override long? Existing(State state, string code, List messages) + { + if (!state.Kinds.TryGetValue(code, out var found)) + { + return null; + } + + if (found.Kind != kind) + { + messages.Add(new("codice", ImportErrors.OtherKind, Value: code)); + return null; + } + + return found.Id; + } + + /// + protected override Task OpenAsync(ImportContext context, long? id, CancellationToken cancellationToken) => + id is { } key + ? parties.GetAsync(context.Actor, context.CompanyCode, key, cancellationToken) + : NewAsync(context, cancellationToken); + + /// + protected override async Task FillAsync(ImportContext context, State state, PartyRecord record, CellReader cells, bool isNew, CancellationToken cancellationToken) + { + var party = record.Party; + if (isNew && cells.Text("codice") is { } code) + { + party.Code = code; + } + + if (cells.Choice(Fields.First(f => f.Key == "tipo_soggetto")) is { } subject) + { + party.SubjectType = (SubjectType)subject; + } + else if (isNew && !cells.Has("tipo_soggetto") && !cells.Has("ragione_sociale") && cells.Has("cognome")) + { + party.SubjectType = SubjectType.Person; + } + + Set(cells, "ragione_sociale", v => party.Name = v); + Set(cells, "nome", v => party.FirstName = v); + Set(cells, "cognome", v => party.LastName = v); + if (party.SubjectType == SubjectType.Person && !cells.Has("ragione_sociale") && (cells.Has("nome") || cells.Has("cognome"))) + { + party.Name = string.Empty; + } + + Set(cells, "partita_iva", v => party.VatNumber = v); + Set(cells, "codice_fiscale", v => party.TaxCode = v.ToUpperInvariant()); + Set(cells, "rea", v => party.Rea = v); + Set(cells, "indirizzo", v => party.Address = v); + Set(cells, "civico", v => party.StreetNumber = v); + Set(cells, "cap", v => party.PostalCode = v); + Set(cells, "comune", v => party.City = v); + Set(cells, "provincia", v => party.Province = v.ToUpperInvariant()); + Set(cells, "nazione", v => party.CountryCode = v.ToUpperInvariant()); + Set(cells, "telefono", v => party.Phone = v); + Set(cells, "email", v => party.Email = v); + Set(cells, "pec", v => party.Pec = v); + Set(cells, "sito", v => party.Website = v); + Set(cells, "codice_destinatario", v => record.Fiscal.RecipientCode = v.ToUpperInvariant()); + Set(cells, "note", v => party.Notes = v); + if (cells.Code("categoria", state.Categories) is { } category) + { + party.CategoryId = category; + } + + if (cells.Code("pagamento", state.PaymentTerms) is { } payment) + { + if (IsCustomer) + { + record.Sales.PaymentTermId = payment; + } + else + { + record.Purchase.PaymentTermId = payment; + } + } + + if (IsCustomer) + { + if (cells.Code("agente", state.Salespeople) is { } salesperson) + { + party.SalespersonId = salesperson; + } + + if (cells.Code("listino", state.PriceLists) is { } list) + { + record.Sales.PriceListId = list; + } + + record.Sales.Discount1 = cells.Number("sconto1") ?? record.Sales.Discount1; + record.Sales.Discount2 = cells.Number("sconto2") ?? record.Sales.Discount2; + record.Sales.CreditLimit = cells.Number("fido") ?? record.Sales.CreditLimit; + } + + if (cells.Text("iban") is { } text) + { + var iban = string.Concat(text.Where(c => !char.IsWhiteSpace(c))).ToUpperInvariant(); + if (!record.BankAccounts.Any(b => string.Equals(b.Iban, iban, StringComparison.OrdinalIgnoreCase))) + { + record.BankAccounts.Add(new PartyBankAccount { Iban = iban, IsDefault = !record.BankAccounts.Any(b => b.IsDefault) }); + } + } + + if (context.Options.FillFromPostalCode && (cells.Has("cap") || cells.Has("comune"))) + { + await FillPlaceAsync(context, state, party, cells, cancellationToken).ConfigureAwait(false); + } + } + + /// + protected override async Task> ValidateAsync(ImportContext context, PartyRecord record, bool isNew, CancellationToken cancellationToken) + { + var problems = (await parties.ValidateAsync(context.Actor, context.CompanyCode, record, cancellationToken).ConfigureAwait(false)).ToList(); + if (isNew && record.Party.Code.Length > 0 && CodeRuleService.CheckManual(await RuleAsync(context, cancellationToken).ConfigureAwait(false), record.Party.Code) is { } manual) + { + problems.Add(new(nameof(Party.Code), manual)); + } + + return problems; + } + + /// + protected override async Task<(string Code, long Id)> SaveAsync(ImportContext context, PartyRecord record, CancellationToken cancellationToken) + { + var saved = await parties.SaveAsync(context.Actor, context.CompanyCode, record, context.Options.VerifyVat, cancellationToken).ConfigureAwait(false); + return (saved.Party.Code, saved.Party.Id); + } + + /// + protected override string Label(ImportRow row) + { + ArgumentNullException.ThrowIfNull(row); + return row["codice"] ?? row["ragione_sociale"] ?? string.Join(' ', new[] { row["cognome"], row["nome"] }.Where(n => n is not null)); + } + + /// + protected override void Remember(State state, string code, long id) + { + ArgumentNullException.ThrowIfNull(state); + state.Kinds[code] = (id, kind); + } + + /// + protected override string ColumnOf(string serviceField) + { + ArgumentNullException.ThrowIfNull(serviceField); + if (Columns.TryGetValue(serviceField, out var column)) + { + return column; + } + + return serviceField.StartsWith("BankAccounts.", StringComparison.Ordinal) ? "iban" : string.Empty; + } + + private static void Set(CellReader cells, string key, Action set) + { + if (cells.Text(key) is { } value) + { + set(value); + } + } + + private object?[] Cells(State state, PartyRecord record) + { + var p = record.Party; + var common = new object?[] + { + p.Code, p.SubjectType == SubjectType.Person ? null : p.Name, p.FirstName, p.LastName, SubjectWords[(int)p.SubjectType], p.VatNumber, p.TaxCode, p.Rea, + p.Address, p.StreetNumber, p.PostalCode, p.City, p.Province, p.CountryCode, p.Phone, p.Email, p.Pec, p.Website, record.Fiscal.RecipientCode, + state.Categories.CodeOf(p.CategoryId), + }; + var iban = record.BankAccounts.OrderByDescending(b => b.IsDefault).FirstOrDefault()?.Iban; + return IsCustomer + ? + [ + .. common, state.Salespeople.CodeOf(p.SalespersonId), state.PaymentTerms.CodeOf(record.Sales.PaymentTermId), state.PriceLists.CodeOf(record.Sales.PriceListId), + record.Sales.Discount1, record.Sales.Discount2, record.Sales.CreditLimit, iban, p.Notes, + ] + : [.. common, state.PaymentTerms.CodeOf(record.Purchase.PaymentTermId), iban, p.Notes]; + } + + private async Task NewAsync(ImportContext context, CancellationToken cancellationToken) => + await parties.NewAsync(context.Actor, context.CompanyCode, kind, cancellationToken).ConfigureAwait(false); + + private async Task RuleAsync(ImportContext context, CancellationToken cancellationToken) => + await codes.RuleAsync(context.CompanyCode, PartyService.CodeRuleOf(kind), cancellationToken).ConfigureAwait(false); + + // City from the postal code and postal code from the city, only for Italian addresses and only when one place fits. + private async Task FillPlaceAsync(ImportContext context, State state, Party party, CellReader cells, CancellationToken cancellationToken) + { + if (!string.Equals(party.CountryCode, "IT", StringComparison.OrdinalIgnoreCase)) + { + return; + } + + if (party.PostalCode is { } cap && string.IsNullOrWhiteSpace(party.City)) + { + if (!state.ByPostalCode.TryGetValue(cap, out var places)) + { + places = await autoFill.PlacesByPostalCodeAsync(context.Actor, context.CompanyCode, cap, cancellationToken).ConfigureAwait(false); + state.ByPostalCode[cap] = places; + } + + if (places.Count == 1) + { + party.City = places[0].Name; + party.Province ??= places[0].ProvinceCode; + cells.Messages.Add(new("comune", ImportErrors.CityFilled, IsWarning: true, Value: places[0].Name)); + } + } + else if (party.City is { } city && string.IsNullOrWhiteSpace(party.PostalCode)) + { + var key = city.ToUpper(CultureInfo.InvariantCulture); + if (!state.ByName.TryGetValue(key, out var places)) + { + places = await autoFill.PlacesByNameAsync(context.Actor, context.CompanyCode, city, cancellationToken).ConfigureAwait(false); + state.ByName[key] = places; + } + + var exact = places.Where(p => string.Equals(p.Name, city, StringComparison.OrdinalIgnoreCase)).ToList(); + if (exact.Count == 1 && exact[0].PostalCode is { } postalCode) + { + party.PostalCode = postalCode; + party.Province ??= exact[0].ProvinceCode; + cells.Messages.Add(new("cap", ImportErrors.PostalCodeFilled, IsWarning: true, Value: postalCode)); + } + } + } + + /// What a check or an import of parties loads once. + public sealed class State + { + /// The id and kind of every party by code. + public required Dictionary Kinds { get; init; } + + /// The categories. + public required CodeIndex Categories { get; init; } + + /// The salespeople. + public required CodeIndex Salespeople { get; init; } + + /// The payment terms. + public required CodeIndex PaymentTerms { get; init; } + + /// The price lists. + public required CodeIndex PriceLists { get; init; } + + /// Places found by postal code. + public Dictionary> ByPostalCode { get; } = new(StringComparer.Ordinal); + + /// Places found by name. + public Dictionary> ByName { get; } = new(StringComparer.Ordinal); + } +} diff --git a/src/Khaemhat.Application/ImportExport/PricesImportTarget.cs b/src/Khaemhat.Application/ImportExport/PricesImportTarget.cs new file mode 100644 index 0000000..625fafb --- /dev/null +++ b/src/Khaemhat.Application/ImportExport/PricesImportTarget.cs @@ -0,0 +1,187 @@ +using Khaemhat.Application.Items; +using Khaemhat.Application.Modules; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Items; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.ImportExport; + +/// +/// The prices of the lists and the net prices of the customers (SPEC §12.12): each row is the price of an item in a list +/// or for a customer, valid from a day; the same item, list or customer and day replaces the price, another day adds a +/// dated price as the price grid does. All rows are written by in one transaction. +/// +/// The price lists. +/// Opens the company databases. +/// Checks the permission. +public sealed class PricesImportTarget(PriceListService prices, IUnitOfWorkFactory factory, PermissionService permissions) : IImportTarget +{ + private static readonly ImportField[] PriceFields = + [ + new("articolo", ImportFieldKind.Code, Required: true, Aliases: ["codice_articolo", "codice", "cod_articolo", "sku"]), + new("listino", ImportFieldKind.Code, Aliases: ["codice_listino", "cod_listino"]), + new("cliente", ImportFieldKind.Code, Aliases: ["codice_cliente", "cod_cliente"]), + new("prezzo", ImportFieldKind.Number, Required: true, Aliases: ["prezzo_netto", "price"]), + new("valido_dal", ImportFieldKind.Date, Aliases: ["validita", "data_inizio", "dal", "decorrenza"]), + ]; + + /// + public string Key => "listini"; + + /// + public string ModuleCode => ModuleCodes.Core; + + /// + public string Permission => ItemService.WritePermission; + + /// + public string ExportPermission => ItemService.ReadPermission; + + /// + public bool CanApply => true; + + /// + public bool CanExport => true; + + /// + public IReadOnlyList Fields => PriceFields; + + /// + public async Task> CheckAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) => + (await PlanAsync(context, rows, cancellationToken).ConfigureAwait(false)).Results; + + /// + public async Task> ApplyAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) + { + var plan = await PlanAsync(context, rows, cancellationToken).ConfigureAwait(false); + if (plan.Edits.Count == 0) + { + return plan.Results; + } + + try + { + await prices.SaveAsync(context.Actor, context.CompanyCode, [.. plan.Edits.Select(e => e.Edit)], cancellationToken).ConfigureAwait(false); + return plan.Results; + } + catch (ValidationFailedException ex) + { + // The rows were checked already: an error here is a change made meanwhile; it goes on its row and nothing is written. + var results = plan.Results.ToList(); + foreach (var (index, code) in ex.Errors.Select(TableErrors.Split)) + { + var position = int.TryParse(index, out var i) && i >= 0 && i < plan.Edits.Count ? plan.Edits[i].Result : -1; + if (position >= 0) + { + var row = results[position]; + results[position] = row with { Action = ImportAction.Skip, Messages = [.. row.Messages, new ImportMessage("prezzo", code)] }; + } + } + + return [.. results.Select(r => r.Outcome == ImportOutcome.Error ? r : r with { Action = ImportAction.Skip, Messages = [.. r.Messages, new ImportMessage(string.Empty, ImportErrors.WriteFailed)] })]; + } + } + + /// + public async Task>> ExportAsync(ImportContext context, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, ExportPermission, cancellationToken).ConfigureAwait(false); + await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var items = new CodeIndex((await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items.Select(i => (i.Code, i.Id))); + var parties = new CodeIndex((await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items.Select(p => (p.Code, p.Id))); + var lists = await CodeIndex.LoadAsync(uow, cancellationToken).ConfigureAwait(false); + var rows = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items; + return + [ + .. rows.Select(p => (IReadOnlyList)[items.CodeOf(p.ItemId), lists.CodeOf(p.PriceListId), parties.CodeOf(p.PartyId), p.Price, p.ValidFrom]) + .OrderBy(r => (string?)r[0], StringComparer.OrdinalIgnoreCase) + .ThenBy(r => (string?)r[1] ?? "~" + (string?)r[2], StringComparer.OrdinalIgnoreCase) + .ThenBy(r => (DateOnly?)r[4]), + ]; + } + + private async Task PlanAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(rows); + var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false); + await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var items = new CodeIndex((await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items.Select(i => (i.Code, i.Id))); + var allParties = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items; + var customers = new CodeIndex(allParties.Where(p => p.IsCustomer).Select(p => (p.Code, p.Id))); + var others = new HashSet(allParties.Where(p => !p.IsCustomer).Select(p => p.Code), StringComparer.OrdinalIgnoreCase); + var lists = await CodeIndex.LoadAsync(uow, cancellationToken).ConfigureAwait(false); + var existing = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items + .Select(p => (p.ItemId, p.PriceListId, p.PartyId, p.ValidFrom)).ToHashSet(); + + var seen = new HashSet<(long, long?, long?, DateOnly?)>(); + var results = new List(rows.Count); + var edits = new List<(PriceEdit Edit, int Result)>(); + foreach (var row in rows) + { + var messages = new List(); + var cells = new CellReader(row, messages); + var item = cells.Code("articolo", items); + long? list = null; + long? party = null; + if (cells.Has("listino") == cells.Has("cliente")) + { + messages.Add(new(cells.Has("listino") ? "cliente" : "listino", ImportErrors.PriceTarget)); + } + else if (cells.Has("listino")) + { + list = cells.Code("listino", lists); + } + else if (row["cliente"] is { } customer && others.Contains(customer)) + { + messages.Add(new("cliente", ImportErrors.OtherKind, Value: customer)); + } + else + { + party = cells.Code("cliente", customers); + } + + var price = cells.Number("prezzo"); + if (price < 0) + { + messages.Add(new("prezzo", ItemService.NotNegative)); + } + + var from = cells.Date("valido_dal"); + messages.AddRange(PriceFields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required))); + var label = row["articolo"] ?? string.Empty; + if (messages.Any(m => !m.IsWarning) || item is not { } itemId || price is not { } value) + { + results.Add(new(row.Line, label, ImportAction.Skip, messages)); + continue; + } + + var key = (itemId, list, party, from); + if (!seen.Add(key)) + { + messages.Add(new("articolo", ImportErrors.CodeRepeated, Value: label)); + results.Add(new(row.Line, label, ImportAction.Skip, messages)); + continue; + } + + var update = existing.Contains(key); + if (update && context.Options.Existing == ExistingCodeAction.Skip) + { + results.Add(new(row.Line, label, ImportAction.Skip, [new("articolo", ImportErrors.CodeExists, IsWarning: true, Value: label)])); + continue; + } + + edits.Add((new PriceEdit(itemId, list, party, value, from), results.Count)); + results.Add(new(row.Line, label, update ? ImportAction.Update : ImportAction.Create, messages)); + } + + return new Plan(results, edits); + } + + private sealed record Plan(IReadOnlyList Results, IReadOnlyList<(PriceEdit Edit, int Result)> Edits); +} diff --git a/src/Khaemhat.Application/Items/ItemService.cs b/src/Khaemhat.Application/Items/ItemService.cs new file mode 100644 index 0000000..903e3e1 --- /dev/null +++ b/src/Khaemhat.Application/Items/ItemService.cs @@ -0,0 +1,885 @@ +using System.Data.Common; +using Khaemhat.Application.Audit; +using Khaemhat.Application.Querying; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Instance; +using Khaemhat.Core.Items; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Tables; +using Khaemhat.Core.Validation; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Items; + +/// An item with all its details, as the record screen edits it (mockup 017). +public sealed class ItemRecord +{ + /// The item. + public Item Item { get; set; } = new(); + + /// The alternative units. + public List Units { get; set; } = []; + + /// The alternative codes. + public List Barcodes { get; set; } = []; + + /// The prices: of the price lists and net of the customers, each with its validity. + public List Prices { get; set; } = []; + + /// The suppliers. + public List Suppliers { get; set; } = []; + + /// The substitutes. + public List Substitutes { get; set; } = []; +} + +/// A row of the items radar. +/// The item. +/// The code. +/// The description. +/// What the item is. +/// The category. +/// The base unit. +/// The main bar code. +/// The brand. +/// Kept in stock. +/// The average cost, only for who can see costs. +/// Disabled. +public sealed record ItemRow( + long Id, string Code, string Description, ItemKind Kind, long? CategoryId, long? UnitOfMeasureId, string? Barcode, string? Brand, bool Stocked, + decimal? AverageCost, bool Disabled) +{ + /// The price of the base list today. + public decimal? BasePrice { get; init; } +} + +/// What happened to an item asked to be deleted. +public enum ItemDeleteOutcome +{ + /// Deleted. + Deleted = 0, + + /// Used by other data: disabled instead. + Disabled = 1, +} + +/// +/// Items (SPEC §11.2, mockup 017, ADR 0030): list, search by code, description, bar codes and codes of the parties, +/// record with units, codes, prices, suppliers and substitutes, checks, automatic code per category, history. +/// +/// Permissions items.item.read, write, delete; costs only with items.cost.read. +public sealed class ItemService +{ + /// Permission to read items and price lists. + public const string ReadPermission = "items.item.read"; + + /// Permission to write items and price lists. + public const string WritePermission = "items.item.write"; + + /// Permission to delete items. + public const string DeletePermission = "items.item.delete"; + + /// Permission to see costs and margins. + public const string CostPermission = "items.cost.read"; + + /// The entity of the attachments of an item. + public const string Entity = "items.item"; + + /// The code rule of the items (ADR 0027). + public const string CodeRule = "items"; + + /// Error: no description. + public const string DescriptionRequired = "items.description.required"; + + /// Error: the code is used by another item. + public const string CodeDuplicate = "items.code.duplicate"; + + /// Error: the code mask needs the category. + public const string CategoryRequired = "items.category.required"; + + /// Error: the bar code has a wrong check digit. + public const string BarcodeInvalid = "items.barcode.invalid"; + + /// Error or warning (by preference): another item has the bar code. + public const string BarcodeDuplicate = "items.barcode.duplicate"; + + /// Error: the NC8 code is not eight digits. + public const string CustomsCodeInvalid = "items.customs-code.invalid"; + + /// Error: a negative quantity, weight, price or cost. + public const string NotNegative = "items.value.negative"; + + /// Error: the factor of a unit is not above zero. + public const string FactorInvalid = "items.factor.invalid"; + + /// Error: a unit is listed twice, or is the base unit. + public const string UnitDuplicate = "items.unit.duplicate"; + + /// Error: a required detail field is empty. + public const string DetailRequired = "items.detail.required"; + + /// Error: the party of a supplier row is not a supplier. + public const string SupplierInvalid = "items.supplier.invalid"; + + /// Error: a supplier or a substitute is listed twice. + public const string DetailDuplicate = "items.detail.duplicate"; + + /// Error: an item cannot be its own substitute. + public const string SubstituteSelf = "items.substitute.self"; + + /// Error: a price is neither of a price list nor of a customer, or of both. + public const string PriceTarget = "items.price.target"; + + /// Error: a net price is for a customer only. + public const string PriceParty = "items.price.party"; + + /// Error: two prices of the same list or customer start on the same day. + public const string PriceDuplicate = "items.price.duplicate"; + + /// Error: the code of a party is used for another item. + public const string PartyCodeDuplicate = "items.party-code.duplicate"; + + /// Error: the item does not exist. + public const string NotFound = "items.not-found"; + + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly AuditTrail _audit; + private readonly CodeRuleService _codes; + private readonly TimeProvider _clock; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The audit trail. + /// The automatic codes. + /// The clock. + public ItemService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, CodeRuleService codes, TimeProvider clock) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(audit); + ArgumentNullException.ThrowIfNull(codes); + ArgumentNullException.ThrowIfNull(clock); + _factory = factory; + _permissions = permissions; + _audit = audit; + _codes = codes; + _clock = clock; + } + + /// The fields of the items radar. + public static ListFields Fields { get; } = new ListFields() + .Add("code", i => i.Code, searchable: true) + .Add("description", i => i.Description, searchable: true) + .Add("barcode", i => i.Barcode, searchable: true) + .Add("brand", i => i.Brand, searchable: true) + .Add("manufacturer", i => i.Manufacturer, searchable: true) + .Add("kind", i => i.Kind) + .Add("category", i => i.CategoryId) + .Add("unit", i => i.UnitOfMeasureId) + .Add("stocked", i => i.Stocked) + .Add("disabled", i => i.Disabled) + .OrderByDefault(new ListSort("code")); + + /// The items for the radar, with the price of the base list today. + /// Who reads. + /// The company. + /// Search, filters, sort, page. + /// Cancellation. + /// The page. + public async Task> ListAsync(Actor actor, string companyCode, ListQuery query, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(query); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + var costs = await CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var page = await uow.Repository().ListAsync(Fields.Apply(Query.For(), query), cancellationToken).ConfigureAwait(false); + var book = await BookAsync(uow, [.. page.Items.Select(i => i.Id)], cancellationToken).ConfigureAwait(false); + var today = Today(); + IReadOnlyList rows = + [ + .. page.Items.Select(i => RowOf(i, costs) with + { + BasePrice = book.Base is { } baseList ? book.ListPrice(i.Id, baseList.Id, today).Price : i.Price, + }), + ]; + return new ListPage(rows, page.TotalCount, new Dictionary()); + } + + /// + /// The active items matching a text, for the lookups: code, description, bar code and brand, or exactly an + /// alternative code or the code a party uses for the item. + /// + /// Who reads. + /// The company. + /// The text. + /// The party of the document, whose codes count too. + /// Cancellation. + /// At most 20 items. + public async Task> SearchAsync(Actor actor, string companyCode, string? text, long? partyId = null, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + var costs = await CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var items = uow.Repository(); + var page = await items.ListAsync( + Fields.Apply(Query.For(), new ListQuery { Search = text, Filters = [ListFilter.Of("disabled", ListFilterOperator.Equals, "false")], Limit = 20 }), + cancellationToken).ConfigureAwait(false); + var found = page.Items.ToList(); + var exact = text?.Trim(); + if (!string.IsNullOrEmpty(exact)) + { + var ids = (await uow.Repository().ListAsync(Query.For().Where(b => b.Code == exact), cancellationToken).ConfigureAwait(false)) + .Items.Select(b => b.ItemId).ToList(); + if (partyId is { } party) + { + ids.AddRange((await uow.Repository().ListAsync( + Query.For().Where(c => c.PartyId == party && c.Code == exact), cancellationToken).ConfigureAwait(false)).Items.Select(c => c.ItemId)); + } + + foreach (var id in ids.Distinct().Where(id => found.All(i => i.Id != id))) + { + if (await items.GetAsync(id, cancellationToken).ConfigureAwait(false) is { Disabled: false } item) + { + found.Insert(0, item); + } + } + } + + return [.. found.Take(20).Select(i => RowOf(i, costs))]; + } + + /// An item with its details; costs hidden without items.cost.read. + /// Who reads. + /// The company. + /// The item. + /// Cancellation. + /// The record, or none. + public async Task GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + var costs = await CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var record = await LoadAsync(uow, id, cancellationToken).ConfigureAwait(false); + if (record is not null && !costs) + { + HideCosts(record); + } + + return record; + } + + /// A new item with the usual values: goods kept in stock, unit PZ, VAT 22, the default warehouse. + /// Who asks. + /// The company. + /// Cancellation. + /// The record to fill. + public async Task NewAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var unit = await uow.Repository().FindAsync(Query.For().Where(u => u.Code == "PZ" && !u.Disabled), cancellationToken).ConfigureAwait(false); + var tax = await uow.Repository().FindAsync(Query.For().Where(t => t.Code == "22" && !t.Disabled), cancellationToken).ConfigureAwait(false); + var warehouse = await uow.Repository().FindAsync(Query.For().Where(w => w.IsDefault && !w.Disabled), cancellationToken).ConfigureAwait(false); + return new ItemRecord + { + Item = new Item + { + Kind = ItemKind.Goods, Stocked = true, UnitOfMeasureId = unit?.Id, SalesTaxCodeId = tax?.Id, PurchaseTaxCodeId = tax?.Id, WarehouseId = warehouse?.Id, + }, + }; + } + + /// Checks a record without saving it (also cleans it, as the save would). + /// Who asks. + /// The company. + /// The record. + /// Cancellation. + /// Errors and warnings. + public async Task> ValidateAsync(Actor actor, string companyCode, ItemRecord record, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(record); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + var rule = await _codes.RuleAsync(company, CodeRule, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await CheckAsync(uow, rule, record, cancellationToken).ConfigureAwait(false); + } + + /// + /// Saves an item and its details in one transaction; a new item gets its code from the rule of the items + /// ({categoria} is the code of its category). Without items.cost.read the costs stay as they were. + /// + /// Who saves. + /// The company. + /// The record. + /// Cancellation. + /// The record as saved. + /// With the errors (field:code). + public async Task SaveAsync(Actor actor, string companyCode, ItemRecord record, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(record); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false); + var costs = await CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false); + var rule = await _codes.RuleAsync(company, CodeRule, cancellationToken).ConfigureAwait(false); + var item = record.Item; + long id; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var before = item.Id == 0 ? null : await LoadAsync(uow, item.Id, cancellationToken).ConfigureAwait(false) ?? throw new ValidationFailedException([":" + NotFound]); + + // The last and average costs come from the receipts (M6); the standard cost only from who sees costs. + item.LastCost = before?.Item.LastCost; + item.AverageCost = before?.Item.AverageCost; + if (!costs) + { + item.StandardCost = before?.Item.StandardCost; + } + + var problems = (await CheckAsync(uow, rule, record, cancellationToken).ConfigureAwait(false)).Where(p => !p.IsWarning).Select(p => p.Field + ":" + p.Code).ToList(); + if (problems.Count > 0) + { + throw new ValidationFailedException(problems); + } + + if (item.Code.Length == 0) + { + var category = item.CategoryId is { } categoryId ? (await uow.Repository().GetAsync(categoryId, cancellationToken).ConfigureAwait(false))?.Code : null; + item.Code = await CodeRuleService.AssignAsync(uow, rule, Today(), category, (c, ct) => TakenAsync(uow, c, ct), cancellationToken).ConfigureAwait(false); + } + + id = await WriteAsync(uow, record, before, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + return await GetAsync(actor, company, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound); + } + + /// Disables or enables items (radar selection). + /// Who does it. + /// The company. + /// The items. + /// Disable or enable. + /// Cancellation. + /// How many changed. + public async Task SetDisabledAsync(Actor actor, string companyCode, IEnumerable ids, bool disabled, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(ids); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + var changed = 0; + foreach (var id in ids.Distinct()) + { + if (await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } item && item.Disabled != disabled) + { + var before = Clone(item); + item.Disabled = disabled; + await repository.UpdateAsync(item, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, id, before, item, actor.UserName, cancellationToken).ConfigureAwait(false); + changed++; + } + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return changed; + } + + /// Deletes an item; one used by other data (a substitute, documents from M5) is disabled instead. + /// Who deletes. + /// The company. + /// The item. + /// Cancellation. + /// What happened. + public async Task DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, DeletePermission, cancellationToken).ConfigureAwait(false); + try + { + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var before = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound); + await uow.Repository().DeleteAsync(id, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Delete, id, before, null, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return ItemDeleteOutcome.Deleted; + } + catch (DbException) + { + await SetDisabledAsync(actor, company, [id], true, cancellationToken).ConfigureAwait(false); + return ItemDeleteOutcome.Disabled; + } + } + + /// The history of an item and of its prices, newest first. + /// Who reads. + /// The company. + /// The item. + /// Cancellation. + /// The changes. + public async Task> HistoryAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var key = id.ToString(System.Globalization.CultureInfo.InvariantCulture); + var entries = new List(); + foreach (var entity in new[] { nameof(Item), nameof(ItemPrice) }) + { + entries.AddRange(await AuditTrail.HistoryAsync(uow, entity, key, cancellationToken).ConfigureAwait(false)); + } + + return [.. entries.OrderByDescending(e => e.At).ThenByDescending(e => e.Id)]; + } + + /// The rows of some items, for the lookups that show them by id. + /// Who reads. + /// The company. + /// The items. + /// Cancellation. + /// The rows found. + public async Task> RowsAsync(Actor actor, string companyCode, IEnumerable ids, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(ids); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + var costs = await CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false); + long[] wanted = [.. ids.Distinct()]; + if (wanted.Length == 0) + { + return []; + } + + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return [.. (await uow.Repository().ListAsync(Query.For().Where(i => wanted.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items + .Select(i => RowOf(i, costs))]; + } + + /// Checks the codes of a party: code and item required, no code twice. + /// The codes. + /// The errors. + public static IReadOnlyList CheckPartyCodes(IReadOnlyList codes) + { + ArgumentNullException.ThrowIfNull(codes); + var problems = new List(); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + for (var i = 0; i < codes.Count; i++) + { + var code = codes[i]; + code.Code = code.Code.Trim(); + code.Description = Clean(code.Description); + if (code.Code.Length == 0) + { + problems.Add(new($"ItemCodes.{i}.{nameof(PartyItemCode.Code)}", DetailRequired)); + } + else if (!seen.Add(code.Code)) + { + problems.Add(new($"ItemCodes.{i}.{nameof(PartyItemCode.Code)}", PartyCodeDuplicate)); + } + + if (code.ItemId == 0) + { + problems.Add(new($"ItemCodes.{i}.{nameof(PartyItemCode.ItemId)}", DetailRequired)); + } + } + + return problems; + } + + /// Whether an actor sees costs and margins. + /// The actor. + /// The company. + /// Cancellation. + /// Whether costs are visible. + public async Task CanSeeCostsAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + return (actor.IsInstanceAccount || string.Equals(actor.CompanyCode, CompanyCodes.Normalize(companyCode), StringComparison.Ordinal)) + && (await _permissions.CheckAsync(actor, CostPermission, cancellationToken).ConfigureAwait(false)).Allowed; + } + + /// The prices of some items and all the price lists, in memory. + /// The unit of work of the company. + /// The items. + /// Cancellation. + /// The book. + public static async Task BookAsync(IUnitOfWork uow, IReadOnlyList itemIds, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(uow); + ArgumentNullException.ThrowIfNull(itemIds); + var lists = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items; + var prices = new List(); + foreach (var chunk in itemIds.Distinct().Chunk(500)) + { + long[] ids = [.. chunk]; + prices.AddRange((await uow.Repository().ListAsync(Query.For().Where(p => ids.Contains(p.ItemId)), cancellationToken).ConfigureAwait(false)).Items); + } + + return new PriceBook(lists, prices); + } + + private DateOnly Today() => DateOnly.FromDateTime(_clock.GetLocalNow().DateTime); + + private static ItemRow RowOf(Item i, bool costs) => + new(i.Id, i.Code, i.Description, i.Kind, i.CategoryId, i.UnitOfMeasureId, i.Barcode, i.Brand, i.Stocked, costs ? i.AverageCost : null, i.Disabled); + + private static void HideCosts(ItemRecord record) + { + record.Item.StandardCost = null; + record.Item.LastCost = null; + record.Item.AverageCost = null; + } + + private static async Task TakenAsync(IUnitOfWork uow, string code, CancellationToken cancellationToken) => + await uow.Repository().CountAsync(Query.For().Where(i => i.Code == code), cancellationToken).ConfigureAwait(false) > 0; + + private static async Task LoadAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) + { + if (await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } item) + { + return null; + } + + return new ItemRecord + { + Item = item, + Units = [.. (await uow.Repository().ListAsync(Query.For().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items], + Barcodes = [.. (await uow.Repository().ListAsync(Query.For().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items], + Prices = [.. (await uow.Repository().ListAsync(Query.For().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items], + Suppliers = [.. (await uow.Repository().ListAsync(Query.For().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items], + Substitutes = [.. (await uow.Repository().ListAsync(Query.For().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items], + }; + } + + private async Task WriteAsync(IUnitOfWork uow, ItemRecord record, ItemRecord? before, string userName, CancellationToken cancellationToken) + { + var item = record.Item; + var items = uow.Repository(); + if (before is null) + { + item.Id = await items.InsertAsync(item, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Insert, item.Id, null, item, userName, cancellationToken).ConfigureAwait(false); + } + else + { + await items.UpdateAsync(item, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, item.Id, before.Item, item, userName, cancellationToken).ConfigureAwait(false); + } + + var id = item.Id; + await ReplaceAsync(uow, record.Units, before?.Units ?? [], u => u.ItemId = id, cancellationToken).ConfigureAwait(false); + await ReplaceAsync(uow, record.Barcodes, before?.Barcodes ?? [], u => u.ItemId = id, cancellationToken).ConfigureAwait(false); + await ReplaceAsync(uow, record.Suppliers, before?.Suppliers ?? [], u => u.ItemId = id, cancellationToken).ConfigureAwait(false); + await ReplaceAsync(uow, record.Substitutes, before?.Substitutes ?? [], u => u.ItemId = id, cancellationToken).ConfigureAwait(false); + await ReplaceAsync(uow, record.Prices, before?.Prices ?? [], u => u.ItemId = id, cancellationToken, async (old, row, ct) => + await _audit.RecordAsync(uow, old is null ? AuditAction.Insert : row is null ? AuditAction.Delete : AuditAction.Update, id, old, row, userName, ct).ConfigureAwait(false)) + .ConfigureAwait(false); + return id; + } + + // The lists: rows removed are deleted, rows kept are updated, new rows inserted; the prices are written in the history. + private static async Task ReplaceAsync( + IUnitOfWork uow, List rows, List before, Action link, CancellationToken cancellationToken, Func? audit = null) + where T : Core.Entities.Entity, new() + { + var repository = uow.Repository(); + var kept = rows.Where(r => r.Id != 0).Select(r => r.Id).ToHashSet(); + foreach (var old in before.Where(b => !kept.Contains(b.Id))) + { + await repository.DeleteAsync(old.Id, cancellationToken).ConfigureAwait(false); + if (audit is not null) + { + await audit(old, null, cancellationToken).ConfigureAwait(false); + } + } + + var previous = before.ToDictionary(b => b.Id); + foreach (var row in rows) + { + link(row); + if (row.Id != 0 && previous.TryGetValue(row.Id, out var old)) + { + row.RowVersion = old.RowVersion; + await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false); + if (audit is not null) + { + await audit(old, row, cancellationToken).ConfigureAwait(false); + } + } + else + { + row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false); + if (audit is not null) + { + await audit(null, row, cancellationToken).ConfigureAwait(false); + } + } + } + } + + private static async Task> CheckAsync(IUnitOfWork uow, CodeRule rule, ItemRecord record, CancellationToken cancellationToken) + { + var problems = new List(); + var item = record.Item; + Normalize(item); + if (item.Description.Length == 0) + { + problems.Add(new(nameof(Item.Description), DescriptionRequired)); + } + + var id = item.Id; + if (item.Code.Length > 0) + { + var code = item.Code; + if (await uow.Repository().CountAsync(Query.For().Where(i => i.Code == code && i.Id != id), cancellationToken).ConfigureAwait(false) > 0) + { + problems.Add(new(nameof(Item.Code), CodeDuplicate)); + } + } + else if (item.CategoryId is null && CodeMask.TryParse(rule.Mask, out var mask, out _) && mask!.UsesCategory) + { + problems.Add(new(nameof(Item.CategoryId), CategoryRequired)); + } + + if (item.Barcode is { } barcode) + { + if (!EanValidator.IsValid(barcode)) + { + problems.Add(new(nameof(Item.Barcode), BarcodeInvalid)); + } + else if (await BarcodeUsedAsync(uow, barcode, id, cancellationToken).ConfigureAwait(false)) + { + problems.Add(new(nameof(Item.Barcode), BarcodeDuplicate, IsWarning: !rule.UniqueBarcode)); + } + } + + if (item.CustomsCode is { } customs && (customs.Length != 8 || !customs.All(char.IsAsciiDigit))) + { + problems.Add(new(nameof(Item.CustomsCode), CustomsCodeInvalid)); + } + + foreach (var (value, field) in new (decimal?, string)[] + { + (item.NetWeight, nameof(Item.NetWeight)), (item.GrossWeight, nameof(Item.GrossWeight)), (item.MinimumStock, nameof(Item.MinimumStock)), + (item.ReorderPoint, nameof(Item.ReorderPoint)), (item.ReorderLot, nameof(Item.ReorderLot)), (item.Price, nameof(Item.Price)), + (item.StandardCost, nameof(Item.StandardCost)), + }) + { + if (value < 0) + { + problems.Add(new(field, NotNegative)); + } + } + + CheckUnits(record, problems); + CheckBarcodes(record, problems); + await CheckPricesAsync(uow, record, problems, cancellationToken).ConfigureAwait(false); + await CheckSuppliersAsync(uow, record, problems, cancellationToken).ConfigureAwait(false); + CheckSubstitutes(record, problems); + return problems; + } + + private static void Normalize(Item item) + { + item.Code = item.Code.Trim(); + item.Description = item.Description.Trim(); + item.ExtendedDescription = Clean(item.ExtendedDescription); + item.Barcode = Clean(item.Barcode); + item.CustomsCode = Clean(item.CustomsCode)?.Replace(" ", string.Empty, StringComparison.Ordinal).Replace(".", string.Empty, StringComparison.Ordinal); + item.Manufacturer = Clean(item.Manufacturer); + item.Brand = Clean(item.Brand); + item.RevenueAccountCode = Clean(item.RevenueAccountCode); + item.CostAccountCode = Clean(item.CostAccountCode); + item.Notes = Clean(item.Notes); + + // Only goods move in the warehouse. + if (item.Kind != ItemKind.Goods) + { + item.Stocked = false; + } + } + + private static async Task BarcodeUsedAsync(IUnitOfWork uow, string barcode, long id, CancellationToken cancellationToken) => + await uow.Repository().CountAsync(Query.For().Where(i => i.Barcode == barcode && i.Id != id), cancellationToken).ConfigureAwait(false) > 0 + || await uow.Repository().CountAsync(Query.For().Where(b => b.Code == barcode && b.ItemId != id), cancellationToken).ConfigureAwait(false) > 0; + + private static void CheckUnits(ItemRecord record, List problems) + { + var seen = new HashSet(); + if (record.Item.UnitOfMeasureId is { } baseUnit) + { + seen.Add(baseUnit); + } + + for (var i = 0; i < record.Units.Count; i++) + { + var unit = record.Units[i]; + unit.Barcode = Clean(unit.Barcode); + if (unit.UnitOfMeasureId == 0) + { + problems.Add(new($"Units.{i}.{nameof(ItemUnit.UnitOfMeasureId)}", DetailRequired)); + } + else if (!seen.Add(unit.UnitOfMeasureId)) + { + problems.Add(new($"Units.{i}.{nameof(ItemUnit.UnitOfMeasureId)}", UnitDuplicate)); + } + + if (unit.Factor <= 0) + { + problems.Add(new($"Units.{i}.{nameof(ItemUnit.Factor)}", FactorInvalid)); + } + + if (unit.Barcode is { } barcode && !EanValidator.IsValid(barcode)) + { + problems.Add(new($"Units.{i}.{nameof(ItemUnit.Barcode)}", BarcodeInvalid)); + } + } + } + + private static void CheckBarcodes(ItemRecord record, List problems) + { + var seen = new HashSet(StringComparer.Ordinal); + if (record.Item.Barcode is { } main) + { + seen.Add(main); + } + + for (var i = 0; i < record.Barcodes.Count; i++) + { + var code = record.Barcodes[i]; + code.Code = code.Code.Trim(); + code.Description = Clean(code.Description); + if (code.Code.Length == 0) + { + problems.Add(new($"Barcodes.{i}.{nameof(ItemBarcode.Code)}", DetailRequired)); + } + else if (!seen.Add(code.Code)) + { + problems.Add(new($"Barcodes.{i}.{nameof(ItemBarcode.Code)}", DetailDuplicate)); + } + } + } + + private static async Task CheckPricesAsync(IUnitOfWork uow, ItemRecord record, List problems, CancellationToken cancellationToken) + { + var seen = new HashSet<(long?, long?, DateOnly?)>(); + var parties = uow.Repository(); + for (var i = 0; i < record.Prices.Count; i++) + { + var price = record.Prices[i]; + var field = $"Prices.{i}."; + if ((price.PriceListId is null) == (price.PartyId is null)) + { + problems.Add(new(field + nameof(ItemPrice.PriceListId), PriceTarget)); + continue; + } + + // A row added on the screen and not filled has id 0. + if (price.PriceListId is 0 || price.PartyId is 0) + { + problems.Add(new(field + (price.PartyId is null ? nameof(ItemPrice.PriceListId) : nameof(ItemPrice.PartyId)), DetailRequired)); + continue; + } + + if (price.PartyId is { } partyId && await parties.GetAsync(partyId, cancellationToken).ConfigureAwait(false) is not { IsCustomer: true }) + { + problems.Add(new(field + nameof(ItemPrice.PartyId), PriceParty)); + } + + if (price.Price < 0) + { + problems.Add(new(field + nameof(ItemPrice.Price), NotNegative)); + } + + if (!seen.Add((price.PriceListId, price.PartyId, price.ValidFrom))) + { + problems.Add(new(field + nameof(ItemPrice.ValidFrom), PriceDuplicate)); + } + } + } + + private static async Task CheckSuppliersAsync(IUnitOfWork uow, ItemRecord record, List problems, CancellationToken cancellationToken) + { + var seen = new HashSet(); + var parties = uow.Repository(); + for (var i = 0; i < record.Suppliers.Count; i++) + { + var supplier = record.Suppliers[i]; + var field = $"Suppliers.{i}."; + supplier.SupplierCode = Clean(supplier.SupplierCode); + if (supplier.PartyId == 0) + { + problems.Add(new(field + nameof(ItemSupplier.PartyId), DetailRequired)); + } + else if (!seen.Add(supplier.PartyId)) + { + problems.Add(new(field + nameof(ItemSupplier.PartyId), DetailDuplicate)); + } + else if (await parties.GetAsync(supplier.PartyId, cancellationToken).ConfigureAwait(false) is not { IsSupplier: true }) + { + problems.Add(new(field + nameof(ItemSupplier.PartyId), SupplierInvalid)); + } + + if (supplier.Price < 0) + { + problems.Add(new(field + nameof(ItemSupplier.Price), NotNegative)); + } + + if (supplier.MinimumQuantity < 0) + { + problems.Add(new(field + nameof(ItemSupplier.MinimumQuantity), NotNegative)); + } + + if (supplier.LeadTimeDays < 0) + { + problems.Add(new(field + nameof(ItemSupplier.LeadTimeDays), NotNegative)); + } + } + + // One usual supplier: the first one marked. + var found = false; + foreach (var supplier in record.Suppliers.Where(s => s.IsDefault)) + { + supplier.IsDefault = !found; + found = true; + } + } + + private static void CheckSubstitutes(ItemRecord record, List problems) + { + var seen = new HashSet(); + for (var i = 0; i < record.Substitutes.Count; i++) + { + var substitute = record.Substitutes[i]; + var field = $"Substitutes.{i}.{nameof(ItemSubstitute.SubstituteId)}"; + substitute.Notes = Clean(substitute.Notes); + if (substitute.SubstituteId == 0) + { + problems.Add(new(field, DetailRequired)); + } + else if (substitute.SubstituteId == record.Item.Id) + { + problems.Add(new(field, SubstituteSelf)); + } + else if (!seen.Add(substitute.SubstituteId)) + { + problems.Add(new(field, DetailDuplicate)); + } + } + } + + private static string? Clean(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + + private static Item Clone(Item item) + { + var copy = new Item(); + foreach (var property in typeof(Item).GetProperties().Where(p => p.CanRead && p.CanWrite)) + { + property.SetValue(copy, property.GetValue(item)); + } + + return copy; + } +} diff --git a/src/Khaemhat.Application/Items/PriceBook.cs b/src/Khaemhat.Application/Items/PriceBook.cs new file mode 100644 index 0000000..734e7b0 --- /dev/null +++ b/src/Khaemhat.Application/Items/PriceBook.cs @@ -0,0 +1,188 @@ +using Khaemhat.Application.Tables; +using Khaemhat.Core.Items; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Tables; + +namespace Khaemhat.Application.Items; + +/// The price proposed for an item and where it comes from (price_source of the document lines). +/// The price, or none. +/// Where it comes from. +/// The price list it comes from. +/// The price includes VAT (a price list with VAT included). +/// The price is valid from this day. +public sealed record PriceQuote(decimal? Price, PriceSource Source, long? PriceListId, bool VatIncluded, DateOnly? ValidFrom) +{ + /// No price. + public static PriceQuote None { get; } = new(null, PriceSource.None, null, false, null); +} + +/// The discounts proposed on a line. +/// The chain, such as 5+2, or none. +/// The single discount equal to the chain, in percent. +public sealed record DiscountQuote(string? Formula, decimal Equivalent) +{ + /// No discount. + public static DiscountQuote None { get; } = new(null, 0m); +} + +/// A price of a price list for an item at a date. +/// The price, or none. +/// The price is computed from the base list of a derived list, not written. +/// The price is valid from this day. +public sealed record PriceCell(decimal? Price, bool Derived, DateOnly? ValidFrom) +{ + /// No price. + public static PriceCell Empty { get; } = new(null, false, null); +} + +/// +/// The prices of some items in memory, and the search of SPEC §11.3 (ADR 0030): net price of the party for the item, +/// then the price list of the party or of the document, then the base price list, then the price of the item. A +/// derived list without its own price takes the price of its base list with the markup and the rounding of the list. +/// +public sealed class PriceBook +{ + // A derived list of a derived list... is followed at most this deep (the table forbids only a list on itself). + private const int MaxDepth = 5; + + private readonly Dictionary _lists; + private readonly ILookup<(long Item, long List), ItemPrice> _listPrices; + private readonly ILookup<(long Item, long Party), ItemPrice> _netPrices; + + /// Creates the book. + /// The price lists of the company. + /// The prices of the items wanted (all their rows). + public PriceBook(IEnumerable lists, IEnumerable prices) + { + ArgumentNullException.ThrowIfNull(lists); + ArgumentNullException.ThrowIfNull(prices); + _lists = lists.ToDictionary(l => l.Id); + var all = prices.ToList(); + _listPrices = all.Where(p => p.PriceListId is not null).ToLookup(p => (p.ItemId, p.PriceListId!.Value)); + _netPrices = all.Where(p => p.PartyId is not null).ToLookup(p => (p.ItemId, p.PartyId!.Value)); + Base = BaseOf(_lists.Values); + } + + /// The base price list: the one marked, or the one with code BASE. + public PriceList? Base { get; } + + /// The price lists. + public IReadOnlyCollection Lists => _lists.Values; + + /// The base price list among some. + /// The price lists. + /// The base one, or none. + public static PriceList? BaseOf(IEnumerable lists) + { + ArgumentNullException.ThrowIfNull(lists); + var active = lists.Where(l => !l.Disabled).OrderBy(l => l.Code, StringComparer.Ordinal).ToList(); + return active.FirstOrDefault(l => l.IsBase) ?? active.FirstOrDefault(l => l.Code == "BASE"); + } + + /// The row in effect at a date: the latest start not after it (a row without start is always valid). + /// The rows of one item and one list or party. + /// The date. + /// The row, or none. + public static ItemPrice? At(IEnumerable rows, DateOnly date) + { + ArgumentNullException.ThrowIfNull(rows); + return rows.Where(r => r.ValidFrom is null || r.ValidFrom <= date).OrderByDescending(r => r.ValidFrom ?? DateOnly.MinValue).FirstOrDefault(); + } + + /// Whether a price list can be used at a date: active and within its validity. + /// The list. + /// The date. + /// Whether it is valid. + public static bool IsValid(PriceList list, DateOnly date) + { + ArgumentNullException.ThrowIfNull(list); + return !list.Disabled && (list.ValidFrom is null || list.ValidFrom <= date) && (list.ValidTo is null || list.ValidTo >= date); + } + + /// The price of an item in a list at a date, derived from the base list when the list has none. + /// The item. + /// The list. + /// The date. + /// The price. + public PriceCell ListPrice(long itemId, long listId, DateOnly date) => ListPrice(itemId, listId, date, 0); + + /// The price written in a list for an item at a date, without derivation. + /// The item. + /// The list. + /// The date. + /// The row, or none. + public ItemPrice? OwnPrice(long itemId, long listId, DateOnly date) => At(_listPrices[(itemId, listId)], date); + + /// The net price of a party for an item at a date. + /// The item. + /// The party. + /// The date. + /// The row, or none. + public ItemPrice? NetPrice(long itemId, long partyId, DateOnly date) => At(_netPrices[(itemId, partyId)], date); + + /// The price proposed for an item (SPEC §11.3): net of the party, list, base list, item. + /// The item. + /// The party of the document. + /// The price list of the party or of the document. + /// The date of the document. + /// The price and its source. + public PriceQuote Quote(Item item, long? partyId, long? priceListId, DateOnly date) + { + ArgumentNullException.ThrowIfNull(item); + if (partyId is { } party && NetPrice(item.Id, party, date) is { } net) + { + return new PriceQuote(net.Price, PriceSource.PartyNet, null, false, net.ValidFrom); + } + + if (priceListId is { } listId && _lists.TryGetValue(listId, out var list) && IsValid(list, date) + && ListPrice(item.Id, listId, date) is { Price: { } listPrice } cell) + { + return new PriceQuote(listPrice, PriceSource.PartyPriceList, listId, list.VatIncluded, cell.ValidFrom); + } + + if (Base is { } baseList && baseList.Id != priceListId && IsValid(baseList, date) + && ListPrice(item.Id, baseList.Id, date) is { Price: { } basePrice } baseCell) + { + return new PriceQuote(basePrice, PriceSource.BasePriceList, baseList.Id, baseList.VatIncluded, baseCell.ValidFrom); + } + + return item.Price is { } own ? new PriceQuote(own, PriceSource.Item, null, false, null) : PriceQuote.None; + } + + /// The discounts of the party on a price (SPEC §11.3): none on a net price, else the two of the sales terms. + /// The price proposed. + /// The sales terms of the party. + /// The discounts. + public static DiscountQuote Discounts(PriceQuote price, PartySalesTerms? terms) + { + ArgumentNullException.ThrowIfNull(price); + if (price.Source == PriceSource.PartyNet || terms is null) + { + return DiscountQuote.None; + } + + decimal[] steps = [.. new[] { terms.Discount1, terms.Discount2 }.Where(d => d is > 0).Select(d => d!.Value)]; + return steps.Length == 0 ? DiscountQuote.None : new DiscountQuote(DiscountFormula.Format(steps), DiscountFormula.Equivalent(steps)); + } + + private PriceCell ListPrice(long itemId, long listId, DateOnly date, int depth) + { + if (depth > MaxDepth || !_lists.TryGetValue(listId, out var list)) + { + return PriceCell.Empty; + } + + if (OwnPrice(itemId, listId, date) is { } own) + { + return new PriceCell(own.Price, false, own.ValidFrom); + } + + if (list.BasePriceListId is { } parent && ListPrice(itemId, parent, date, depth + 1) is { Price: { } basePrice } from) + { + return new PriceCell(PriceRounding.Round(PriceRounding.Change(basePrice, list.MarkupPercent), list.RoundingStep), true, from.ValidFrom); + } + + return PriceCell.Empty; + } +} diff --git a/src/Khaemhat.Application/Items/PriceListService.cs b/src/Khaemhat.Application/Items/PriceListService.cs new file mode 100644 index 0000000..64adc17 --- /dev/null +++ b/src/Khaemhat.Application/Items/PriceListService.cs @@ -0,0 +1,360 @@ +using Khaemhat.Application.Audit; +using Khaemhat.Application.Querying; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Items; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Items; + +/// A column of the price grid: a price list. +/// The list. +/// Its code. +/// Its description. +/// The base list. +/// Derived from another list. +/// Prices with VAT. +public sealed record PriceListColumn(long Id, string Code, string Description, bool IsBase, bool Derived, bool VatIncluded); + +/// A row of the price grid: an item with its price in every list at the date. +/// The item. +/// Its code. +/// Its description. +/// Its unit. +/// Its average cost (standard when none), only for who sees costs. +/// The prices by list. +/// The net price of the party chosen, if any. +public sealed record PriceGridRow( + long ItemId, string Code, string Description, long? UnitOfMeasureId, decimal? AverageCost, IReadOnlyDictionary Prices, PriceCell? Net); + +/// The price grid (mockup 018). +/// The columns. +/// The rows. +public sealed record PriceGrid(IReadOnlyList Lists, ListPage Page); + +/// A price to write: of a list or net of a customer, valid from a day; no price removes the row of that day. +/// The item. +/// The list. +/// The customer. +/// The price, or none to remove it. +/// Valid from this day. +public sealed record PriceEdit(long ItemId, long? PriceListId, long? PartyId, decimal? Price, DateOnly? ValidFrom); + +/// A mass update of a price list (mockup 018): from the list itself or another one, a percent and a rounding. +public sealed record BulkUpdate +{ + /// The list to update. + public long PriceListId { get; init; } + + /// The list the prices start from; none: the list itself. + public long? SourcePriceListId { get; init; } + + /// The change in percent, also negative. + public decimal Percent { get; init; } + + /// The rounding step, such as 0.10, 0.50 or 1.00; zero: cents. + public decimal RoundingStep { get; init; } + + /// Rounding up, down or to the nearest. + public RoundingDirection Direction { get; init; } + + /// The prices are read at this day and the new ones are valid from it. + public DateOnly Date { get; init; } + + /// Only the items of this category. + public long? CategoryId { get; init; } + + /// Only these items (the selection); none: all the active items with a price. + public IReadOnlyList? ItemIds { get; init; } +} + +/// +/// Price lists (mockup 018, ADR 0030): the grid of items by lists at a date with the net prices of a customer, mass +/// updates, the writing of prices with their validity, and the price and discounts proposed for a document line. +/// +/// Permissions items.item.read and write; costs and margins with items.cost.read. +public sealed class PriceListService +{ + /// Error: a price is negative. + public const string NotNegative = ItemService.NotNegative; + + /// Error: the list of a mass update does not exist. + public const string ListUnknown = "items.price-list.unknown"; + + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly AuditTrail _audit; + private readonly ItemService _items; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The audit trail. + /// The items (for the cost permission). + public PriceListService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, ItemService items) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(audit); + ArgumentNullException.ThrowIfNull(items); + _factory = factory; + _permissions = permissions; + _audit = audit; + _items = items; + } + + /// The active price lists: the base one first, then by code. + /// Who reads. + /// The company. + /// Cancellation. + /// The lists. + public async Task> ListsAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ItemService.ReadPermission, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await ColumnsAsync(uow, cancellationToken).ConfigureAwait(false); + } + + /// The price grid: a page of items (no text items) with the price of every list at a date. + /// Who reads. + /// The company. + /// Search, filters (those of the items radar), sort, page. + /// The day the prices are read at. + /// The customer whose net prices are shown. + /// Cancellation. + /// The grid. + public async Task GridAsync(Actor actor, string companyCode, ListQuery query, DateOnly date, long? partyId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(query); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ItemService.ReadPermission, cancellationToken).ConfigureAwait(false); + var costs = await _items.CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var columns = await ColumnsAsync(uow, cancellationToken).ConfigureAwait(false); + var page = await uow.Repository().ListAsync( + ItemService.Fields.Apply(Query.For().Where(i => i.Kind != ItemKind.Text), query), cancellationToken).ConfigureAwait(false); + var book = await ItemService.BookAsync(uow, [.. page.Items.Select(i => i.Id)], cancellationToken).ConfigureAwait(false); + IReadOnlyList rows = + [ + .. page.Items.Select(i => new PriceGridRow( + i.Id, i.Code, i.Description, i.UnitOfMeasureId, costs ? i.AverageCost ?? i.StandardCost : null, + columns.ToDictionary(c => c.Id, c => book.ListPrice(i.Id, c.Id, date)), + partyId is { } party ? book.NetPrice(i.Id, party, date) is { } net ? new PriceCell(net.Price, false, net.ValidFrom) : PriceCell.Empty : null)), + ]; + return new PriceGrid(columns, new ListPage(rows, page.TotalCount, new Dictionary())); + } + + /// + /// Computes a mass update without saving it: for every item with a price in the source list at the date, the new + /// price of the list, changed by the percent and rounded. The screen shows them highlighted until saved. + /// + /// Who asks. + /// The company. + /// The update. + /// Cancellation. + /// The prices to write; unchanged ones are left out. + /// When the lists are unknown or the step negative. + public async Task> PreviewAsync(Actor actor, string companyCode, BulkUpdate update, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(update); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ItemService.WritePermission, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var lists = uow.Repository(); + var source = update.SourcePriceListId ?? update.PriceListId; + if (await lists.GetAsync(update.PriceListId, cancellationToken).ConfigureAwait(false) is null || await lists.GetAsync(source, cancellationToken).ConfigureAwait(false) is null) + { + throw new ValidationFailedException([nameof(BulkUpdate.PriceListId) + ":" + ListUnknown]); + } + + if (update.RoundingStep < 0) + { + throw new ValidationFailedException([nameof(BulkUpdate.RoundingStep) + ":" + TableCatalog.NumberRange]); + } + + var select = Query.For().Where(i => !i.Disabled && i.Kind != ItemKind.Text); + if (update.CategoryId is { } category) + { + select = select.Where(i => i.CategoryId == category); + } + + var items = (await uow.Repository().ListAsync(select, cancellationToken).ConfigureAwait(false)).Items; + if (update.ItemIds is { } wanted) + { + var only = wanted.ToHashSet(); + items = [.. items.Where(i => only.Contains(i.Id))]; + } + + var book = await ItemService.BookAsync(uow, [.. items.Select(i => i.Id)], cancellationToken).ConfigureAwait(false); + var edits = new List(); + foreach (var item in items.OrderBy(i => i.Code, StringComparer.Ordinal)) + { + if (book.ListPrice(item.Id, source, update.Date).Price is not { } from) + { + continue; + } + + var price = PriceRounding.Round(PriceRounding.Change(from, update.Percent), update.RoundingStep, update.Direction); + if (book.ListPrice(item.Id, update.PriceListId, update.Date).Price != price) + { + edits.Add(new PriceEdit(item.Id, update.PriceListId, null, price, update.Date)); + } + } + + return edits; + } + + /// + /// Writes prices: a row of the same list or customer and day is changed (or removed when the price is none), else a + /// new row starts that day, so the prices before it stay for older documents. A price equal to the one in effect is + /// not written again. Every change goes in the history of the item. + /// + /// Who saves. + /// The company. + /// The prices. + /// Cancellation. + /// How many rows were written or removed. + /// With the errors (index:code). + public async Task SaveAsync(Actor actor, string companyCode, IReadOnlyList edits, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(edits); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ItemService.WritePermission, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var problems = new List(); + var parties = uow.Repository(); + for (var i = 0; i < edits.Count; i++) + { + var edit = edits[i]; + if ((edit.PriceListId is null) == (edit.PartyId is null)) + { + problems.Add(i + ":" + ItemService.PriceTarget); + } + else if (edit.PartyId is { } partyId && await parties.GetAsync(partyId, cancellationToken).ConfigureAwait(false) is not { IsCustomer: true }) + { + problems.Add(i + ":" + ItemService.PriceParty); + } + + if (edit.Price < 0) + { + problems.Add(i + ":" + NotNegative); + } + } + + if (problems.Count > 0) + { + throw new ValidationFailedException(problems); + } + + var prices = uow.Repository(); + var written = 0; + foreach (var group in edits.GroupBy(e => e.ItemId)) + { + var itemId = group.Key; + var rows = (await prices.ListAsync(Query.For().Where(p => p.ItemId == itemId), cancellationToken).ConfigureAwait(false)).Items.ToList(); + foreach (var edit in group) + { + var same = rows.Where(r => r.PriceListId == edit.PriceListId && r.PartyId == edit.PartyId).ToList(); + var day = same.FirstOrDefault(r => r.ValidFrom == edit.ValidFrom); + if (edit.Price is not { } price) + { + if (day is not null) + { + await prices.DeleteAsync(day.Id, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Delete, itemId, day, null, actor.UserName, cancellationToken).ConfigureAwait(false); + rows.Remove(day); + written++; + } + + continue; + } + + if (day is not null) + { + if (day.Price != price) + { + var before = Copy(day); + day.Price = price; + await prices.UpdateAsync(day, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, itemId, before, day, actor.UserName, cancellationToken).ConfigureAwait(false); + written++; + } + + continue; + } + + if (edit.ValidFrom is { } from && PriceBook.At(same, from) is { } current && current.Price == price) + { + continue; + } + + var row = new ItemPrice { ItemId = itemId, PriceListId = edit.PriceListId, PartyId = edit.PartyId, Price = price, ValidFrom = edit.ValidFrom }; + row.Id = await prices.InsertAsync(row, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Insert, itemId, null, row, actor.UserName, cancellationToken).ConfigureAwait(false); + rows.Add(row); + written++; + } + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return written; + } + + /// + /// The price and the discounts proposed for an item on a document (SPEC §11.3): net price of the party, then the + /// list given or the one of the party, then the base list, then the item; the discounts of the party unless net. + /// + /// Who asks. + /// The company. + /// The item. + /// The party of the document. + /// The list of the document; none: the one of the party. + /// The date of the document. + /// Cancellation. + /// The price and the discounts. + public async Task<(PriceQuote Price, DiscountQuote Discounts)> QuoteAsync( + Actor actor, string companyCode, long itemId, long? partyId, long? priceListId, DateOnly date, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ItemService.ReadPermission, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await QuoteAsync(uow, itemId, partyId, priceListId, date, cancellationToken).ConfigureAwait(false); + } + + /// The price and the discounts of a line, inside the unit of work of a document. + /// The unit of work of the company. + /// The item. + /// The party of the document. + /// The list of the document; none: the one of the party. + /// The date of the document. + /// Cancellation. + /// The price and the discounts. + public static async Task<(PriceQuote Price, DiscountQuote Discounts)> QuoteAsync( + IUnitOfWork uow, long itemId, long? partyId, long? priceListId, DateOnly date, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(uow); + var item = await uow.Repository().GetAsync(itemId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(ItemService.NotFound); + var terms = partyId is { } party + ? await uow.Repository().FindAsync(Query.For().Where(t => t.PartyId == party), cancellationToken).ConfigureAwait(false) + : null; + var book = await ItemService.BookAsync(uow, [itemId], cancellationToken).ConfigureAwait(false); + var price = book.Quote(item, partyId, priceListId ?? terms?.PriceListId, date); + return (price, PriceBook.Discounts(price, terms)); + } + + private static async Task> ColumnsAsync(IUnitOfWork uow, CancellationToken cancellationToken) + { + var lists = (await uow.Repository().ListAsync(Query.For().Where(l => !l.Disabled), cancellationToken).ConfigureAwait(false)).Items; + var baseList = PriceBook.BaseOf(lists); + return + [ + .. lists.OrderBy(l => l.Id == baseList?.Id ? 0 : 1).ThenBy(l => l.Code, StringComparer.Ordinal) + .Select(l => new PriceListColumn(l.Id, l.Code, l.Description, l.Id == baseList?.Id, l.BasePriceListId is not null, l.VatIncluded)), + ]; + } + + private static ItemPrice Copy(ItemPrice price) => new() + { + Id = price.Id, ItemId = price.ItemId, PriceListId = price.PriceListId, PartyId = price.PartyId, Price = price.Price, ValidFrom = price.ValidFrom, + }; +} diff --git a/src/Khaemhat.Application/Jobs/JobScheduler.cs b/src/Khaemhat.Application/Jobs/JobScheduler.cs index dd428a0..ab6a824 100644 --- a/src/Khaemhat.Application/Jobs/JobScheduler.cs +++ b/src/Khaemhat.Application/Jobs/JobScheduler.cs @@ -39,7 +39,8 @@ public interface IScheduledJob /// The job type. /// When it runs. /// Its timeout. -public sealed record SystemTaskDefinition(string Code, string Name, string JobType, string Cron, int TimeoutSeconds = 600); +/// Whether it calls services outside the instance (the tests run it with a stub). +public sealed record SystemTaskDefinition(string Code, string Name, string JobType, string Cron, int TimeoutSeconds = 600, bool UsesNetwork = false); /// /// The scheduler (SPEC §9.4; mockup 083): reads sys_scheduled_tasks, runs the due ones with a lock in @@ -49,13 +50,14 @@ public sealed record SystemTaskDefinition(string Code, string Name, string JobTy /// public sealed class JobScheduler { - /// The system tasks (M2, attachments trash from M3). + /// The system tasks (M2, attachments trash from M3, ECB rates from M4). public static readonly IReadOnlyList SystemTasks = [ new("system.sessions-cleanup", "Pulizia sessioni scadute", SessionCleanupJob.JobType, "15 * * * *", 300), new("system.license-check", "Verifica licenza", LicenseCheckJob.JobType, "0 * * * *", 120), new("system.log-retention", "Conservazione del log", LogRetentionJob.JobType, "30 3 * * *", 1800), new("system.attachments-trash", "Svuotamento cestino allegati", Files.AttachmentTrashPurgeJob.JobType, "45 3 * * *", 1800), + new("system.ecb-rates", "Cambi di riferimento BCE", Tables.EcbRatesJob.JobType, "30 16 * * 1-5", 300, UsesNetwork: true), ]; private readonly IUnitOfWorkFactory _factory; diff --git a/src/Khaemhat.Application/Khaemhat.Application.csproj b/src/Khaemhat.Application/Khaemhat.Application.csproj index c5adc45..060cc02 100644 --- a/src/Khaemhat.Application/Khaemhat.Application.csproj +++ b/src/Khaemhat.Application/Khaemhat.Application.csproj @@ -9,6 +9,11 @@ + + + + + diff --git a/src/Khaemhat.Application/Parties/PartyService.cs b/src/Khaemhat.Application/Parties/PartyService.cs new file mode 100644 index 0000000..c5ad394 --- /dev/null +++ b/src/Khaemhat.Application/Parties/PartyService.cs @@ -0,0 +1,1020 @@ +using System.Data.Common; +using Khaemhat.Application.Audit; +using Khaemhat.Core.Instance; +using Khaemhat.Application.Querying; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Application.Items; +using Khaemhat.Core.Items; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Tables; +using Khaemhat.Core.Validation; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; +using Khaemhat.Infrastructure.Http; + +namespace Khaemhat.Application.Parties; + +/// A party with every detail: what the record page shows and saves in one go. +public sealed class PartyRecord +{ + /// The party. + public Party Party { get; set; } = new(); + + /// The sales terms (customers). + public PartySalesTerms Sales { get; set; } = new(); + + /// The purchase terms (suppliers). + public PartyPurchaseTerms Purchase { get; set; } = new(); + + /// The fiscal data. + public PartyFiscal Fiscal { get; set; } = new(); + + /// The other addresses. + public List Addresses { get; set; } = []; + + /// The contact people. + public List Contacts { get; set; } = []; + + /// The bank accounts. + public List BankAccounts { get; set; } = []; + + /// The codes the party uses for our items (tab Articoli e codici). + public List ItemCodes { get; set; } = []; +} + +/// Which parties a radar shows (menu Anagrafiche). +public enum PartyArchive +{ + /// Customers (also those that are suppliers). + Customers = 0, + + /// Suppliers (also customers that are suppliers). + Suppliers = 1, + + /// Prospects and leads. + Contacts = 2, +} + +/// A row of the radar of the parties (mockup 012). +/// The id. +/// The code. +/// The name. +/// What the party is. +/// A customer that is also a supplier. +/// The kind of subject. +/// The VAT number. +/// The tax code. +/// The city. +/// The province. +/// The country. +/// The salesperson. +/// The category. +/// Disabled. +public sealed record PartyRow( + long Id, string Code, string Name, PartyKind Kind, bool IsAlsoSupplier, SubjectType SubjectType, string? VatNumber, string? TaxCode, string? City, + string? Province, string CountryCode, long? SalespersonId, long? CategoryId, bool Disabled) +{ + /// The terms of the row, filled for the page shown. + public PartyRowTerms? Terms { get; init; } + + /// VAT number or, without one, tax code (column P.IVA / C.F.). + public string? Identifier => VatNumber ?? TaxCode; +} + +/// The terms shown on a radar row. +/// The payment terms. +/// The price list. +/// Orders blocked. +/// Split payment. +public sealed record PartyRowTerms(long? PaymentTermId, long? PriceListId, bool Blocked, bool SplitPayment); + +/// What deleting a party did. +public enum PartyDeleteOutcome +{ + /// The party is gone. + Deleted = 0, + + /// The party is used by documents: it was disabled instead. + Disabled = 1, +} + +/// +/// The parties (SPEC §11.2, issue #41, ADR 0029): radar, read and save of a party with its details in one transaction, +/// automatic codes by kind, the checks of the fiscal pack, the VIES check of EU numbers, conversion of leads and prospects +/// into customers, delete or disable. +/// +/// Permissions parties.party.read, write, delete. +public sealed class PartyService +{ + /// Permission to see the parties. + public const string ReadPermission = "parties.party.read"; + + /// Permission to create and change the parties. + public const string WritePermission = "parties.party.write"; + + /// Permission to delete the parties. + public const string DeletePermission = "parties.party.delete"; + + /// Error: the name is missing. + public const string NameRequired = "parties.name.required"; + + /// Error: the VAT number is required for this kind of subject. + public const string VatNumberRequired = "parties.vat-number.required"; + + /// Error: a public administration needs a VAT number or a tax code. + public const string IdentifierRequired = "parties.identifier.required"; + + /// Error: the tax code is not valid. + public const string TaxCodeInvalid = "parties.tax-code.invalid"; + + /// Warning: a private customer without tax code. + public const string TaxCodeMissing = "parties.tax-code.missing"; + + /// Error: another party has the code. + public const string CodeDuplicate = "parties.code.duplicate"; + + /// Error: the country is not in the table of the countries. + public const string CountryUnknown = "parties.country.unknown"; + + /// Error: an EU subject needs a member state other than the company's. + public const string CountryNotEu = "parties.country.not-eu"; + + /// Error: a domestic subject needs the company's country. + public const string CountryNotDomestic = "parties.country.not-domestic"; + + /// Warning: another party has the same VAT number. + public const string VatNumberDuplicate = "parties.vat-number.duplicate"; + + /// Error: a declaration of intent needs number and ceiling. + public const string IntentIncomplete = "parties.intent.incomplete"; + + /// Error: the exigibility is not I, D or S. + public const string ExigibilityInvalid = "parties.exigibility.invalid"; + + /// Error: the day of the month is not 1-31. + public const string DayRange = "parties.day.range"; + + /// Error: a value cannot be negative. + public const string NotNegative = "parties.value.negative"; + + /// Error: an address or contact without name, a bank account without IBAN. + public const string DetailRequired = "parties.detail.required"; + + /// Error: the party is not a lead or prospect, nor a supplier (conversion). + public const string AlreadyCustomer = "parties.convert.already-customer"; + + /// Error: the party changed or was deleted meanwhile. + public const string NotFound = "parties.not-found"; + + /// The entity name of the attachments and the history. + public const string Entity = "parties.party"; + + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly AuditTrail _audit; + private readonly CompanyFiscalContext _fiscal; + private readonly CodeRuleService _codes; + private readonly AutoFillService _autoFill; + private readonly TimeProvider _clock; + + /// Creates the service. + /// Opens the company databases. + /// Checks permissions. + /// Writes the history. + /// The fiscal pack of each company. + /// The automatic codes. + /// The automatic filling options and the VIES check. + /// The clock. + public PartyService( + IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, CompanyFiscalContext fiscal, CodeRuleService codes, AutoFillService autoFill, + TimeProvider clock) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(audit); + ArgumentNullException.ThrowIfNull(fiscal); + ArgumentNullException.ThrowIfNull(codes); + ArgumentNullException.ThrowIfNull(autoFill); + ArgumentNullException.ThrowIfNull(clock); + _factory = factory; + _permissions = permissions; + _audit = audit; + _fiscal = fiscal; + _codes = codes; + _autoFill = autoFill; + _clock = clock; + } + + /// The fields of the radar: search on code, name, VAT number, tax code and city. + public static ListFields Fields { get; } = new ListFields() + .Add("code", p => p.Code, searchable: true) + .Add("name", p => p.Name, searchable: true) + .Add("vatNumber", p => p.VatNumber, searchable: true) + .Add("taxCode", p => p.TaxCode, searchable: true) + .Add("city", p => p.City, searchable: true) + .Add("province", p => p.Province) + .Add("country", p => p.CountryCode) + .Add("subjectType", p => p.SubjectType) + .Add("kind", p => p.Kind) + .Add("salesperson", p => p.SalespersonId) + .Add("category", p => p.CategoryId) + .Add("disabled", p => p.Disabled) + .OrderByDefault(new ListSort("name")); + + /// The code archive of a kind of party (ADR 0027). + /// The kind. + /// The key of . + public static string CodeRuleOf(PartyKind kind) => kind switch + { + PartyKind.Customer => "customers", + PartyKind.Supplier => "suppliers", + _ => "leads", + }; + + /// The kind of e-invoice recipient of a subject. + /// The kind of subject. + /// The recipient kind. + public static RecipientKind RecipientOf(SubjectType subject) => subject switch + { + SubjectType.PublicAdministration => RecipientKind.PublicAdministration, + SubjectType.Person => RecipientKind.Consumer, + SubjectType.EuCompany or SubjectType.NonEuCompany => RecipientKind.Foreign, + _ => RecipientKind.Business, + }; + + /// A page of the radar. + /// Who reads. + /// The company. + /// Customers, suppliers or contacts. + /// Search, filters, ordering and page. + /// Cancellation. + /// The page, with the terms of its rows. + public async Task> ListAsync(Actor actor, string companyCode, PartyArchive archive, ListQuery query, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(query); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var select = archive switch + { + PartyArchive.Customers => Query.For().Where(p => p.Kind == PartyKind.Customer), + PartyArchive.Suppliers => Query.For().Where(p => p.Kind == PartyKind.Supplier || (p.Kind == PartyKind.Customer && p.IsAlsoSupplier)), + _ => Query.For().Where(p => p.Kind == PartyKind.Prospect || p.Kind == PartyKind.Lead), + }; + var page = await uow.Repository().ListAsync(Fields.Apply(select, query), cancellationToken).ConfigureAwait(false); + var ids = page.Items.Select(p => p.Id).ToList(); + var sales = ids.Count == 0 + ? [] + : (await uow.Repository().ListAsync(Query.For().Where(s => ids.Contains(s.PartyId)), cancellationToken).ConfigureAwait(false)).Items; + var purchase = ids.Count == 0 + ? [] + : (await uow.Repository().ListAsync(Query.For().Where(s => ids.Contains(s.PartyId)), cancellationToken).ConfigureAwait(false)).Items; + var fiscal = ids.Count == 0 + ? [] + : (await uow.Repository().ListAsync(Query.For().Where(s => ids.Contains(s.PartyId)), cancellationToken).ConfigureAwait(false)).Items; + var salesBy = sales.ToDictionary(s => s.PartyId); + var purchaseBy = purchase.ToDictionary(s => s.PartyId); + var fiscalBy = fiscal.ToDictionary(s => s.PartyId); + IReadOnlyList rows = + [ + .. page.Items.Select(p => RowOf(p) with + { + Terms = new PartyRowTerms( + archive == PartyArchive.Suppliers ? purchaseBy.GetValueOrDefault(p.Id)?.PaymentTermId : salesBy.GetValueOrDefault(p.Id)?.PaymentTermId, + salesBy.GetValueOrDefault(p.Id)?.PriceListId, + salesBy.GetValueOrDefault(p.Id)?.Blocked ?? false, + fiscalBy.GetValueOrDefault(p.Id)?.SplitPayment ?? false), + }), + ]; + return new ListPage(rows, page.TotalCount, new Dictionary()); + } + + /// Parties for a hotlink: active ones whose code or name starts with or contains the text. + /// Who reads. + /// The company. + /// Customers, suppliers or contacts. + /// The text typed. + /// Cancellation. + /// Up to 20 rows. + public async Task> SearchAsync(Actor actor, string companyCode, PartyArchive archive, string? text, CancellationToken cancellationToken = default) + { + var page = await ListAsync( + actor, companyCode, archive, + new ListQuery { Search = text, Filters = [ListFilter.Of("disabled", ListFilterOperator.Equals, "false")], Limit = 20 }, + cancellationToken).ConfigureAwait(false); + return page.Items; + } + + /// A party with every detail. + /// Who reads. + /// The company. + /// The party. + /// Cancellation. + /// The record, or . + public async Task GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await LoadAsync(uow, id, cancellationToken).ConfigureAwait(false); + } + + /// A new party of a kind, with the values proposed by the company (country, currency, defaults). + /// Who creates it. + /// The company. + /// The kind. + /// Cancellation. + /// The record, not saved. + public async Task NewAsync(Actor actor, string companyCode, PartyKind kind, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false); + var today = DateOnly.FromDateTime(_clock.GetLocalNow().DateTime); + return new PartyRecord + { + Party = new Party { Kind = kind, CountryCode = pack.CountryCode, Since = kind is PartyKind.Customer or PartyKind.Supplier ? today : null }, + }; + } + + /// Checks a record without saving it: normalizes it in place and returns errors and warnings. + /// Who checks. + /// The company. + /// The record. + /// Cancellation. + /// The problems, with fields such as VatNumber, Fiscal.RecipientCode or Addresses.0.Name. + public async Task> ValidateAsync(Actor actor, string companyCode, PartyRecord record, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(record); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await CheckAsync(uow, pack, record, cancellationToken).ConfigureAwait(false); + } + + /// + /// Saves a party with its details: inserts it when its id is 0 (assigning the code when empty), updates it otherwise. + /// An EU VAT number that is new or changed is checked on VIES when the option is on; the outcome is saved. + /// + /// Who saves. + /// The company. + /// The record. + /// Cancellation. + /// The saved record, read back. + /// A rule failed; errors are Field:code. + /// Someone else changed the party meanwhile. + public Task SaveAsync(Actor actor, string companyCode, PartyRecord record, CancellationToken cancellationToken = default) => + SaveAsync(actor, companyCode, record, null, cancellationToken); + + /// Saves a party with its details, choosing whether to check an EU VAT number on VIES (the import asks it in its options). + /// Who saves. + /// The company. + /// The record. + /// Check on VIES; : as the automatic filling option of the company says. + /// Cancellation. + /// The saved record, read back. + /// A rule failed; errors are Field:code. + /// Someone else changed the party meanwhile. + public async Task SaveAsync(Actor actor, string companyCode, PartyRecord record, bool? verifyVat, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(record); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false); + var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false); + var party = record.Party; + long id; + PartyRecord? before; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + before = party.Id == 0 ? null : await LoadAsync(uow, party.Id, cancellationToken).ConfigureAwait(false) ?? throw new ValidationFailedException([":" + NotFound]); + var problems = (await CheckAsync(uow, pack, record, cancellationToken).ConfigureAwait(false)).Where(p => !p.IsWarning).Select(p => p.Field + ":" + p.Code).ToList(); + var codeChanged = before is null || !string.Equals(before.Party.Code, party.Code, StringComparison.Ordinal); + var rule = await _codes.RuleAsync(company, CodeRuleOf(party.Kind), cancellationToken).ConfigureAwait(false); + if (party.Code.Length > 0 && codeChanged && CodeRuleService.CheckManual(rule, party.Code) is { } manual) + { + problems.Add(nameof(Party.Code) + ":" + manual); + } + + if (problems.Count > 0) + { + throw new ValidationFailedException(problems); + } + + if (party.Code.Length == 0) + { + var today = DateOnly.FromDateTime(_clock.GetLocalNow().DateTime); + party.Code = await CodeRuleService.AssignAsync(uow, rule, today, null, (c, ct) => TakenAsync(uow, c, ct), cancellationToken).ConfigureAwait(false); + } + + id = await WriteAsync(uow, record, before, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + if (party.SubjectType == SubjectType.EuCompany && party.VatNumber is { Length: > 0 } + && (before is null || before.Party.VatNumber != party.VatNumber || before.Party.CountryCode != party.CountryCode || before.Party.VatCheck == VatCheckStatus.None) + && (verifyVat ?? await _autoFill.IsOnAsync(company, AutoFillService.Vies, cancellationToken).ConfigureAwait(false))) + { + await CheckVatCoreAsync(company, id, actor.UserName, cancellationToken).ConfigureAwait(false); + } + + await using var read = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await LoadAsync(read, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound); + } + + /// Checks the VAT number of an EU party on VIES now (action VIES) and saves the outcome. + /// Who asks. + /// The company. + /// The party. + /// Cancellation. + /// The answer of VIES, or when the party has no VAT number of a member state. + public async Task CheckVatAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false); + return await CheckVatCoreAsync(company, id, actor.UserName, cancellationToken).ConfigureAwait(false); + } + + /// + /// Turns a lead or prospect into a customer with a customer code (the old code stays in + /// ), or makes a supplier also a customer (it keeps its code). + /// + /// Who converts. + /// The company. + /// The party. + /// Cancellation. + /// The party. + public async Task ConvertToCustomerAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false); + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + var party = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound); + var before = Clone(party); + switch (party.Kind) + { + case PartyKind.Customer: + throw new ValidationFailedException(["Kind:" + AlreadyCustomer]); + case PartyKind.Supplier: + party.Kind = PartyKind.Customer; + party.IsAlsoSupplier = true; + break; + default: + var rule = await _codes.RuleAsync(company, CodeRuleOf(PartyKind.Customer), cancellationToken).ConfigureAwait(false); + var today = DateOnly.FromDateTime(_clock.GetLocalNow().DateTime); + party.PreviousCode = party.Code; + party.Code = await CodeRuleService.AssignAsync(uow, rule, today, null, (c, ct) => TakenAsync(uow, c, ct), cancellationToken).ConfigureAwait(false); + party.Kind = PartyKind.Customer; + party.Since ??= today; + break; + } + + await repository.UpdateAsync(party, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, id, before, party, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + return await GetAsync(actor, company, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound); + } + + /// Disables or enables parties (radar action Disabilita). + /// Who acts. + /// The company. + /// The parties. + /// Disable or enable. + /// Cancellation. + /// The parties changed. + public async Task SetDisabledAsync(Actor actor, string companyCode, IEnumerable ids, bool disabled, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(ids); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + var changed = 0; + foreach (var id in ids.Distinct()) + { + if (await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } party && party.Disabled != disabled) + { + var before = Clone(party); + party.Disabled = disabled; + await repository.UpdateAsync(party, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, id, before, party, actor.UserName, cancellationToken).ConfigureAwait(false); + changed++; + } + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return changed; + } + + /// Deletes a party never used, or disables it when documents refer to it. + /// Who deletes. + /// The company. + /// The party. + /// Cancellation. + /// What happened. + public async Task DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, DeletePermission, cancellationToken).ConfigureAwait(false); + try + { + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var before = await LoadAsync(uow, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound); + + // The details go with the party (cascade); the documents of later milestones refuse the delete. + await uow.Repository().DeleteAsync(id, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Delete, id, before.Party, null, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return PartyDeleteOutcome.Deleted; + } + catch (DbException) + { + await SetDisabledAsync(actor, company, [id], true, cancellationToken).ConfigureAwait(false); + return PartyDeleteOutcome.Disabled; + } + } + + /// The history of a party, newest first. + /// Who reads. + /// The company. + /// The party. + /// Cancellation. + /// The changes of the party and of its details. + public async Task> HistoryAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var key = id.ToString(System.Globalization.CultureInfo.InvariantCulture); + var entries = new List(); + foreach (var entity in new[] { nameof(Party), nameof(PartySalesTerms), nameof(PartyPurchaseTerms), nameof(PartyFiscal) }) + { + entries.AddRange(await AuditTrail.HistoryAsync(uow, entity, key, cancellationToken).ConfigureAwait(false)); + } + + return [.. entries.OrderByDescending(e => e.At).ThenByDescending(e => e.Id)]; + } + + /// The rows of some parties, for the lookups that show them by id. + /// Who reads. + /// The company. + /// The parties. + /// Cancellation. + /// The rows found. + public async Task> RowsAsync(Actor actor, string companyCode, IEnumerable ids, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(ids); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + long[] wanted = [.. ids.Distinct()]; + if (wanted.Length == 0) + { + return []; + } + + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return [.. (await uow.Repository().ListAsync(Query.For().Where(p => wanted.Contains(p.Id)), cancellationToken).ConfigureAwait(false)).Items.Select(RowOf)]; + } + + private static PartyRow RowOf(Party p) => + new(p.Id, p.Code, p.Name, p.Kind, p.IsAlsoSupplier, p.SubjectType, p.VatNumber, p.TaxCode, p.City, p.Province, p.CountryCode, p.SalespersonId, p.CategoryId, p.Disabled); + + private static async Task TakenAsync(IUnitOfWork uow, string code, CancellationToken cancellationToken) => + await uow.Repository().CountAsync(Query.For().Where(p => p.Code == code), cancellationToken).ConfigureAwait(false) > 0; + + private static async Task LoadAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) + { + if (await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } party) + { + return null; + } + + return new PartyRecord + { + Party = party, + Sales = await uow.Repository().FindAsync(Query.For().Where(s => s.PartyId == id), cancellationToken).ConfigureAwait(false) + ?? new PartySalesTerms { PartyId = id }, + Purchase = await uow.Repository().FindAsync(Query.For().Where(s => s.PartyId == id), cancellationToken).ConfigureAwait(false) + ?? new PartyPurchaseTerms { PartyId = id }, + Fiscal = await uow.Repository().FindAsync(Query.For().Where(s => s.PartyId == id), cancellationToken).ConfigureAwait(false) + ?? new PartyFiscal { PartyId = id }, + Addresses = [.. (await uow.Repository().ListAsync(Query.For().Where(a => a.PartyId == id).OrderBy(a => a.Id), cancellationToken).ConfigureAwait(false)).Items], + Contacts = [.. (await uow.Repository().ListAsync(Query.For().Where(a => a.PartyId == id).OrderBy(a => a.Id), cancellationToken).ConfigureAwait(false)).Items], + BankAccounts = [.. (await uow.Repository().ListAsync(Query.For().Where(a => a.PartyId == id).OrderBy(a => a.Id), cancellationToken).ConfigureAwait(false)).Items], + ItemCodes = [.. (await uow.Repository().ListAsync(Query.For().Where(a => a.PartyId == id).OrderBy(a => a.Code), cancellationToken).ConfigureAwait(false)).Items], + }; + } + + private async Task WriteAsync(IUnitOfWork uow, PartyRecord record, PartyRecord? before, string userName, CancellationToken cancellationToken) + { + var party = record.Party; + var parties = uow.Repository(); + if (before is null) + { + party.Id = await parties.InsertAsync(party, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Insert, party.Id, null, party, userName, cancellationToken).ConfigureAwait(false); + } + else + { + await parties.UpdateAsync(party, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, party.Id, before.Party, party, userName, cancellationToken).ConfigureAwait(false); + } + + var id = party.Id; + await UpsertAsync(uow, record.Sales, before?.Sales, id, userName, s => s.PartyId = id, cancellationToken).ConfigureAwait(false); + await UpsertAsync(uow, record.Purchase, before?.Purchase, id, userName, s => s.PartyId = id, cancellationToken).ConfigureAwait(false); + await UpsertAsync(uow, record.Fiscal, before?.Fiscal, id, userName, s => s.PartyId = id, cancellationToken).ConfigureAwait(false); + await ReplaceAsync(uow, record.Addresses, before?.Addresses ?? [], a => a.PartyId = id, cancellationToken).ConfigureAwait(false); + await ReplaceAsync(uow, record.Contacts, before?.Contacts ?? [], a => a.PartyId = id, cancellationToken).ConfigureAwait(false); + await ReplaceAsync(uow, record.BankAccounts, before?.BankAccounts ?? [], a => a.PartyId = id, cancellationToken).ConfigureAwait(false); + await ReplaceAsync(uow, record.ItemCodes, before?.ItemCodes ?? [], a => a.PartyId = id, cancellationToken).ConfigureAwait(false); + return id; + } + + // The one-to-one details: inserted the first time, then updated; the history is kept under the id of the party. + private async Task UpsertAsync(IUnitOfWork uow, T row, T? before, long partyId, string userName, Action link, CancellationToken cancellationToken) + where T : Core.Entities.Entity, new() + { + link(row); + var repository = uow.Repository(); + if (before is null || before.Id == 0) + { + row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false); + return; + } + + row.Id = before.Id; + row.RowVersion = before.RowVersion; + await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, partyId, before, row, userName, cancellationToken).ConfigureAwait(false); + } + + // The lists: rows removed are deleted, rows kept are updated, new rows inserted. + private static async Task ReplaceAsync(IUnitOfWork uow, List rows, List before, Action link, CancellationToken cancellationToken) + where T : Core.Entities.Entity, new() + { + var repository = uow.Repository(); + var kept = rows.Where(r => r.Id != 0).Select(r => r.Id).ToHashSet(); + foreach (var old in before.Where(b => !kept.Contains(b.Id))) + { + await repository.DeleteAsync(old.Id, cancellationToken).ConfigureAwait(false); + } + + var versions = before.ToDictionary(b => b.Id, b => b.RowVersion); + foreach (var row in rows) + { + link(row); + if (row.Id != 0 && versions.TryGetValue(row.Id, out var version)) + { + row.RowVersion = version; + await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false); + } + else + { + row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false); + } + } + } + + private async Task CheckVatCoreAsync(string company, long id, string userName, CancellationToken cancellationToken) + { + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + var party = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound); + if (party.VatNumber is not { Length: > 0 } number || ViesClient.MemberStateCode(party.CountryCode) is not { } state) + { + return null; + } + + var result = await _autoFill.CheckVatAsync(state, number, cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + party = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound); + var before = Clone(party); + party.VatCheck = result.Status switch + { + ViesStatus.Valid => VatCheckStatus.Valid, + ViesStatus.Invalid or ViesStatus.InvalidInput => VatCheckStatus.Invalid, + _ => VatCheckStatus.Unavailable, + }; + party.VatCheckedAt = result.CheckedAt.UtcDateTime; + await repository.UpdateAsync(party, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, id, before, party, userName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return result; + } + + private static async Task> CheckAsync(IUnitOfWork uow, IFiscalPack pack, PartyRecord record, CancellationToken cancellationToken) + { + var problems = new List(); + var party = record.Party; + var trading = party.Kind is PartyKind.Customer or PartyKind.Supplier; + Normalize(party); + + if (party.SubjectType == SubjectType.Person && party.Name.Length == 0 && (party.LastName is not null || party.FirstName is not null)) + { + party.Name = string.Join(' ', new[] { party.LastName, party.FirstName }.Where(n => n is not null)); + } + + if (party.Name.Length == 0) + { + problems.Add(new(nameof(Party.Name), NameRequired)); + } + + if (party.Code.Length > 0) + { + var code = party.Code; + var id = party.Id; + if (await uow.Repository().CountAsync(Query.For().Where(p => p.Code == code && p.Id != id), cancellationToken).ConfigureAwait(false) > 0) + { + problems.Add(new(nameof(Party.Code), CodeDuplicate)); + } + } + + // Country: the domestic subjects live in the company's country, the EU ones in another member state. + var countryCode = party.CountryCode; + var country = await uow.Repository().FindAsync(Query.For().Where(c => c.Code == countryCode), cancellationToken).ConfigureAwait(false); + var domestic = party.CountryCode == pack.CountryCode; + if (country is null) + { + problems.Add(new(nameof(Party.CountryCode), CountryUnknown)); + } + else if (party.SubjectType == SubjectType.EuCompany && (!country.EuMember || domestic)) + { + problems.Add(new(nameof(Party.CountryCode), CountryNotEu)); + } + else if (party.SubjectType is SubjectType.Company or SubjectType.PublicAdministration or SubjectType.FlatRate && !domestic) + { + problems.Add(new(nameof(Party.CountryCode), CountryNotDomestic)); + } + + var rules = pack.GetFeature(); + if (party.VatNumber is not null) + { + if (domestic && rules is not null) + { + party.VatNumber = rules.NormalizeVatNumber(party.VatNumber); + if (!rules.IsValidVatNumber(party.VatNumber)) + { + problems.Add(new(nameof(Party.VatNumber), TableCatalog.VatNumberInvalid)); + } + } + else if ((country?.VatPrefix ?? country?.Code) is { } prefix && party.VatNumber.StartsWith(prefix, StringComparison.Ordinal)) + { + party.VatNumber = party.VatNumber[prefix.Length..]; + } + + var vat = party.VatNumber; + var self = party.Id; + if (await uow.Repository().CountAsync(Query.For().Where(p => p.VatNumber == vat && p.CountryCode == countryCode && p.Id != self), cancellationToken).ConfigureAwait(false) > 0) + { + problems.Add(new(nameof(Party.VatNumber), VatNumberDuplicate, IsWarning: true)); + } + } + else if (trading && party.SubjectType is SubjectType.Company or SubjectType.FlatRate or SubjectType.EuCompany) + { + problems.Add(new(nameof(Party.VatNumber), VatNumberRequired)); + } + + if (party.TaxCode is not null && domestic && rules is not null && !rules.IsValidTaxCode(party.TaxCode)) + { + problems.Add(new(nameof(Party.TaxCode), TaxCodeInvalid)); + } + + if (trading && party.SubjectType == SubjectType.PublicAdministration && party.VatNumber is null && party.TaxCode is null) + { + problems.Add(new(nameof(Party.TaxCode), IdentifierRequired)); + } + + if (party.Kind == PartyKind.Customer && party.SubjectType == SubjectType.Person && party.TaxCode is null) + { + problems.Add(new(nameof(Party.TaxCode), TaxCodeMissing, IsWarning: true)); + } + + Email(party.Email, nameof(Party.Email), problems); + Email(party.Pec, nameof(Party.Pec), problems); + CheckFiscal(record.Fiscal, party, rules, problems); + CheckTerms(record, problems); + CheckDetails(record, pack, problems); + return problems; + } + + private static void Normalize(Party party) + { + party.Code = party.Code.Trim().ToUpperInvariant(); + party.Name = party.Name.Trim(); + party.FirstName = Clean(party.FirstName); + party.LastName = Clean(party.LastName); + party.FiscalName = Clean(party.FiscalName); + party.VatNumber = Clean(party.VatNumber)?.Replace(" ", string.Empty, StringComparison.Ordinal).ToUpperInvariant(); + party.TaxCode = Clean(party.TaxCode)?.Replace(" ", string.Empty, StringComparison.Ordinal).ToUpperInvariant(); + party.Province = Clean(party.Province)?.ToUpperInvariant(); + party.CountryCode = (Clean(party.CountryCode) ?? string.Empty).ToUpperInvariant(); + party.CurrencyCode = (Clean(party.CurrencyCode) ?? "EUR").ToUpperInvariant(); + party.Language = (Clean(party.Language) ?? "it").ToLowerInvariant(); + party.Email = Clean(party.Email); + party.Pec = Clean(party.Pec); + party.PostalCode = Clean(party.PostalCode); + party.City = Clean(party.City); + party.Address = Clean(party.Address); + } + + private static void CheckFiscal(PartyFiscal fiscal, Party party, ITaxIdentifierRules? rules, List problems) + { + fiscal.RecipientCode = Clean(fiscal.RecipientCode)?.ToUpperInvariant(); + fiscal.RecipientPec = Clean(fiscal.RecipientPec); + fiscal.Exigibility = Clean(fiscal.Exigibility)?.ToUpperInvariant(); + var recipient = RecipientOf(party.SubjectType); + if (party.Kind is PartyKind.Customer && rules is not null) + { + // Consumers and foreign customers get the code of the e-invoice format; a business with only a PEC gets 0000000. + if (fiscal.RecipientCode is null && (recipient is RecipientKind.Consumer or RecipientKind.Foreign || fiscal.RecipientPec is not null)) + { + fiscal.RecipientCode = rules.DefaultRecipientCode(recipient); + } + + problems.AddRange(rules.CheckRecipientCode(fiscal.RecipientCode, recipient) + .Select(p => new TableProblem("Fiscal." + p.Field, p.Code, p.Severity == FiscalProblemSeverity.Warning))); + } + + Email(fiscal.RecipientPec, "Fiscal." + nameof(PartyFiscal.RecipientPec), problems); + if (fiscal.SplitPayment) + { + fiscal.Exigibility = "S"; + } + + if (fiscal.Exigibility is not (null or "I" or "D" or "S")) + { + problems.Add(new("Fiscal." + nameof(PartyFiscal.Exigibility), ExigibilityInvalid)); + } + + Percent(fiscal.WithholdingRate, "Fiscal." + nameof(PartyFiscal.WithholdingRate), problems); + Percent(fiscal.PensionFundRate, "Fiscal." + nameof(PartyFiscal.PensionFundRate), problems); + if (fiscal.IntentActive) + { + fiscal.IntentNumber = Clean(fiscal.IntentNumber); + if (fiscal.IntentNumber is null) + { + problems.Add(new("Fiscal." + nameof(PartyFiscal.IntentNumber), IntentIncomplete)); + } + + if (fiscal.IntentCeiling is null) + { + problems.Add(new("Fiscal." + nameof(PartyFiscal.IntentCeiling), IntentIncomplete)); + } + } + + if (fiscal.IntentCeiling < 0) + { + problems.Add(new("Fiscal." + nameof(PartyFiscal.IntentCeiling), NotNegative)); + } + + if (fiscal.IntentFrom is { } from && fiscal.IntentTo is { } to && to < from) + { + problems.Add(new("Fiscal." + nameof(PartyFiscal.IntentTo), TableCatalog.ValidityOrder)); + } + } + + private static void CheckTerms(PartyRecord record, List problems) + { + var sales = record.Sales; + Percent(sales.Discount1, "Sales." + nameof(PartySalesTerms.Discount1), problems); + Percent(sales.Discount2, "Sales." + nameof(PartySalesTerms.Discount2), problems); + if (sales.CreditLimit < 0) + { + problems.Add(new("Sales." + nameof(PartySalesTerms.CreditLimit), NotNegative)); + } + + if (sales.InvoiceDay is < 1 or > 31) + { + problems.Add(new("Sales." + nameof(PartySalesTerms.InvoiceDay), DayRange)); + } + + sales.DocumentsEmail = Clean(sales.DocumentsEmail); + Email(sales.DocumentsEmail, "Sales." + nameof(PartySalesTerms.DocumentsEmail), problems); + + var purchase = record.Purchase; + Percent(purchase.Discount, "Purchase." + nameof(PartyPurchaseTerms.Discount), problems); + if (purchase.LeadTimeDays < 0) + { + problems.Add(new("Purchase." + nameof(PartyPurchaseTerms.LeadTimeDays), NotNegative)); + } + + if (purchase.MinimumOrder < 0) + { + problems.Add(new("Purchase." + nameof(PartyPurchaseTerms.MinimumOrder), NotNegative)); + } + + purchase.OrdersEmail = Clean(purchase.OrdersEmail); + Email(purchase.OrdersEmail, "Purchase." + nameof(PartyPurchaseTerms.OrdersEmail), problems); + } + + private static void CheckDetails(PartyRecord record, IFiscalPack pack, List problems) + { + for (var i = 0; i < record.Addresses.Count; i++) + { + var address = record.Addresses[i]; + address.Name = address.Name.Trim(); + address.CountryCode = (Clean(address.CountryCode) ?? pack.CountryCode).ToUpperInvariant(); + address.Province = Clean(address.Province)?.ToUpperInvariant(); + if (address.Name.Length == 0) + { + problems.Add(new($"Addresses.{i}.{nameof(PartyAddress.Name)}", DetailRequired)); + } + } + + for (var i = 0; i < record.Contacts.Count; i++) + { + var contact = record.Contacts[i]; + contact.Name = contact.Name.Trim(); + contact.Email = Clean(contact.Email); + if (contact.Name.Length == 0) + { + problems.Add(new($"Contacts.{i}.{nameof(PartyContact.Name)}", DetailRequired)); + } + + Email(contact.Email, $"Contacts.{i}.{nameof(PartyContact.Email)}", problems); + } + + var directory = pack.GetFeature(); + for (var i = 0; i < record.BankAccounts.Count; i++) + { + var account = record.BankAccounts[i]; + account.Iban = IbanValidator.Normalize(account.Iban); + account.Bic = Clean(account.Bic)?.ToUpperInvariant(); + if (account.Iban.Length == 0) + { + problems.Add(new($"BankAccounts.{i}.{nameof(PartyBankAccount.Iban)}", DetailRequired)); + continue; + } + + if (!IbanValidator.IsValid(account.Iban)) + { + problems.Add(new($"BankAccounts.{i}.{nameof(PartyBankAccount.Iban)}", TableCatalog.IbanInvalid)); + continue; + } + + if (directory?.ReadIban(account.Iban) is { } bank) + { + account.BankCode = bank.BankCode; + account.BranchCode = bank.BranchCode; + account.BankName ??= bank.Name; + account.Bic ??= bank.Bic; + } + } + + problems.AddRange(ItemService.CheckPartyCodes(record.ItemCodes)); + + // One default per list: the first one marked wins. + OneDefault(record.Contacts, c => c.IsDefault, (c, v) => c.IsDefault = v); + OneDefault(record.BankAccounts, c => c.IsDefault, (c, v) => c.IsDefault = v); + foreach (var kind in record.Addresses.Select(a => a.Kind).Distinct().ToList()) + { + OneDefault([.. record.Addresses.Where(a => a.Kind == kind)], a => a.IsDefault, (a, v) => a.IsDefault = v); + } + } + + private static void OneDefault(List rows, Func get, Action set) + { + var found = false; + foreach (var row in rows) + { + if (get(row)) + { + if (found) + { + set(row, false); + } + + found = true; + } + } + } + + private static void Email(string? value, string field, List problems) + { + if (value is not null && !EmailValidator.IsValid(value)) + { + problems.Add(new(field, TableCatalog.EmailInvalid)); + } + } + + private static void Percent(decimal? value, string field, List problems) + { + if (value is < 0 or > 100) + { + problems.Add(new(field, TableCatalog.PercentRange)); + } + } + + private static string? Clean(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + + private static Party Clone(Party party) + { + var copy = new Party(); + foreach (var property in typeof(Party).GetProperties().Where(p => p.CanRead && p.CanWrite)) + { + property.SetValue(copy, property.GetValue(party)); + } + + return copy; + } +} diff --git a/src/Khaemhat.Application/Seeding/BaseTablesSeeder.cs b/src/Khaemhat.Application/Seeding/BaseTablesSeeder.cs new file mode 100644 index 0000000..4564270 --- /dev/null +++ b/src/Khaemhat.Application/Seeding/BaseTablesSeeder.cs @@ -0,0 +1,265 @@ +using Khaemhat.Application.Modules; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Tables; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; +using Khaemhat.Infrastructure.Files; + +namespace Khaemhat.Application.Seeding; + +/// +/// The base tables of SPEC §14 available from M4: countries, currencies, units, VAT codes (from the fiscal pack), +/// payment methods and terms and document types (from the pack's ), transport tables, +/// warehouse reasons, the main warehouse, categories, the base price list, the numerators and the fiscal year of the +/// current year, and the provinces and municipalities of the pack's (ADR 0028). Banks +/// come from a dataset loaded separately (ADR 0026). +/// +/// Creates the current fiscal year. +public sealed class BaseTablesSeeder(FiscalYearService years) : ISeeder +{ + /// The currencies of the ECB reference rates, plus the euro: code, name, symbol, decimals. + public static readonly IReadOnlyList<(string Code, string Name, string Symbol, int Decimals)> Currencies = + [ + ("EUR", "Euro", "€", 2), ("USD", "Dollaro statunitense", "$", 2), ("GBP", "Sterlina britannica", "£", 2), ("CHF", "Franco svizzero", "CHF", 2), + ("JPY", "Yen giapponese", "¥", 0), ("CZK", "Corona ceca", "Kč", 2), ("DKK", "Corona danese", "kr", 2), ("HUF", "Fiorino ungherese", "Ft", 2), + ("PLN", "Zloty polacco", "zł", 2), ("RON", "Leu rumeno", "lei", 2), ("SEK", "Corona svedese", "kr", 2), ("ISK", "Corona islandese", "kr", 0), + ("NOK", "Corona norvegese", "kr", 2), ("TRY", "Lira turca", "₺", 2), ("AUD", "Dollaro australiano", "A$", 2), ("BRL", "Real brasiliano", "R$", 2), + ("CAD", "Dollaro canadese", "C$", 2), ("CNY", "Renminbi cinese", "¥", 2), ("HKD", "Dollaro di Hong Kong", "HK$", 2), ("IDR", "Rupia indonesiana", "Rp", 2), + ("ILS", "Nuovo siclo israeliano", "₪", 2), ("INR", "Rupia indiana", "₹", 2), ("KRW", "Won sudcoreano", "₩", 0), ("MXN", "Peso messicano", "Mex$", 2), + ("MYR", "Ringgit malese", "RM", 2), ("NZD", "Dollaro neozelandese", "NZ$", 2), ("PHP", "Peso filippino", "₱", 2), ("SGD", "Dollaro di Singapore", "S$", 2), + ("THB", "Baht thailandese", "฿", 2), ("ZAR", "Rand sudafricano", "R", 2), + ]; + + /// The numerators of the base data: code, description, family, section, format, gaps allowed. + public static readonly IReadOnlyList<(string Code, string Description, NumeratorKind Kind, string? Section, string Format, bool Gaps)> Numerators = + [ + ("PRE", "Preventivi", NumeratorKind.Quotation, null, "PRE-{year}-{number:D4}", true), + ("ORD", "Ordini clienti", NumeratorKind.SalesOrder, null, "OC-{year}-{number:D4}", true), + ("DDT", "Documenti di trasporto", NumeratorKind.DeliveryNote, null, "{number}/{year}", true), + ("FAT", "Fatture e note di credito", NumeratorKind.SalesInvoice, null, "{number}/{year}", false), + ("AUT", "Autofatture e integrazioni", NumeratorKind.SalesInvoice, "AF", "{number}/AF/{year}", false), + ("PRF", "Pro forma", NumeratorKind.Other, null, "PF-{year}-{number:D4}", true), + ("ORF", "Ordini fornitori", NumeratorKind.PurchaseOrder, null, "OF-{year}-{number:D4}", true), + ("PRA", "Protocollo acquisti", NumeratorKind.PurchaseInvoice, null, "{number}", false), + ("MAG", "Movimenti di magazzino", NumeratorKind.Inventory, null, "MM-{year}-{number:D5}", true), + ("PN", "Registrazioni contabili", NumeratorKind.Journal, null, "{number}", false), + ]; + + /// + public string ModuleCode => ModuleCodes.Core; + + /// + public SeedKind Kind => SeedKind.Base; + + /// + public int Order => 0; + + /// + public async Task RunAsync(SeedContext context, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + await context.EnsureAsync("countries", ReadCountries(), cancellationToken).ConfigureAwait(false); + if (context.Pack.GetFeature() is { } places) + { + await context.EnsureAsync("provinces", places.Provinces.Select(p => new Province { Code = p.Code, Description = p.Name, Region = p.Region }), cancellationToken) + .ConfigureAwait(false); + await context.EnsureAsync( + "municipalities", + places.Municipalities.Select(m => new Municipality + { + Code = m.Code, + Description = m.Name, + ProvinceCode = m.ProvinceCode, + Region = m.Region, + IstatCode = m.StatisticalCode, + PostalCodes = m.PostalCodes, + }), + cancellationToken).ConfigureAwait(false); + } + + await context.EnsureAsync("currencies", Currencies.Select(c => new Currency { Code = c.Code, Description = c.Name, Symbol = c.Symbol, Decimals = c.Decimals }), cancellationToken) + .ConfigureAwait(false); + await context.EnsureAsync("units_of_measure", Units(), cancellationToken).ConfigureAwait(false); + await context.EnsureAsync("tax_codes", TaxCodes(context.Pack), cancellationToken).ConfigureAwait(false); + + var reasons = await context.EnsureAsync("inventory_reasons", InventoryReasons(), cancellationToken).ConfigureAwait(false); + await context.EnsureAsync("warehouses", [new Warehouse { Code = "SEDE", Description = "Magazzino sede", IsDefault = true }], cancellationToken).ConfigureAwait(false); + await context.EnsureAsync("shipping_terms", Coded(("FRANCO", "Porto franco"), ("ASSEGNATO", "Porto assegnato"), ("ADDEBITO", "Franco con addebito in fattura")), cancellationToken) + .ConfigureAwait(false); + await context.EnsureAsync("transport_means", Coded(("MITT", "Mittente"), ("DEST", "Destinatario"), ("VETT", "Vettore")), cancellationToken).ConfigureAwait(false); + await context.EnsureAsync( + "goods_appearances", + Coded(("CARTONI", "Cartoni"), ("SCATOLE", "Scatole"), ("BANCALI", "Bancali"), ("COLLI", "Colli"), ("BUSTE", "Buste"), ("SFUSO", "Sfuso"), ("VISTA", "A vista")), + cancellationToken).ConfigureAwait(false); + await context.EnsureAsync("delivery_terms", Incoterms(), cancellationToken).ConfigureAwait(false); + await context.EnsureAsync( + "transport_reasons", + Coded( + ("VEN", "Vendita"), ("CV", "Conto visione"), ("CD", "Conto deposito"), ("CL", "Conto lavorazione"), ("RES", "Reso"), ("RIP", "Riparazione"), + ("OMA", "Omaggio"), ("TRA", "Trasferimento tra depositi")), + cancellationToken).ConfigureAwait(false); + await context.EnsureAsync("item_categories", [new ItemCategory { Code = "GEN", Description = "Generica" }], cancellationToken).ConfigureAwait(false); + await context.EnsureAsync("party_categories", Coded(("GEN", "Generica")), cancellationToken).ConfigureAwait(false); + await context.EnsureAsync("price_lists", [new PriceList { Code = "BASE", Description = "Listino base", IsBase = true }], cancellationToken).ConfigureAwait(false); + + var year = context.Today.Year; + var numerators = new Dictionary(StringComparer.Ordinal); + foreach (var n in Numerators) + { + numerators[n.Code] = await context.EnsureOneAsync( + "document_numerators", + x => x.Code == n.Code && x.Year == year, + new DocumentNumerator { Code = n.Code, Description = n.Description, Kind = n.Kind, Section = n.Section, Year = year, Format = n.Format, GapsAllowed = n.Gaps }, + cancellationToken).ConfigureAwait(false); + } + + if (context.Pack.GetFeature() is { } template) + { + await SeedPaymentsAsync(context, template, cancellationToken).ConfigureAwait(false); + await context.EnsureAsync( + "document_types", + template.DocumentTypes.Select(d => new DocumentType + { + Code = d.Code, + Description = d.Description, + Kind = d.Kind, + NumeratorId = d.NumeratorCode is { } n && numerators.TryGetValue(n, out var numerator) ? numerator.Id : null, + InventoryReasonId = d.InventoryReasonCode is { } r && reasons.TryGetValue(r, out var reason) ? reason.Id : null, + EInvoiceType = d.EInvoiceType, + }), + cancellationToken).ConfigureAwait(false); + } + + var calendar = await context.UnitOfWork.Repository() + .CountAsync(Query.For().Where(y => y.StartDate <= context.Today && y.EndDate >= context.Today), cancellationToken).ConfigureAwait(false); + if (calendar == 0 && await context.UnitOfWork.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) == 0) + { + await years.CreateAsync(context.UnitOfWork, context.Today, "system", cancellationToken).ConfigureAwait(false); + context.Count("fiscal_years"); + } + } + + /// The countries of the embedded list (ISO 3166-1, Italian names, EU members, currency). + /// The rows. + public static IReadOnlyList ReadCountries() + { + using var stream = typeof(BaseTablesSeeder).Assembly.GetManifestResourceStream("Khaemhat.Application.Seeding.Data.countries.csv") + ?? throw new InvalidOperationException("The country list is missing from the assembly."); + using var reader = new StreamReader(stream); + var lines = CsvReader.Parse(reader.ReadToEnd(), ';'); + return + [ + .. lines.Skip(1).Select(l => new Country + { + Code = l[0], + Iso3 = l[1].Length == 0 ? null : l[1], + Description = l[2], + EuMember = l[3] == "1", + CurrencyCode = l[4].Length == 0 ? null : l[4], + + // Greece uses EL in VAT numbers and VIES. + VatPrefix = l[0] == "GR" ? "EL" : null, + }), + ]; + } + + private static async Task SeedPaymentsAsync(SeedContext context, IBaseTablesTemplate template, CancellationToken cancellationToken) + { + var methods = await context.EnsureAsync( + "payment_methods", + template.PaymentMethods.Select(m => new PaymentMethod { Code = m.Code, Description = m.Description, EInvoiceCode = m.EInvoiceCode, NeedsBank = m.NeedsBank }), + cancellationToken).ConfigureAwait(false); + var existing = (await context.UnitOfWork.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items + .Select(t => t.Code) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + var lines = context.UnitOfWork.Repository(); + foreach (var t in template.PaymentTerms.Where(t => !existing.Contains(t.Code))) + { + var terms = await context.EnsureOneAsync( + "payment_terms", + x => x.Code == t.Code, + new PaymentTerm + { + Code = t.Code, + Description = t.Description, + Condition = t.Condition, + PaymentMethodId = methods.TryGetValue(t.PaymentMethodCode, out var method) ? method.Id : null, + }, + cancellationToken).ConfigureAwait(false); + var number = 1; + foreach (var i in t.Installments) + { + await lines.InsertAsync(new PaymentTermLine { PaymentTermId = terms.Id, Number = number++, Days = i.Days, EndOfMonth = i.EndOfMonth, Percent = i.Percent }, cancellationToken) + .ConfigureAwait(false); + } + } + } + + private static IEnumerable TaxCodes(IFiscalPack pack) => + pack.TaxCodes.BaseCodes.Select(c => new TaxCode + { + Code = c.Code, + Description = c.Description, + Rate = c.Rate, + Nature = c.Nature, + Exigibility = c.Exigibility, + NonDeductiblePercent = c.NonDeductiblePercent, + LegalReference = c.LegalReference, + Kind = pack.TaxCodes.KindOf(c.Rate, c.Nature), + }); + + private static IEnumerable Units() => + [ + new() { Code = "NR", Description = "Numero", Decimals = 0 }, + new() { Code = "PZ", Description = "Pezzi", Decimals = 0 }, + new() { Code = "CF", Description = "Confezioni", Decimals = 0 }, + new() { Code = "CT", Description = "Cartoni", Decimals = 0 }, + new() { Code = "PAL", Description = "Pallet", Decimals = 0 }, + new() { Code = "KG", Description = "Chilogrammi", Decimals = 3 }, + new() { Code = "G", Description = "Grammi", Decimals = 0 }, + new() { Code = "T", Description = "Tonnellate", Decimals = 3 }, + new() { Code = "L", Description = "Litri", Decimals = 3 }, + new() { Code = "M", Description = "Metri", Decimals = 3 }, + new() { Code = "M2", Description = "Metri quadrati", Decimals = 3 }, + new() { Code = "M3", Description = "Metri cubi", Decimals = 3 }, + new() { Code = "KM", Description = "Chilometri", Decimals = 2 }, + new() { Code = "KWH", Description = "Kilowattora", Decimals = 3 }, + new() { Code = "ORE", Description = "Ore", Decimals = 2 }, + new() { Code = "GG", Description = "Giorni", Decimals = 2 }, + new() { Code = "MESI", Description = "Mesi", Decimals = 0 }, + new() { Code = "SERV", Description = "Servizio", Decimals = 0 }, + ]; + + private static IEnumerable InventoryReasons() => + [ + new() { Code = "CAR", Description = "Carico da acquisto", Effect = StockEffect.Load }, + new() { Code = "SCA", Description = "Scarico per vendita", Effect = StockEffect.Unload }, + new() { Code = "RESC", Description = "Reso da cliente", Effect = StockEffect.Load }, + new() { Code = "RESF", Description = "Reso a fornitore", Effect = StockEffect.Unload }, + new() { Code = "TRA", Description = "Trasferimento tra depositi", Effect = StockEffect.None, AffectsValue = false, IsTransfer = true }, + new() { Code = "INVP", Description = "Rettifica inventariale in aumento", Effect = StockEffect.Load }, + new() { Code = "INVN", Description = "Rettifica inventariale in diminuzione", Effect = StockEffect.Unload }, + new() { Code = "CVU", Description = "Uscita in conto visione", Effect = StockEffect.Unload, AffectsValue = false }, + new() { Code = "CVR", Description = "Rientro da conto visione", Effect = StockEffect.Load, AffectsValue = false }, + new() { Code = "OMA", Description = "Omaggio", Effect = StockEffect.Unload }, + new() { Code = "AUTO", Description = "Autoconsumo", Effect = StockEffect.Unload }, + new() { Code = "APE", Description = "Esistenza iniziale", Effect = StockEffect.Load }, + ]; + + private static IEnumerable Incoterms() => Coded( + ("EXW", "Franco fabbrica (Ex Works)"), + ("FCA", "Franco vettore (Free Carrier)"), + ("CPT", "Trasporto pagato fino a (Carriage Paid To)"), + ("CIP", "Trasporto e assicurazione pagati fino a (Carriage and Insurance Paid To)"), + ("DAP", "Reso al luogo di destinazione (Delivered at Place)"), + ("DPU", "Reso al luogo di destinazione scaricato (Delivered at Place Unloaded)"), + ("DDP", "Reso sdoganato (Delivered Duty Paid)"), + ("FAS", "Franco lungo bordo (Free Alongside Ship)"), + ("FOB", "Franco a bordo (Free On Board)"), + ("CFR", "Costo e nolo (Cost and Freight)"), + ("CIF", "Costo, assicurazione e nolo (Cost, Insurance and Freight)")); + + private static IEnumerable Coded(params (string Code, string Description)[] rows) + where T : CodedEntity, new() => + rows.Select(r => new T { Code = r.Code, Description = r.Description }); +} diff --git a/src/Khaemhat.Application/Seeding/Data/countries.csv b/src/Khaemhat.Application/Seeding/Data/countries.csv new file mode 100644 index 0000000..69f4342 --- /dev/null +++ b/src/Khaemhat.Application/Seeding/Data/countries.csv @@ -0,0 +1,252 @@ +code;iso3;name;eu;currency +AD;AND;Andorra;0;EUR +AE;ARE;Emirati Arabi Uniti;0;AED +AF;AFG;Afghanistan;0;AFN +AG;ATG;Antigua e Barbuda;0;XCD +AI;AIA;Anguilla;0;XCD +AL;ALB;Albania;0;ALL +AM;ARM;Armenia;0;AMD +AO;AGO;Angola;0;AOA +AQ;ATA;Antartide;0; +AR;ARG;Argentina;0;ARS +AS;ASM;Samoa americane;0;USD +AT;AUT;Austria;1;EUR +AU;AUS;Australia;0;AUD +AW;ABW;Aruba;0;AWG +AX;ALA;Isole Åland;0;EUR +AZ;AZE;Azerbaigian;0;AZN +BA;BIH;Bosnia ed Erzegovina;0;BAM +BB;BRB;Barbados;0;BBD +BD;BGD;Bangladesh;0;BDT +BE;BEL;Belgio;1;EUR +BF;BFA;Burkina Faso;0;XOF +BG;BGR;Bulgaria;1;EUR +BH;BHR;Bahrein;0;BHD +BI;BDI;Burundi;0;BIF +BJ;BEN;Benin;0;XOF +BL;BLM;Saint-Barthélemy;0;EUR +BM;BMU;Bermuda;0;BMD +BN;BRN;Brunei;0;BND +BO;BOL;Bolivia;0;BOB +BQ;BES;Caraibi olandesi;0;USD +BR;BRA;Brasile;0;BRL +BS;BHS;Bahamas;0;BSD +BT;BTN;Bhutan;0;BTN +BV;BVT;Isola Bouvet;0;NOK +BW;BWA;Botswana;0;BWP +BY;BLR;Bielorussia;0;BYN +BZ;BLZ;Belize;0;BZD +CA;CAN;Canada;0;CAD +CC;CCK;Isole Cocos (Keeling);0;AUD +CD;COD;Repubblica Democratica del Congo;0;CDF +CF;CAF;Repubblica Centrafricana;0;XAF +CG;COG;Repubblica del Congo;0;XAF +CH;CHE;Svizzera;0;CHF +CI;CIV;Costa d'Avorio;0;XOF +CK;COK;Isole Cook;0;NZD +CL;CHL;Cile;0;CLP +CM;CMR;Camerun;0;XAF +CN;CHN;Cina;0;CNY +CO;COL;Colombia;0;COP +CR;CRI;Costa Rica;0;CRC +CU;CUB;Cuba;0;CUP +CV;CPV;Capo Verde;0;CVE +CW;CUW;Curaçao;0;XCG +CX;CXR;Isola di Natale;0;AUD +CY;CYP;Cipro;1;EUR +CZ;CZE;Cechia;1;CZK +DE;DEU;Germania;1;EUR +DJ;DJI;Gibuti;0;DJF +DK;DNK;Danimarca;1;DKK +DM;DMA;Dominica;0;XCD +DO;DOM;Repubblica Dominicana;0;DOP +DZ;DZA;Algeria;0;DZD +EC;ECU;Ecuador;0;USD +EE;EST;Estonia;1;EUR +EG;EGY;Egitto;0;EGP +EH;ESH;Sahara Occidentale;0;MAD +ER;ERI;Eritrea;0;ERN +ES;ESP;Spagna;1;EUR +ET;ETH;Etiopia;0;ETB +FI;FIN;Finlandia;1;EUR +FJ;FJI;Figi;0;FJD +FK;FLK;Isole Falkland;0;FKP +FM;FSM;Micronesia;0;USD +FO;FRO;Isole Fær Øer;0;DKK +FR;FRA;Francia;1;EUR +GA;GAB;Gabon;0;XAF +GB;GBR;Regno Unito;0;GBP +GD;GRD;Grenada;0;XCD +GE;GEO;Georgia;0;GEL +GF;GUF;Guyana francese;0;EUR +GG;GGY;Guernsey;0;GBP +GH;GHA;Ghana;0;GHS +GI;GIB;Gibilterra;0;GIP +GL;GRL;Groenlandia;0;DKK +GM;GMB;Gambia;0;GMD +GN;GIN;Guinea;0;GNF +GP;GLP;Guadalupa;0;EUR +GQ;GNQ;Guinea Equatoriale;0;XAF +GR;GRC;Grecia;1;EUR +GS;SGS;Georgia del Sud e isole Sandwich australi;0;GBP +GT;GTM;Guatemala;0;GTQ +GU;GUM;Guam;0;USD +GW;GNB;Guinea-Bissau;0;XOF +GY;GUY;Guyana;0;GYD +HK;HKG;Hong Kong;0;HKD +HM;HMD;Isole Heard e McDonald;0;AUD +HN;HND;Honduras;0;HNL +HR;HRV;Croazia;1;EUR +HT;HTI;Haiti;0;HTG +HU;HUN;Ungheria;1;HUF +ID;IDN;Indonesia;0;IDR +IE;IRL;Irlanda;1;EUR +IL;ISR;Israele;0;ILS +IM;IMN;Isola di Man;0;GBP +IN;IND;India;0;INR +IO;IOT;Territorio britannico dell'Oceano Indiano;0;USD +IQ;IRQ;Iraq;0;IQD +IR;IRN;Iran;0;IRR +IS;ISL;Islanda;0;ISK +IT;ITA;Italia;1;EUR +JE;JEY;Jersey;0;GBP +JM;JAM;Giamaica;0;JMD +JO;JOR;Giordania;0;JOD +JP;JPN;Giappone;0;JPY +KE;KEN;Kenya;0;KES +KG;KGZ;Kirghizistan;0;KGS +KH;KHM;Cambogia;0;KHR +KI;KIR;Kiribati;0;AUD +KM;COM;Comore;0;KMF +KN;KNA;Saint Kitts e Nevis;0;XCD +KP;PRK;Corea del Nord;0;KPW +KR;KOR;Corea del Sud;0;KRW +KW;KWT;Kuwait;0;KWD +KY;CYM;Isole Cayman;0;KYD +KZ;KAZ;Kazakistan;0;KZT +LA;LAO;Laos;0;LAK +LB;LBN;Libano;0;LBP +LC;LCA;Santa Lucia;0;XCD +LI;LIE;Liechtenstein;0;CHF +LK;LKA;Sri Lanka;0;LKR +LR;LBR;Liberia;0;LRD +LS;LSO;Lesotho;0;LSL +LT;LTU;Lituania;1;EUR +LU;LUX;Lussemburgo;1;EUR +LV;LVA;Lettonia;1;EUR +LY;LBY;Libia;0;LYD +MA;MAR;Marocco;0;MAD +MC;MCO;Monaco;0;EUR +MD;MDA;Moldavia;0;MDL +ME;MNE;Montenegro;0;EUR +MF;MAF;Saint-Martin;0;EUR +MG;MDG;Madagascar;0;MGA +MH;MHL;Isole Marshall;0;USD +MK;MKD;Macedonia del Nord;0;MKD +ML;MLI;Mali;0;XOF +MM;MMR;Myanmar;0;MMK +MN;MNG;Mongolia;0;MNT +MO;MAC;Macao;0;MOP +MP;MNP;Isole Marianne Settentrionali;0;USD +MQ;MTQ;Martinica;0;EUR +MR;MRT;Mauritania;0;MRU +MS;MSR;Montserrat;0;XCD +MT;MLT;Malta;1;EUR +MU;MUS;Mauritius;0;MUR +MV;MDV;Maldive;0;MVR +MW;MWI;Malawi;0;MWK +MX;MEX;Messico;0;MXN +MY;MYS;Malaysia;0;MYR +MZ;MOZ;Mozambico;0;MZN +NA;NAM;Namibia;0;NAD +NC;NCL;Nuova Caledonia;0;XPF +NE;NER;Niger;0;XOF +NF;NFK;Isola Norfolk;0;AUD +NG;NGA;Nigeria;0;NGN +NI;NIC;Nicaragua;0;NIO +NL;NLD;Paesi Bassi;1;EUR +NO;NOR;Norvegia;0;NOK +NP;NPL;Nepal;0;NPR +NR;NRU;Nauru;0;AUD +NU;NIU;Niue;0;NZD +NZ;NZL;Nuova Zelanda;0;NZD +OM;OMN;Oman;0;OMR +PA;PAN;Panama;0;PAB +PE;PER;Perù;0;PEN +PF;PYF;Polinesia francese;0;XPF +PG;PNG;Papua Nuova Guinea;0;PGK +PH;PHL;Filippine;0;PHP +PK;PAK;Pakistan;0;PKR +PL;POL;Polonia;1;PLN +PM;SPM;Saint-Pierre e Miquelon;0;EUR +PN;PCN;Isole Pitcairn;0;NZD +PR;PRI;Porto Rico;0;USD +PS;PSE;Palestina;0;ILS +PT;PRT;Portogallo;1;EUR +PW;PLW;Palau;0;USD +PY;PRY;Paraguay;0;PYG +QA;QAT;Qatar;0;QAR +RE;REU;Riunione;0;EUR +RO;ROU;Romania;1;RON +RS;SRB;Serbia;0;RSD +RU;RUS;Russia;0;RUB +RW;RWA;Ruanda;0;RWF +SA;SAU;Arabia Saudita;0;SAR +SB;SLB;Isole Salomone;0;SBD +SC;SYC;Seychelles;0;SCR +SD;SDN;Sudan;0;SDG +SE;SWE;Svezia;1;SEK +SG;SGP;Singapore;0;SGD +SH;SHN;Sant'Elena, Ascensione e Tristan da Cunha;0;SHP +SI;SVN;Slovenia;1;EUR +SJ;SJM;Svalbard e Jan Mayen;0;NOK +SK;SVK;Slovacchia;1;EUR +SL;SLE;Sierra Leone;0;SLE +SM;SMR;San Marino;0;EUR +SN;SEN;Senegal;0;XOF +SO;SOM;Somalia;0;SOS +SR;SUR;Suriname;0;SRD +SS;SSD;Sudan del Sud;0;SSP +ST;STP;São Tomé e Príncipe;0;STN +SV;SLV;El Salvador;0;USD +SX;SXM;Sint Maarten;0;XCG +SY;SYR;Siria;0;SYP +SZ;SWZ;Eswatini;0;SZL +TC;TCA;Isole Turks e Caicos;0;USD +TD;TCD;Ciad;0;XAF +TF;ATF;Terre australi e antartiche francesi;0;EUR +TG;TGO;Togo;0;XOF +TH;THA;Thailandia;0;THB +TJ;TJK;Tagikistan;0;TJS +TK;TKL;Tokelau;0;NZD +TL;TLS;Timor Est;0;USD +TM;TKM;Turkmenistan;0;TMT +TN;TUN;Tunisia;0;TND +TO;TON;Tonga;0;TOP +TR;TUR;Turchia;0;TRY +TT;TTO;Trinidad e Tobago;0;TTD +TV;TUV;Tuvalu;0;AUD +TW;TWN;Taiwan;0;TWD +TZ;TZA;Tanzania;0;TZS +UA;UKR;Ucraina;0;UAH +UG;UGA;Uganda;0;UGX +UM;UMI;Isole minori esterne degli Stati Uniti;0;USD +US;USA;Stati Uniti;0;USD +UY;URY;Uruguay;0;UYU +UZ;UZB;Uzbekistan;0;UZS +VA;VAT;Città del Vaticano;0;EUR +VC;VCT;Saint Vincent e Grenadine;0;XCD +VE;VEN;Venezuela;0;VES +VG;VGB;Isole Vergini britanniche;0;USD +VI;VIR;Isole Vergini americane;0;USD +VN;VNM;Vietnam;0;VND +VU;VUT;Vanuatu;0;VUV +WF;WLF;Wallis e Futuna;0;XPF +WS;WSM;Samoa;0;WST +XI;;Irlanda del Nord (IVA);1;GBP +XK;XKX;Kosovo;0;EUR +YE;YEM;Yemen;0;YER +YT;MYT;Mayotte;0;EUR +ZA;ZAF;Sudafrica;0;ZAR +ZM;ZMB;Zambia;0;ZMW +ZW;ZWE;Zimbabwe;0;ZWG diff --git a/src/Khaemhat.Application/Seeding/DemoItemsSeeder.cs b/src/Khaemhat.Application/Seeding/DemoItemsSeeder.cs new file mode 100644 index 0000000..868d86b --- /dev/null +++ b/src/Khaemhat.Application/Seeding/DemoItemsSeeder.cs @@ -0,0 +1,382 @@ +using System.Globalization; +using Khaemhat.Application.Items; +using Khaemhat.Application.Modules; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Items; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Tables; +using Khaemhat.Core.Validation; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Seeding; + +/// +/// The items of the demo company (SPEC §14, issue #42): 120 items of a plumbing and heating wholesaler in ten categories +/// (goods, services, expenses and description lines), two price lists derived from the base one (public with markup and +/// rounding, resellers with a discount), prices with an older row for the history, the net prices and the item codes of +/// a customer, usual suppliers, alternative units and codes, substitutes, demo costs. Names and brands are fictitious; +/// the bar codes use the prefix 200-299, reserved for internal use, with a valid check digit. Runs only on a company +/// without items; seed --demo --scale N repeats the catalogue N times. The rows are marked as demo. +/// +/// The automatic code rules. +public sealed class DemoItemsSeeder(CodeRuleService codes) : ISeeder +{ + /// The items of one scale. + public const int ItemsPerScale = 120; + + private static readonly string[] Sizes = ["1/2\"", "3/4\"", "1\"", "1 1/4\"", "1 1/2\"", "2\""]; + + /// + public string ModuleCode => ModuleCodes.Core; + + /// + public SeedKind Kind => SeedKind.Demo; + + /// + public int Order => 20; + + /// The catalogue of one scale, in order. + /// The items to create. + public static IReadOnlyList Catalogue() + { + var items = new List(); + + // Valves: ball valves with lever and butterfly handle, check valves, gate valves. + for (var i = 0; i < Sizes.Length; i++) + { + items.Add(Goods("VALV", "Valvola a sfera " + Sizes[i] + " ottone cromato leva", "PZ", 12.80m + (i * 9.6m), "Idrodemo", "84818081", 0.25m + (i * 0.2m))); + items.Add(Goods("VALV", "Valvola a sfera " + Sizes[i] + " ottone cromato farfalla", "PZ", 11.90m + (i * 9.1m), "Idrodemo", "84818081", 0.24m + (i * 0.2m))); + items.Add(Goods("VALV", "Valvola di ritegno " + Sizes[i] + " a molla", "PZ", 9.40m + (i * 6.2m), "Idrodemo", "84813091", 0.2m + (i * 0.15m))); + } + + for (var i = 0; i < 4; i++) + { + items.Add(Goods("VALV", "Saracinesca " + Sizes[i] + " ottone", "PZ", 14.50m + (i * 8.3m), "Idrodemo", "84818081", 0.4m + (i * 0.25m))); + } + + items.Add(Goods("VALV", "Valvola miscelatrice termostatica 3/4\"", "PZ", 54m, "Idrodemo", "84818019", 0.7m)); + items.Add(Goods("VALV", "Riduttore di pressione 1/2\" con manometro", "PZ", 39.50m, "Idrodemo", "84811019", 0.6m)); + items.Add(Goods("VALV", "Filtro autopulente 3/4\"", "PZ", 68m, "Idrodemo", "84212100", 0.9m)); + + // Fittings: five shapes in four sizes. + foreach (var shape in new[] { "Manicotto", "Gomito 90 gradi", "Raccordo a T", "Nipplo", "Riduzione" }) + { + for (var i = 0; i < 4; i++) + { + items.Add(Goods("RACC", shape + " " + Sizes[i] + " ottone M/F", "PZ", 1.60m + (i * 1.35m) + (shape.Length / 10m), "Raccordemo", "74122000", 0.05m + (i * 0.04m))); + } + } + + // Pipes: copper bars, multilayer and polyethylene rolls. + foreach (var (diameter, price) in new[] { (12, 2.10m), (14, 2.45m), (15, 2.78m), (16, 3.05m), (18, 3.60m), (22, 4.85m) }) + { + items.Add(Goods("TUBI", "Tubo rame " + diameter.ToString(CultureInfo.InvariantCulture) + "x1 barra 5 m", "M", price, "Ramedemo", "74111010", 0.4m)); + } + + foreach (var (diameter, price) in new[] { (16, 1.15m), (20, 1.65m), (26, 2.70m) }) + { + items.Add(Goods("TUBI", "Tubo multistrato " + diameter.ToString(CultureInfo.InvariantCulture) + "x2 rotolo 100 m", "M", price, "Plastidemo", "39172110", 0.15m)); + items.Add(Goods("TUBI", "Tubo polietilene PE100 " + (diameter + 9).ToString(CultureInfo.InvariantCulture) + " mm rotolo 50 m", "M", price * 0.8m, "Plastidemo", "39172110", 0.2m)); + } + + // Heating: boilers, radiators, thermostats, manifolds, expansion vessels. + foreach (var (kw, price) in new[] { (24, 1180m), (28, 1290m), (35, 1520m) }) + { + items.Add(Goods("CALD", "Caldaia a condensazione " + kw.ToString(CultureInfo.InvariantCulture) + " kW", "PZ", price, "Termodemo", "84031090", 32m + kw)); + } + + foreach (var (height, price) in new[] { (500, 9.20m), (600, 10.40m), (700, 11.60m), (800, 12.90m) }) + { + items.Add(Goods("CALD", "Elemento radiatore alluminio interasse " + height.ToString(CultureInfo.InvariantCulture), "PZ", price, "Termodemo", "76169990", 1.2m)); + } + + items.Add(Goods("CALD", "Termostato ambiente digitale", "PZ", 48m, "Termodemo", "90321020", 0.3m)); + items.Add(Goods("CALD", "Cronotermostato settimanale wifi", "PZ", 129m, "Termodemo", "90321020", 0.35m)); + for (var ways = 2; ways <= 5; ways++) + { + items.Add(Goods("CALD", "Collettore " + ways.ToString(CultureInfo.InvariantCulture) + " vie con valvole", "PZ", 58m + (ways * 23m), "Idrodemo", "84818081", 0.6m * ways)); + } + + foreach (var (liters, price) in new[] { (8, 32m), (18, 46m), (24, 58m) }) + { + items.Add(Goods("CALD", "Vaso di espansione " + liters.ToString(CultureInfo.InvariantCulture) + " l", "PZ", price, "Termodemo", "73110099", liters / 4m)); + } + + // Taps and sanitary. + foreach (var (name, price) in new[] { ("Miscelatore lavabo monocomando", 64m), ("Miscelatore bidet monocomando", 61m), ("Miscelatore doccia esterno", 72m), ("Miscelatore cucina canna alta", 89m), ("Sifone lavabo 1 1/4\"", 7.80m), ("Sifone lavello doppio", 14.50m) }) + { + items.Add(Goods("SAN", name, "PZ", price, "Rubidemo", "84818011", 0.9m)); + } + + foreach (var length in new[] { 30, 40, 50 }) + { + items.Add(Goods("SAN", "Flessibile inox 1/2\" F/F " + length.ToString(CultureInfo.InvariantCulture) + " cm", "PZ", 3.10m + (length / 20m), "Rubidemo", "83071000", 0.12m)); + } + + // Consumables. + foreach (var (name, unit, price) in new[] + { + ("Nastro PTFE 12 mm x 12 m", "PZ", 0.95m), ("Canapa pettinata 100 g", "PZ", 2.40m), ("Pasta sigillante 500 g", "PZ", 6.90m), + ("Silicone sanitario trasparente 280 ml", "PZ", 5.20m), ("Kit guarnizioni assortite", "CF", 9.80m), ("Collare fissatubo 1/2\" con tassello", "CF", 12.40m), + ("Tassello nylon 8 mm", "CF", 4.60m), ("Fascetta stringitubo 20-32", "CF", 7.30m), ("Saldatura stagno-rame 250 g", "PZ", 18.50m), ("Disossidante 125 ml", "PZ", 4.10m), + }) + { + items.Add(Goods("CONS", name, unit, price, null, null, 0.2m)); + } + + // Pumps. + foreach (var (name, price) in new[] { ("Circolatore elettronico 25-40", 168m), ("Circolatore elettronico 25-60", 196m), ("Circolatore elettronico 25-80", 254m), ("Pompa sommersa 0,75 kW", 312m), ("Pompa sommersa 1,1 kW", 389m), ("Pompa sommersa 1,5 kW", 465m), ("Autoclave 24 l 0,8 kW", 278m), ("Autoclave 60 l 1,1 kW", 412m) }) + { + items.Add(Goods("POMP", name, "PZ", price, "Pompdemo", "84137035", 4.5m)); + } + + // Tools. + foreach (var (name, price) in new[] { ("Chiave stringitubi 14\"", 24.50m), ("Tagliatubi rame 3-35 mm", 19.80m), ("Piegatubi a molla set", 15.40m), ("Svasatubi", 28.90m), ("Cannello a gas", 32m), ("Pinza regolabile 250 mm", 16.70m), ("Seghetto per metalli", 12.30m), ("Livella 60 cm", 14.90m) }) + { + items.Add(Goods("UTEN", name, "PZ", price, "Utendemo", "82055980", 0.6m)); + } + + // Services, expenses and description lines: never in stock. + items.Add(Other(ItemKind.Service, "SERV", "Manodopera idraulico", "ORE", 38m)); + items.Add(Other(ItemKind.Service, "SERV", "Manodopera apprendista", "ORE", 26m)); + items.Add(Other(ItemKind.Service, "SERV", "Uscita e diritto di chiamata", "SERV", 35m)); + items.Add(Other(ItemKind.Service, "SERV", "Sopralluogo tecnico", "SERV", 60m)); + items.Add(Other(ItemKind.Service, "SERV", "Manutenzione annuale caldaia", "SERV", 95m)); + items.Add(Other(ItemKind.Service, "SERV", "Analisi fumi e libretto impianto", "SERV", 45m)); + items.Add(Other(ItemKind.Service, "SERV", "Dichiarazione di conformità impianto", "SERV", 120m)); + items.Add(Other(ItemKind.Expense, "SPESE", "Spese di trasporto", "SERV", 15m)); + items.Add(Other(ItemKind.Expense, "SPESE", "Spese di imballo", "SERV", 5m)); + items.Add(Other(ItemKind.Expense, "SPESE", "Smaltimento materiale rimosso", "SERV", 25m)); + items.Add(Other(ItemKind.Text, "SERV", "Riga descrittiva", "NR", null)); + items.Add(Other(ItemKind.Text, "SERV", "Materiale fornito dal cliente", "NR", null)); + + return items; + } + + /// + public async Task RunAsync(SeedContext context, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + var uow = context.UnitOfWork; + if (await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) > 0) + { + return; + } + + var categories = await context.EnsureAsync( + "item_categories", + [ + new ItemCategory { Code = "VALV", Description = "Valvolame", IsDemo = true }, + new ItemCategory { Code = "RACC", Description = "Raccorderia", IsDemo = true }, + new ItemCategory { Code = "TUBI", Description = "Tubi", IsDemo = true }, + new ItemCategory { Code = "CALD", Description = "Caldaie e riscaldamento", IsDemo = true }, + new ItemCategory { Code = "SAN", Description = "Rubinetteria e sanitari", IsDemo = true }, + new ItemCategory { Code = "CONS", Description = "Materiale di consumo", IsDemo = true }, + new ItemCategory { Code = "POMP", Description = "Pompe e circolatori", IsDemo = true }, + new ItemCategory { Code = "UTEN", Description = "Utensili", IsDemo = true }, + new ItemCategory { Code = "SERV", Description = "Servizi e manodopera", IsDemo = true }, + new ItemCategory { Code = "SPESE", Description = "Spese accessorie", IsDemo = true }, + ], + cancellationToken).ConfigureAwait(false); + var lists = uow.Repository(); + var allLists = (await lists.ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items; + var baseList = PriceBook.BaseOf(allLists); + if (baseList is null) + { + baseList = new PriceList { Code = "BASE", Description = "Listino base", IsBase = true, IsDemo = true }; + baseList.Id = await lists.InsertAsync(baseList, cancellationToken).ConfigureAwait(false); + context.Count("price_lists"); + } + + await context.EnsureAsync( + "price_lists", + [ + new PriceList { Code = "PUBB", Description = "Pubblico", BasePriceListId = baseList.Id, MarkupPercent = 45m, RoundingStep = 0.10m, IsDemo = true }, + new PriceList { Code = "RIV", Description = "Rivenditori", BasePriceListId = baseList.Id, MarkupPercent = -10m, RoundingStep = 0.01m, IsDemo = true }, + ], + cancellationToken).ConfigureAwait(false); + + var units = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items + .ToDictionary(u => u.Code, u => u.Id, StringComparer.OrdinalIgnoreCase); + var tax = (await uow.Repository().FindAsync(Query.For().Where(t => t.Code == "22"), cancellationToken).ConfigureAwait(false))?.Id; + var warehouse = (await uow.Repository().FindAsync(Query.For().Where(w => w.IsDefault), cancellationToken).ConfigureAwait(false))?.Id; + var parties = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items + .GroupBy(p => p.Name, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().Id, StringComparer.Ordinal); + long? PartyOf(string name) => parties.TryGetValue(name, out var id) ? id : null; + var suppliers = new Dictionary(StringComparer.Ordinal) + { + ["VALV"] = PartyOf("Metalli Nord S.p.A."), ["RACC"] = PartyOf("Metalli Nord S.p.A."), ["TUBI"] = PartyOf("Metalli Nord S.p.A."), + ["SAN"] = PartyOf("Metalli Nord S.p.A."), ["CONS"] = PartyOf("Plastica Sud S.r.l."), ["CALD"] = PartyOf("Elektro Werke Süd GmbH"), + ["POMP"] = PartyOf("Elektro Werke Süd GmbH"), ["UTEN"] = PartyOf("Plastica Sud S.r.l."), + }; + var customer = PartyOf("Rossi Impianti S.r.l."); + + var rule = await codes.RuleAsync(context.CompanyCode, ItemService.CodeRule, cancellationToken).ConfigureAwait(false); + var items = uow.Repository(); + var thisYear = new DateOnly(context.Today.Year, 1, 1); + var lastYear = thisYear.AddYears(-1); + var catalogue = Catalogue(); + var created = new List<(DemoItem Seed, Item Item)>(); + var ean = 0; + for (var round = 1; round <= Math.Max(1, context.Scale); round++) + { + foreach (var seed in catalogue) + { + var category = categories[seed.Category]; + var cost = seed.Price is { } p && seed.Kind == ItemKind.Goods ? Math.Round(p * 0.58m, 2) : (decimal?)null; + var item = new Item + { + Kind = seed.Kind, + Description = round == 1 ? seed.Description : seed.Description + " (serie " + round.ToString(CultureInfo.InvariantCulture) + ")", + CategoryId = category.Id, + UnitOfMeasureId = units.TryGetValue(seed.Unit, out var unit) ? unit : null, + SalesTaxCodeId = tax, + PurchaseTaxCodeId = tax, + Barcode = seed.Kind == ItemKind.Goods ? Ean(++ean) : null, + CustomsCode = seed.CustomsCode, + Brand = seed.Brand, + Manufacturer = seed.Brand is null ? null : seed.Brand + " Industrie", + NetWeight = seed.Weight, + GrossWeight = seed.Weight is { } w ? Math.Round(w * 1.08m, 3) : null, + Stocked = seed.Kind == ItemKind.Goods, + WarehouseId = seed.Kind == ItemKind.Goods ? warehouse : null, + MinimumStock = seed.Kind == ItemKind.Goods && seed.Unit == "PZ" ? 5m : null, + ReorderPoint = seed.Kind == ItemKind.Goods && seed.Unit == "PZ" ? 10m : null, + ReorderLot = seed.Kind == ItemKind.Goods && seed.Unit == "PZ" ? 20m : null, + Price = seed.Kind is ItemKind.Service or ItemKind.Expense ? seed.Price : null, + StandardCost = cost, + AverageCost = cost, + LastCost = cost is { } c ? Math.Round(c * 1.02m, 2) : null, + IsDemo = true, + }; + item.Code = await CodeRuleService.AssignAsync( + uow, rule, context.Today, category.Code, + async (code, ct) => await items.CountAsync(Query.For().Where(i => i.Code == code), ct).ConfigureAwait(false) > 0, + cancellationToken).ConfigureAwait(false); + item.Id = await items.InsertAsync(item, cancellationToken).ConfigureAwait(false); + context.Count("items"); + created.Add((seed, item)); + + if (seed.Kind == ItemKind.Goods && seed.Price is { } price) + { + // The price of this year, and the one of last year for the history. + await AddAsync(uow, context, "item_prices", new ItemPrice { ItemId = item.Id, PriceListId = baseList.Id, Price = price, ValidFrom = thisYear }, cancellationToken).ConfigureAwait(false); + await AddAsync(uow, context, "item_prices", + new ItemPrice { ItemId = item.Id, PriceListId = baseList.Id, Price = PriceRounding.Round(price * 0.96m, 0.10m), ValidFrom = lastYear }, cancellationToken).ConfigureAwait(false); + if (suppliers.GetValueOrDefault(seed.Category) is { } supplier) + { + await AddAsync(uow, context, "item_suppliers", new ItemSupplier + { + ItemId = item.Id, PartyId = supplier, SupplierCode = "F-" + item.Code, Price = cost, LeadTimeDays = 7, MinimumQuantity = seed.Unit == "M" ? 50m : 1m, IsDefault = true, + }, cancellationToken).ConfigureAwait(false); + } + } + } + } + + await DetailsAsync(uow, context, created, units, customer, baseList, thisYear, cancellationToken).ConfigureAwait(false); + } + + private static async Task DetailsAsync(IUnitOfWork uow, SeedContext context, List<(DemoItem Seed, Item Item)> created, Dictionary units, + long? customer, PriceList baseList, DateOnly thisYear, CancellationToken cancellationToken) + { + Item? Find(string description) => created.FirstOrDefault(c => c.Item.Description == description).Item; + + // Copper bars are sold also by the bar of 5 m; small valves and fittings by the box of 10. + foreach (var (seed, item) in created.Where(c => c.Item.Description.StartsWith("Tubo rame", StringComparison.Ordinal))) + { + if (units.TryGetValue("PZ", out var bar)) + { + await AddAsync(uow, context, "item_uoms", new ItemUnit { ItemId = item.Id, UnitOfMeasureId = bar, Factor = 5m }, cancellationToken).ConfigureAwait(false); + } + } + + foreach (var (seed, item) in created.Where(c => c.Seed.Category is "VALV" or "RACC" && c.Seed.Unit == "PZ").Take(30)) + { + if (units.TryGetValue("CT", out var box)) + { + await AddAsync(uow, context, "item_uoms", new ItemUnit { ItemId = item.Id, UnitOfMeasureId = box, Factor = 10m, Barcode = Ean(500_000 + (int)item.Id) }, cancellationToken).ConfigureAwait(false); + } + } + + // The codes of the old system, found by the search. + foreach (var (seed, item) in created.Where(c => c.Seed.Category == "VALV").Take(6)) + { + await AddAsync(uow, context, "item_barcodes", new ItemBarcode { ItemId = item.Id, Code = "OLD-" + item.Id.ToString("00000", CultureInfo.InvariantCulture), Description = "Codice del gestionale precedente" }, cancellationToken).ConfigureAwait(false); + } + + // Substitutes: the butterfly valve for the lever one of the same size, the bigger boiler for the smaller one. + foreach (var size in Sizes) + { + if (Find("Valvola a sfera " + size + " ottone cromato leva") is { } lever && Find("Valvola a sfera " + size + " ottone cromato farfalla") is { } butterfly) + { + await AddAsync(uow, context, "item_substitutes", new ItemSubstitute { ItemId = lever.Id, SubstituteId = butterfly.Id, Notes = "Stessa misura, maniglia a farfalla" }, cancellationToken).ConfigureAwait(false); + } + } + + if (Find("Caldaia a condensazione 24 kW") is { } small && Find("Caldaia a condensazione 28 kW") is { } big) + { + await AddAsync(uow, context, "item_substitutes", new ItemSubstitute { ItemId = small.Id, SubstituteId = big.Id, Notes = "Potenza superiore, stessi attacchi" }, cancellationToken).ConfigureAwait(false); + } + + if (customer is not { } rossi) + { + return; + } + + // The usual customer has net prices on the valves and calls some items with its own codes. + var valves = created.Where(c => c.Seed.Category == "VALV" && c.Seed.Price is not null).Take(8).ToList(); + for (var i = 0; i < valves.Count; i++) + { + var (seed, item) = valves[i]; + await AddAsync(uow, context, "item_prices", new ItemPrice { ItemId = item.Id, PartyId = rossi, Price = PriceRounding.Round(seed.Price!.Value * 0.95m, 0.05m), ValidFrom = thisYear }, cancellationToken).ConfigureAwait(false); + if (i < 5) + { + await AddAsync(uow, context, "party_item_codes", + new PartyItemCode { PartyId = rossi, ItemId = item.Id, Code = "RI-" + (100 + i).ToString(CultureInfo.InvariantCulture), Description = "Valvola " + (i + 1).ToString(CultureInfo.InvariantCulture) }, cancellationToken).ConfigureAwait(false); + } + } + + // A price of the public list written by hand, over the derived one. + if (Find("Caldaia a condensazione 24 kW") is { } boiler + && await uow.Repository().FindAsync(Query.For().Where(l => l.Code == "PUBB"), cancellationToken).ConfigureAwait(false) is { } publicList + && publicList.BasePriceListId == baseList.Id) + { + await AddAsync(uow, context, "item_prices", new ItemPrice { ItemId = boiler.Id, PriceListId = publicList.Id, Price = 1690m, ValidFrom = thisYear }, cancellationToken).ConfigureAwait(false); + } + } + + private static async Task AddAsync(IUnitOfWork uow, SeedContext context, string table, T row, CancellationToken cancellationToken) + where T : class, Khaemhat.Core.Entities.IEntity, new() + { + await uow.Repository().InsertAsync(row, cancellationToken).ConfigureAwait(false); + context.Count(table); + } + + /// A fictitious EAN-13 with the prefix 200, for internal use, and a valid check digit. + /// The progressive number. + /// The code. + public static string Ean(int number) + { + var digits = "200" + number.ToString("000000000", CultureInfo.InvariantCulture); + return digits + EanValidator.CheckDigit(digits).ToString(CultureInfo.InvariantCulture); + } + + private static DemoItem Goods(string category, string description, string unit, decimal price, string? brand, string? customs, decimal? weight) => + new(category, ItemKind.Goods, description, unit, Math.Round(price, 2), brand, customs, weight); + + private static DemoItem Other(ItemKind kind, string category, string description, string unit, decimal? price) => + new(category, kind, description, unit, price, null, null, null); +} + +/// An item of the demo catalogue. +/// The category code. +/// What it is. +/// The description. +/// The unit code. +/// The price of the base list (goods) or of the item (services and expenses). +/// The fictitious brand. +/// The combined nomenclature. +/// The net weight in kg. +public sealed record DemoItem(string Category, ItemKind Kind, string Description, string Unit, decimal? Price, string? Brand, string? CustomsCode, decimal? Weight); diff --git a/src/Khaemhat.Application/Seeding/DemoPartiesSeeder.cs b/src/Khaemhat.Application/Seeding/DemoPartiesSeeder.cs new file mode 100644 index 0000000..1407be1 --- /dev/null +++ b/src/Khaemhat.Application/Seeding/DemoPartiesSeeder.cs @@ -0,0 +1,293 @@ +using Khaemhat.Application.Modules; +using Khaemhat.Application.Parties; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Application.Seeding; + +/// +/// The parties of the demo company (SPEC §14, issue #41): customers of every kind of subject (companies, public +/// administration with split payment, private persons, EU and non-EU companies, flat rate, a declaration of intent, a +/// customer blocked over its credit, one that is also a supplier, one disabled), suppliers (a professional with +/// withholding, an ENASARCO agent, an EU supplier), prospects and leads, and three salespeople. Every name, number and +/// bank account is fictitious: the VAT numbers have a valid check digit, the IBANs a valid check, the ABI codes belong +/// to no bank. Runs only on a company without parties; the rows are marked as demo. +/// +/// The automatic code rules. +public sealed class DemoPartiesSeeder(CodeRuleService codes) : ISeeder +{ + /// The fictitious VAT numbers, valid for the Italian check digit (tests check them with the pack). + public static readonly IReadOnlyList VatNumbers = + [ + "04123456784", "05234567898", "06345678905", "07456789010", "08567890127", "09678901233", "10789012340", "11890123455", + "12901234562", "13012345677", "14123456700", "15234567814", "16345678920", "17456789035", + ]; + + /// The fictitious tax code of the public administration (numeric, valid check digit). + public const string AdministrationTaxCode = "80012345676"; + + /// The fictitious IBANs, with a valid check and ABI codes of no bank. + public static readonly IReadOnlyList Ibans = ["IT53X0123410100000012345678", "IT21X0567822000000000987654", "IT11X0987645600000101234567"]; + + /// + public string ModuleCode => ModuleCodes.Core; + + /// + public SeedKind Kind => SeedKind.Demo; + + /// + public int Order => 10; + + /// + public async Task RunAsync(SeedContext context, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + var uow = context.UnitOfWork; + if (await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) > 0) + { + return; + } + + var rules = new Dictionary(); + foreach (var kind in Enum.GetValues()) + { + rules[kind] = await codes.RuleAsync(context.CompanyCode, PartyService.CodeRuleOf(kind), cancellationToken).ConfigureAwait(false); + } + + var salespeople = await context.EnsureAsync( + "salespeople", + [ + new Salesperson { Code = "VERDI", Description = "Marco Verdi", Email = "m.verdi@demo.example", CommissionPercent = 5m, Enasarco = true }, + new Salesperson { Code = "NERI", Description = "Laura Neri", Email = "l.neri@demo.example", CommissionPercent = 4m, Enasarco = true }, + new Salesperson { Code = "BIANCO", Description = "Paolo Bianco", Email = "p.bianco@demo.example", CommissionPercent = 3m }, + ], + cancellationToken).ConfigureAwait(false); + var terms = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items + .ToDictionary(t => t.Code, t => t.Id, StringComparer.OrdinalIgnoreCase); + var priceList = (await uow.Repository().FindAsync(Query.For().Where(p => p.Code == "BASE"), cancellationToken).ConfigureAwait(false))?.Id; + long? Term(string code) => terms.TryGetValue(code, out var id) ? id : null; + long? Agent(string code) => salespeople.TryGetValue(code, out var s) ? s.Id : null; + var identifiers = context.Pack.GetFeature(); + var year = context.Today.Year; + + var seeds = new List + { + Customer("Rossi Impianti S.r.l.", SubjectType.Company, VatNumbers[0], "Via Nizza", "120", "10126", "Torino", "TO", Term("RB60FM"), Agent("VERDI"), r => + { + r.Fiscal.RecipientCode = "M5UXCR1"; + r.Party.Phone = "011 5550101"; + r.Party.Email = "amministrazione@rossi-impianti.example"; + r.Contacts.Add(new PartyContact { Name = "Mario Rossi", Role = "Titolare", Mobile = "333 5550101", Email = "mario@rossi-impianti.example", IsDefault = true }); + r.Contacts.Add(new PartyContact { Name = "Anna Ferri", Role = "Amministrazione", Phone = "011 5550102", Email = "amministrazione@rossi-impianti.example" }); + r.Addresses.Add(new PartyAddress { Kind = PartyAddressKind.Site, Name = "Cantiere Lingotto", Address = "Via Ventimiglia", StreetNumber = "88", PostalCode = "10126", City = "Torino", Province = "TO", IsDefault = true }); + r.BankAccounts.Add(new PartyBankAccount { Iban = Ibans[0], BankCode = "01234", BranchCode = "10100", IsDefault = true }); + r.Sales.Discount1 = 5m; + r.Sales.CreditLimit = 30000m; + r.Sales.SendDocuments = DocumentDelivery.Email; + r.Sales.DocumentsEmail = "amministrazione@rossi-impianti.example"; + }), + Customer("Bianchi & Figli S.n.c.", SubjectType.Company, VatNumbers[1], "Corso Langhe", "5", "12051", "Alba", "CN", Term("RB3060FM"), Agent("VERDI"), r => + { + r.Fiscal.RecipientCode = "0000000"; + r.Fiscal.RecipientPec = "bianchiefigli@pec.demo.example"; + r.Party.Pec = "bianchiefigli@pec.demo.example"; + }), + Customer("Comune di Valdora", SubjectType.PublicAdministration, null, "Piazza del Municipio", "1", "12060", "Valdora", "CN", Term("BB30"), null, r => + { + r.Party.TaxCode = AdministrationTaxCode; + r.Fiscal.RecipientCode = "UFX9K2"; + r.Fiscal.SplitPayment = true; + r.Fiscal.Exigibility = "S"; + r.Fiscal.AdministrationReference = "SETT-TECNICO"; + }), + Customer("Ferramenta Gallo", SubjectType.Company, VatNumbers[2], "Corso Alfieri", "210", "14100", "Asti", "AT", Term("RD"), Agent("NERI"), r => + { + r.Fiscal.RecipientCode = "KRRH6B9"; + r.Sales.CreditLimit = 5000m; + r.Sales.Blocked = true; + r.Party.Notes = "Ordini bloccati: fido superato, rientro concordato entro fine mese."; + }), + Customer("Bergwerk Bau GmbH", SubjectType.EuCompany, "U12345678", "Museumstrasse", "12", "6020", "Innsbruck", null, Term("BB30"), Agent("NERI"), r => + { + r.Party.CountryCode = "AT"; + r.Party.Language = "de"; + r.Fiscal.RecipientCode = "XXXXXXX"; + }), + Customer("Esposito Mario", SubjectType.Person, null, "Via Po", "18", "10124", "Torino", "TO", Term("RD"), null, r => + { + r.Party.LastName = "Esposito"; + r.Party.FirstName = "Mario"; + r.Party.TaxCode = Personal(identifiers, "Esposito", "Mario", new DateOnly(1980, 1, 1), PersonSex.Male, "L219"); + r.Party.Email = "mario.esposito@posta.example"; + r.Fiscal.RecipientCode = "0000000"; + r.Party.PrivacyAccepted = true; + }), + Customer("Idrotermica Piemonte S.r.l.", SubjectType.Company, VatNumbers[3], "Via Roma", "44", "12100", "Cuneo", "CN", Term("RB3060FM"), Agent("VERDI"), r => + { + r.Fiscal.RecipientCode = "T04ZHR3"; + r.Fiscal.IntentActive = true; + r.Fiscal.IntentNumber = "14/" + year; + r.Fiscal.IntentDate = new DateOnly(year, 1, 15); + r.Fiscal.IntentProtocol = "26011512345678901-000001"; + r.Fiscal.IntentCeiling = 150000m; + r.Fiscal.IntentFrom = new DateOnly(year, 1, 1); + r.Fiscal.IntentTo = new DateOnly(year, 12, 31); + }), + Customer("Nordic Pipes AS", SubjectType.NonEuCompany, "987654321", "Storgata", "7", "0155", "Oslo", null, Term("RD"), Agent("NERI"), r => + { + r.Party.CountryCode = "NO"; + r.Party.Language = "en"; + r.Fiscal.RecipientCode = "XXXXXXX"; + }), + Customer("Studio Tecnico Ing. Ferrero", SubjectType.FlatRate, VatNumbers[4], "Via Vittorio Emanuele", "3", "12051", "Alba", "CN", Term("BB30"), null, r => + { + r.Fiscal.RecipientCode = "USAL8PV"; + r.Fiscal.StampDutyCharged = true; + }), + Customer("Edilizia Moderna S.p.A.", SubjectType.Company, VatNumbers[5], "Viale Monza", "250", "20126", "Milano", "MI", Term("RB3060FM"), Agent("BIANCO"), r => + { + r.Party.IsAlsoSupplier = true; + r.Fiscal.RecipientCode = "W7YVJK9"; + r.Purchase.PaymentTermId = Term("BB30FM"); + r.Sales.Discount1 = 10m; + r.Sales.Discount2 = 3m; + }), + Customer("Termoidraulica Sacco", SubjectType.Company, VatNumbers[6], "Via Cavour", "9", "12042", "Bra", "CN", Term("RD"), Agent("NERI"), r => + { + r.Fiscal.RecipientCode = "SUBM70N"; + r.Party.Disabled = true; + r.Party.Notes = "Attività cessata."; + }), + Customer("Hotel Belvedere S.r.l.", SubjectType.Company, VatNumbers[7], "Passeggiata Cadorna", "15", "17021", "Alassio", "SV", Term("BB30FM"), Agent("BIANCO"), r => + { + r.Fiscal.RecipientCode = "5RUO82D"; + r.Contacts.Add(new PartyContact { Name = "Giulia Marino", Role = "Direzione", Phone = "0182 555010", IsDefault = true }); + }), + Supplier("Metalli Nord S.p.A.", VatNumbers[8], "Via Industriale", "40", "25125", "Brescia", "BS", Term("RB60FM"), r => + { + r.Purchase.LeadTimeDays = 10; + r.Purchase.MinimumOrder = 500m; + r.Purchase.OrdersEmail = "ordini@metalli-nord.example"; + r.BankAccounts.Add(new PartyBankAccount { Iban = Ibans[1], BankCode = "05678", BranchCode = "22000", IsDefault = true }); + }), + Supplier("Plastica Sud S.r.l.", VatNumbers[9], "Via Appia", "301", "81100", "Caserta", "CE", Term("BB30FM"), r => r.Purchase.LeadTimeDays = 15), + Supplier("Studio Rag. Neri Paola", VatNumbers[10], "Via Vittorio Veneto", "21", "12100", "Cuneo", "CN", Term("RD"), r => + { + r.Fiscal.Withholding = true; + r.Fiscal.WithholdingRate = 20m; + r.Fiscal.WithholdingReason = "A"; + r.Fiscal.PensionFund = "TC04"; + r.Fiscal.PensionFundRate = 4m; + r.BankAccounts.Add(new PartyBankAccount { Iban = Ibans[2], BankCode = "09876", BranchCode = "45600", IsDefault = true }); + }), + Supplier("Agenzia Commerciale Bruno", VatNumbers[11], "Corso Francia", "77", "10138", "Torino", "TO", Term("BB30FM"), r => + { + r.Fiscal.Withholding = true; + r.Fiscal.WithholdingRate = 23m; + r.Fiscal.WithholdingReason = "R"; + r.Fiscal.Enasarco = true; + }), + Supplier("Elektro Werke Süd GmbH", "123456789", "Industriestrasse", "5", "80331", "München", null, Term("BB30"), r => + { + r.Party.SubjectType = SubjectType.EuCompany; + r.Party.CountryCode = "DE"; + r.Party.Language = "de"; + }), + Contact(PartyKind.Prospect, "Caseificio Valle Stura S.r.l.", VatNumbers[12], "12014", "Demonte", "CN", Agent("VERDI")), + Contact(PartyKind.Prospect, "Agriturismo Le Vigne", VatNumbers[13], "12060", "Barolo", "CN", Agent("BIANCO")), + Contact(PartyKind.Lead, "Fontana Marco (fiera di Bologna)", null, null, null, null, Agent("NERI")), + Contact(PartyKind.Lead, "Cantina Sociale del Roero", null, "12043", "Canale", "CN", null), + }; + + foreach (var record in seeds) + { + record.Sales.PriceListId ??= record.Party.IsCustomer ? priceList : null; + await InsertAsync(uow, record, rules[record.Party.Kind], context.Today, cancellationToken).ConfigureAwait(false); + context.Count("parties"); + } + } + + private static PartyRecord Customer(string name, SubjectType subject, string? vat, string address, string number, string postalCode, string city, string? province, + long? paymentTermId, long? salespersonId, Action more) + { + var record = New(PartyKind.Customer, name, subject, vat, postalCode, city, province, salespersonId); + record.Party.Address = address; + record.Party.StreetNumber = number; + record.Sales.PaymentTermId = paymentTermId; + more(record); + return record; + } + + private static PartyRecord Supplier(string name, string vat, string address, string number, string postalCode, string city, string? province, long? paymentTermId, + Action more) + { + var record = New(PartyKind.Supplier, name, SubjectType.Company, vat, postalCode, city, province, null); + record.Party.Address = address; + record.Party.StreetNumber = number; + record.Purchase.PaymentTermId = paymentTermId; + more(record); + return record; + } + + private static PartyRecord Contact(PartyKind kind, string name, string? vat, string? postalCode, string? city, string? province, long? salespersonId) => + New(kind, name, SubjectType.Company, vat, postalCode, city, province, salespersonId); + + private static PartyRecord New(PartyKind kind, string name, SubjectType subject, string? vat, string? postalCode, string? city, string? province, long? salespersonId) => new() + { + Party = new Party + { + Kind = kind, Name = name, SubjectType = subject, VatNumber = vat, PostalCode = postalCode, City = city, Province = province, SalespersonId = salespersonId, + CategoryId = null, PrivacyAccepted = kind is PartyKind.Customer or PartyKind.Supplier, IsDemo = true, + }, + }; + + private static string? Personal(ITaxIdentifierRules? rules, string surname, string name, DateOnly birth, PersonSex sex, string place) => + rules?.ComputePersonalTaxCode(new PersonalTaxCodeData(surname, name, birth, sex, place)); + + private static async Task InsertAsync(IUnitOfWork uow, PartyRecord record, CodeRule rule, DateOnly today, CancellationToken cancellationToken) + { + var parties = uow.Repository(); + var party = record.Party; + party.Code = await CodeRuleService.AssignAsync( + uow, rule, today, null, + async (code, ct) => await parties.CountAsync(Query.For().Where(p => p.Code == code), ct).ConfigureAwait(false) > 0, + cancellationToken).ConfigureAwait(false); + party.Id = await parties.InsertAsync(party, cancellationToken).ConfigureAwait(false); + if (party.IsCustomer) + { + record.Sales.PartyId = party.Id; + await uow.Repository().InsertAsync(record.Sales, cancellationToken).ConfigureAwait(false); + } + + if (party.IsSupplier) + { + record.Purchase.PartyId = party.Id; + await uow.Repository().InsertAsync(record.Purchase, cancellationToken).ConfigureAwait(false); + } + + record.Fiscal.PartyId = party.Id; + await uow.Repository().InsertAsync(record.Fiscal, cancellationToken).ConfigureAwait(false); + foreach (var address in record.Addresses) + { + address.PartyId = party.Id; + address.CountryCode = address.CountryCode.Length == 0 ? party.CountryCode : address.CountryCode; + await uow.Repository().InsertAsync(address, cancellationToken).ConfigureAwait(false); + } + + foreach (var contact in record.Contacts) + { + contact.PartyId = party.Id; + await uow.Repository().InsertAsync(contact, cancellationToken).ConfigureAwait(false); + } + + foreach (var account in record.BankAccounts) + { + account.PartyId = party.Id; + await uow.Repository().InsertAsync(account, cancellationToken).ConfigureAwait(false); + } + } +} diff --git a/src/Khaemhat.Application/Seeding/Seeding.cs b/src/Khaemhat.Application/Seeding/Seeding.cs new file mode 100644 index 0000000..1008f89 --- /dev/null +++ b/src/Khaemhat.Application/Seeding/Seeding.cs @@ -0,0 +1,305 @@ +using Khaemhat.Application.Instance; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Entities; +using Khaemhat.Core.Instance; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; +using Microsoft.Extensions.Logging; + +namespace Khaemhat.Application.Seeding; + +/// The kind of data a seeder loads (SPEC §14). +public enum SeedKind +{ + /// The base tables every company needs. + Base = 0, + + /// The fictitious demo company. + Demo = 1, +} + +/// A source of base or demo data (SPEC §14). Seeders are idempotent: they add what is missing and change nothing else. +public interface ISeeder +{ + /// The licence module whose tables it fills (CORE, ACCT...). + string ModuleCode { get; } + + /// Base or demo. + SeedKind Kind { get; } + + /// The order among seeders of the same kind (lower first). + int Order { get; } + + /// Loads the data. + /// The company, its unit of work and fiscal pack. + /// Cancellation. + /// A task. + Task RunAsync(SeedContext context, CancellationToken cancellationToken); +} + +/// What a seeder works with, and the counts of what it added. +public sealed class SeedContext +{ + private readonly Dictionary _added = new(StringComparer.Ordinal); + + /// Creates the context. + /// The company. + /// The company unit of work, committed by the runner. + /// The fiscal pack of the company. + /// Today, for the current year. + public SeedContext(string companyCode, IUnitOfWork unitOfWork, IFiscalPack pack, DateOnly today) + { + ArgumentException.ThrowIfNullOrWhiteSpace(companyCode); + ArgumentNullException.ThrowIfNull(unitOfWork); + ArgumentNullException.ThrowIfNull(pack); + CompanyCode = companyCode; + UnitOfWork = unitOfWork; + Pack = pack; + Today = today; + } + + /// The company. + public string CompanyCode { get; } + + /// The company unit of work. + public IUnitOfWork UnitOfWork { get; } + + /// The fiscal pack. + public IFiscalPack Pack { get; } + + /// Today. + public DateOnly Today { get; } + + /// How many times the demo seeders repeat their catalogues (seed --demo --scale N), at least 1. + public int Scale { get; init; } = 1; + + /// Rows added, by table. + public IReadOnlyDictionary Added => _added; + + /// Adds the rows whose code is missing; existing rows are left as the users made them. + /// The entity. + /// The table, for the counts. + /// The rows. + /// Cancellation. + /// Every row of the seed as stored (the existing one when the code was there). + public async Task> EnsureAsync(string table, IEnumerable rows, CancellationToken cancellationToken) + where T : CodedEntity, new() + { + ArgumentNullException.ThrowIfNull(rows); + var repository = UnitOfWork.Repository(); + var existing = (await repository.ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items + .GroupBy(r => r.Code, StringComparer.OrdinalIgnoreCase) + .ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase); + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var row in rows) + { + if (existing.TryGetValue(row.Code, out var found)) + { + result[row.Code] = found; + continue; + } + + row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false); + existing[row.Code] = row; + result[row.Code] = row; + Count(table); + } + + return result; + } + + /// Adds one row when nothing matches a condition. + /// The entity. + /// The table, for the counts. + /// Finds the row. + /// The row to add. + /// Cancellation. + /// The stored row. + public async Task EnsureOneAsync(string table, System.Linq.Expressions.Expression> match, T row, CancellationToken cancellationToken) + where T : class, IEntity, new() + { + ArgumentNullException.ThrowIfNull(row); + var repository = UnitOfWork.Repository(); + var found = await repository.FindAsync(Query.For().Where(match), cancellationToken).ConfigureAwait(false); + if (found is not null) + { + return found; + } + + row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false); + Count(table); + return row; + } + + /// Counts a row added by hand. + /// The table. + public void Count(string table) => _added[table] = _added.GetValueOrDefault(table) + 1; +} + +/// The outcome of a seed run. +/// The data version now recorded, such as IT 2026.2. +/// Rows added, by table. +public sealed record SeedReport(string DataVersion, IReadOnlyDictionary Added) +{ + /// Total rows added. + public int Total => Added.Values.Sum(); +} + +/// +/// Runs the seeders of a kind on a company in one unit of work and records the data version in the company setting +/// (SPEC §14). At company creation and at every start it runs the base seeders when +/// KHAEMHAT_SEED_BASE is on; the button Aggiorna tabelle di base and scripts/seed.sh --base run +/// them on demand. Being idempotent, running again only adds what a newer data version brings. +/// +public sealed partial class SeedRunner : ICompanySeeder +{ + /// The company setting with the version of the base data. + public const string VersionSetting = "seed.base.version"; + + private readonly IReadOnlyList _seeders; + private readonly IUnitOfWorkFactory _factory; + private readonly CompanyFiscalContext _fiscal; + private readonly PermissionService _permissions; + private readonly TableService _tables; + private readonly FiscalYearService _years; + private readonly TimeProvider _clock; + private readonly ILogger _logger; + + /// Creates the runner. + /// The seeders. + /// Opens the company databases. + /// The fiscal pack of each company. + /// Checks permissions (the button). + /// The tables (cache invalidation). + /// The fiscal years (cache invalidation). + /// The clock. + /// The log. + public SeedRunner( + IEnumerable seeders, IUnitOfWorkFactory factory, CompanyFiscalContext fiscal, PermissionService permissions, TableService tables, + FiscalYearService years, TimeProvider clock, ILogger logger) + { + ArgumentNullException.ThrowIfNull(seeders); + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(fiscal); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(tables); + ArgumentNullException.ThrowIfNull(years); + ArgumentNullException.ThrowIfNull(clock); + ArgumentNullException.ThrowIfNull(logger); + _seeders = [.. seeders.OrderBy(s => s.Kind).ThenBy(s => s.Order)]; + _factory = factory; + _fiscal = fiscal; + _permissions = permissions; + _tables = tables; + _years = years; + _clock = clock; + _logger = logger; + } + + /// + public int Order => 10; + + /// + public async Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(context); + if (context.Base) + { + await RunAsync(companyCode, SeedKind.Base, cancellationToken).ConfigureAwait(false); + } + + // The demo seeders fill only a company without data of their own (each checks its tables). + if (context.Demo) + { + await RunAsync(companyCode, SeedKind.Demo, cancellationToken).ConfigureAwait(false); + } + } + + /// The button Aggiorna tabelle di base: runs the base seeders for a company. + /// Who asks: needs company.settings.write. + /// The company. + /// Cancellation. + /// What was added. + public async Task UpdateBaseAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.WritePermission, cancellationToken).ConfigureAwait(false); + return await RunAsync(company, SeedKind.Base, cancellationToken).ConfigureAwait(false); + } + + /// The data version recorded in a company, or before the first run. + /// The company. + /// Cancellation. + /// The version. + public async Task VersionAsync(string companyCode, CancellationToken cancellationToken = default) + { + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(CompanyCodes.Normalize(companyCode)), cancellationToken).ConfigureAwait(false); + var setting = await uow.Repository().FindAsync(Query.For().Where(s => s.Key == VersionSetting), cancellationToken).ConfigureAwait(false); + return setting?.Value; + } + + /// Runs every seeder of a kind on a company. + /// The company. + /// Base or demo. + /// Cancellation. + /// What was added. + public Task RunAsync(string companyCode, SeedKind kind, CancellationToken cancellationToken = default) => + RunAsync(companyCode, kind, 1, cancellationToken); + + /// Runs every seeder of a kind on a company, the demo ones repeating their catalogues. + /// The company. + /// Base or demo. + /// How many times the demo catalogues are repeated (--scale), at least 1. + /// Cancellation. + /// What was added. + public async Task RunAsync(string companyCode, SeedKind kind, int scale, CancellationToken cancellationToken = default) + { + var company = CompanyCodes.Normalize(companyCode); + var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false); + var today = DateOnly.FromDateTime(_clock.GetLocalNow().DateTime); + SeedContext context; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + context = new SeedContext(company, uow, pack, today) { Scale = Math.Max(1, scale) }; + foreach (var seeder in _seeders.Where(s => s.Kind == kind)) + { + await seeder.RunAsync(context, cancellationToken).ConfigureAwait(false); + } + + if (kind == SeedKind.Base) + { + await WriteVersionAsync(uow, pack.DataVersion, cancellationToken).ConfigureAwait(false); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + await _tables.InvalidateAllAsync(company, cancellationToken).ConfigureAwait(false); + await _years.InvalidateAsync(company, cancellationToken).ConfigureAwait(false); + await _fiscal.InvalidateAsync(company, cancellationToken).ConfigureAwait(false); + var report = new SeedReport(pack.DataVersion, context.Added); + LogSeeded(_logger, kind, company, pack.DataVersion, report.Total); + return report; + } + + private static async Task WriteVersionAsync(IUnitOfWork uow, string version, CancellationToken cancellationToken) + { + var settings = uow.Repository(); + var setting = await settings.FindAsync(Query.For().Where(s => s.Key == VersionSetting), cancellationToken).ConfigureAwait(false); + if (setting is null) + { + await settings.InsertAsync(new CompanySetting { Key = VersionSetting, Value = version }, cancellationToken).ConfigureAwait(false); + } + else if (setting.Value != version) + { + setting.Value = version; + await settings.UpdateAsync(setting, cancellationToken).ConfigureAwait(false); + } + } + + [LoggerMessage(Level = LogLevel.Information, Message = "Dati {Kind} dell'azienda {Company} (versione {Version}): {Added} righe aggiunte.")] + private static partial void LogSeeded(ILogger logger, SeedKind kind, string company, string version, int added); +} 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/CompanyFiscalContext.cs b/src/Khaemhat.Application/Tables/CompanyFiscalContext.cs new file mode 100644 index 0000000..49e1fd0 --- /dev/null +++ b/src/Khaemhat.Application/Tables/CompanyFiscalContext.cs @@ -0,0 +1,72 @@ +using Khaemhat.Application.Configuration; +using Khaemhat.Core.Caching; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Application.Tables; + +/// +/// The fiscal pack of each company: the one of company_profile.country, or of KHAEMHAT_COUNTRY while the +/// profile is missing (ADR 0025). The country is cached per company. +/// +public sealed class CompanyFiscalContext +{ + private static readonly TimeSpan CacheTime = TimeSpan.FromHours(1); + + private readonly IUnitOfWorkFactory _factory; + private readonly FiscalPackCatalog _packs; + private readonly ICacheProvider _cache; + private readonly string _defaultCountry; + + /// Creates the context. + /// Opens the company databases. + /// The fiscal packs. + /// The cache. + /// The instance options (KHAEMHAT_COUNTRY). + public CompanyFiscalContext(IUnitOfWorkFactory factory, FiscalPackCatalog packs, ICacheProvider cache, KhaemhatOptions options) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(packs); + ArgumentNullException.ThrowIfNull(cache); + ArgumentNullException.ThrowIfNull(options); + _factory = factory; + _packs = packs; + _cache = cache; + _defaultCountry = options.Country; + } + + /// The country given to new companies. + public string DefaultCountry => _defaultCountry; + + /// The pack of the instance's default country. + public IFiscalPack DefaultPack => _packs.ForCountry(_defaultCountry); + + /// The fiscal pack of a company. + /// The company. + /// Cancellation. + /// The pack. + public async Task PackOfAsync(string companyCode, CancellationToken cancellationToken = default) + { + var company = CompanyCodes.Normalize(companyCode); + var country = await _cache.GetOrCreateAsync( + CacheKeys.For(company, "fiscal", "country"), + async ct => + { + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), ct).ConfigureAwait(false); + var profile = await uow.Repository().FindAsync(Query.For(), ct).ConfigureAwait(false); + return profile?.Country ?? _defaultCountry; + }, + CacheTime, + cancellationToken).ConfigureAwait(false); + return _packs.TryForCountry(country, out var pack) ? pack : DefaultPack; + } + + /// Forgets the cached country of a company (after the profile changes). + /// The company. + /// Cancellation. + /// A task. + public ValueTask InvalidateAsync(string companyCode, CancellationToken cancellationToken = default) => + _cache.PublishInvalidationAsync(CacheKeys.Prefix(CompanyCodes.Normalize(companyCode), "fiscal"), cancellationToken); +} diff --git a/src/Khaemhat.Application/Tables/CompanyProfileService.cs b/src/Khaemhat.Application/Tables/CompanyProfileService.cs new file mode 100644 index 0000000..ccdf48c --- /dev/null +++ b/src/Khaemhat.Application/Tables/CompanyProfileService.cs @@ -0,0 +1,287 @@ +using System.Text.RegularExpressions; +using Khaemhat.Application.Audit; +using Khaemhat.Application.Security; +using Khaemhat.Core.Tables; +using Khaemhat.Core.Tax; +using Khaemhat.Core.Validation; +using Khaemhat.Data; +using Khaemhat.Data.Companies; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Application.Tables; + +/// +/// The company profile (SPEC §11.1, mockup 075): one row per company, created on the first save. The country chooses +/// the fiscal pack; changing it is refused once documents exist (from M5). +/// +public sealed partial class CompanyProfileService +{ + /// Error: the name is missing. + public const string NameRequired = "profile.name.required"; + + /// Error: no fiscal pack for the country. + public const string CountryUnknown = "profile.country.unknown"; + + /// Error: the month is outside 1-12. + public const string MonthRange = "profile.month.range"; + + /// Error: a code that must be two letters. + public const string TwoLettersRequired = "profile.two-letters"; + + /// Error: the tax code is not valid. + public const string TaxCodeInvalid = "profile.tax-code.invalid"; + + /// Error: the recipient code is not seven characters. + public const string RecipientCodeInvalid = "profile.recipient-code.invalid"; + + /// Error: a value outside the list (SU/SM, LS/LN). + public const string ValueInvalid = "profile.value.invalid"; + + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly AuditTrail _audit; + private readonly CompanyFiscalContext _fiscal; + private readonly FiscalPackCatalog _packs; + private readonly ICompanyRegistry _companies; + + /// Creates the service. + /// Opens the company databases. + /// Checks permissions. + /// Writes the history. + /// The fiscal pack of each company. + /// The installed fiscal packs. + /// The registry, for the name of a company without a profile yet. + public CompanyProfileService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, CompanyFiscalContext fiscal, FiscalPackCatalog packs, ICompanyRegistry companies) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(audit); + ArgumentNullException.ThrowIfNull(fiscal); + ArgumentNullException.ThrowIfNull(packs); + ArgumentNullException.ThrowIfNull(companies); + _companies = companies; + _factory = factory; + _permissions = permissions; + _audit = audit; + _fiscal = fiscal; + _packs = packs; + } + + /// The profile, or a new one with the defaults of the instance when the company has none yet. + /// Who reads. + /// The company. + /// Cancellation. + /// The profile ( 0 when new). + public async Task GetAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.ReadPermission, cancellationToken).ConfigureAwait(false); + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + if (await LoadAsync(uow, cancellationToken).ConfigureAwait(false) is { } profile) + { + return profile; + } + } + + // A new profile starts from the name the company was registered with. + var registered = await _companies.FindAsync(company, cancellationToken).ConfigureAwait(false); + return NewProfile(registered?.Name is { Length: > 0 } name ? name : company); + } + + /// Checks a profile without saving it. + /// The profile (normalized in place). + /// Errors and warnings by field. + public IReadOnlyList Validate(CompanyProfile profile) + { + ArgumentNullException.ThrowIfNull(profile); + var problems = new List(); + profile.LegalName = profile.LegalName.Trim(); + profile.Country = profile.Country.Trim().ToUpperInvariant(); + if (profile.LegalName.Length == 0) + { + problems.Add(new(nameof(CompanyProfile.LegalName), NameRequired)); + } + + if (!_packs.TryForCountry(profile.Country, out var pack)) + { + problems.Add(new(nameof(CompanyProfile.Country), CountryUnknown)); + pack = _fiscal.DefaultPack; + } + + if (pack.GetFeature() is { } rules) + { + if (!string.IsNullOrWhiteSpace(profile.VatNumber)) + { + profile.VatNumber = rules.NormalizeVatNumber(profile.VatNumber); + if (!rules.IsValidVatNumber(profile.VatNumber)) + { + problems.Add(new(nameof(CompanyProfile.VatNumber), TableCatalog.VatNumberInvalid)); + } + } + + if (!string.IsNullOrWhiteSpace(profile.TaxCode)) + { + profile.TaxCode = profile.TaxCode.Trim().ToUpperInvariant(); + if (!rules.IsValidTaxCode(profile.TaxCode)) + { + problems.Add(new(nameof(CompanyProfile.TaxCode), TaxCodeInvalid)); + } + } + } + + if (pack.GetFeature() is { } format && format.TaxRegimes.Find(profile.TaxRegime) is not { Obsolete: false }) + { + problems.Add(new(nameof(CompanyProfile.TaxRegime), TableCatalog.NotInCodeList)); + } + + if (!string.IsNullOrWhiteSpace(profile.RecipientCode)) + { + profile.RecipientCode = profile.RecipientCode.Trim().ToUpperInvariant(); + if (!RecipientCode().IsMatch(profile.RecipientCode)) + { + problems.Add(new(nameof(CompanyProfile.RecipientCode), RecipientCodeInvalid)); + } + } + + CheckTwoLetters(profile.ProvinceCode, nameof(CompanyProfile.ProvinceCode), problems, v => profile.ProvinceCode = v); + CheckTwoLetters(profile.ReaOffice, nameof(CompanyProfile.ReaOffice), problems, v => profile.ReaOffice = v); + CheckTwoLetters(profile.AddressCountry, nameof(CompanyProfile.AddressCountry), problems, v => profile.AddressCountry = v); + CheckTwoLetters(profile.TransmitterCountry, nameof(CompanyProfile.TransmitterCountry), problems, v => profile.TransmitterCountry = v); + if (profile.Shareholders is { Length: > 0 } shareholders && shareholders is not ("SU" or "SM")) + { + problems.Add(new(nameof(CompanyProfile.Shareholders), ValueInvalid)); + } + + if (profile.LiquidationStatus is { Length: > 0 } liquidation && liquidation is not ("LS" or "LN")) + { + problems.Add(new(nameof(CompanyProfile.LiquidationStatus), ValueInvalid)); + } + + foreach (var (value, field) in new[] { (profile.Email, nameof(CompanyProfile.Email)), (profile.Pec, nameof(CompanyProfile.Pec)) }) + { + if (!string.IsNullOrWhiteSpace(value) && !EmailValidator.IsValid(value)) + { + problems.Add(new(field, TableCatalog.EmailInvalid)); + } + } + + if (profile.ProRataPercent is < 0 or > 100) + { + problems.Add(new(nameof(CompanyProfile.ProRataPercent), TableCatalog.PercentRange)); + } + + if (profile.FiscalYearStartMonth is < 1 or > 12) + { + problems.Add(new(nameof(CompanyProfile.FiscalYearStartMonth), MonthRange)); + } + + profile.CurrencyCode = profile.CurrencyCode.Trim().ToUpperInvariant(); + if (profile.CurrencyCode.Length != 3) + { + problems.Add(new(nameof(CompanyProfile.CurrencyCode), TableCatalog.CodePattern)); + } + + return problems; + } + + /// Saves the profile (inserted the first time). + /// Who saves. + /// The company. + /// The profile. + /// Cancellation. + /// The saved profile. + /// A rule failed (Field:code). + public async Task SaveAsync(Actor actor, string companyCode, CompanyProfile profile, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(profile); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.WritePermission, cancellationToken).ConfigureAwait(false); + var errors = Validate(profile).Where(p => !p.IsWarning).Select(p => p.Field + ":" + p.Code).ToList(); + if (errors.Count > 0) + { + throw new ValidationFailedException(errors); + } + + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + var before = await LoadAsync(uow, cancellationToken).ConfigureAwait(false); + if (before is null) + { + profile.Id = await repository.InsertAsync(profile, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Insert, profile.Id, null, profile, actor.UserName, cancellationToken).ConfigureAwait(false); + } + else + { + profile.Id = before.Id; + await repository.UpdateAsync(profile, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, profile.Id, before, profile, actor.UserName, cancellationToken).ConfigureAwait(false); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + await _fiscal.InvalidateAsync(company, cancellationToken).ConfigureAwait(false); + return profile; + } + + /// A new profile with the defaults of the instance (country from KHAEMHAT_COUNTRY). + /// The name proposed. + /// The profile. + public CompanyProfile NewProfile(string companyName) => new() + { + LegalName = companyName, + Country = _fiscal.DefaultCountry.ToUpperInvariant(), + AddressCountry = _fiscal.DefaultCountry.ToUpperInvariant(), + CurrencyCode = "EUR", + VatPeriodicity = VatPeriodicity.Monthly, + LiquidationStatus = "LN", + }; + + internal static Task LoadAsync(IUnitOfWork uow, CancellationToken cancellationToken) => + uow.Repository().FindAsync(Query.For().OrderBy(x => x.Id), cancellationToken); + + private static void CheckTwoLetters(string? value, string field, List problems, Action set) + { + if (string.IsNullOrWhiteSpace(value)) + { + set(null); + return; + } + + var upper = value.Trim().ToUpperInvariant(); + set(upper); + if (upper.Length != 2 || !upper.All(char.IsAsciiLetterUpper)) + { + problems.Add(new(field, TwoLettersRequired)); + } + } + + [GeneratedRegex("^[A-Z0-9]{6,7}$", RegexOptions.CultureInvariant)] + private static partial Regex RecipientCode(); +} + +/// The common access check of the company services. +internal static class CompanyGuard +{ + /// Checks that the actor works in the company and has the permission. + /// The permission service. + /// Who acts. + /// The company. + /// The permission. + /// Cancellation. + /// The normalized company code. + public static async Task DemandAsync(PermissionService permissions, Actor actor, string companyCode, string permission, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(actor); + var company = CompanyCodes.Normalize(companyCode); + if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, company, StringComparison.Ordinal)) + { + throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A company user works only in its own company."); + } + + await permissions.DemandAsync(actor, permission, cancellationToken).ConfigureAwait(false); + return company; + } +} diff --git a/src/Khaemhat.Application/Tables/ExchangeRates.cs b/src/Khaemhat.Application/Tables/ExchangeRates.cs new file mode 100644 index 0000000..7955f52 --- /dev/null +++ b/src/Khaemhat.Application/Tables/ExchangeRates.cs @@ -0,0 +1,212 @@ +using System.Globalization; +using Khaemhat.Application.Audit; +using Khaemhat.Application.Jobs; +using Khaemhat.Application.Querying; +using Khaemhat.Application.Security; +using Khaemhat.Core.Instance; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Companies; +using Khaemhat.Data.Querying; +using Khaemhat.Infrastructure.Http; + +namespace Khaemhat.Application.Tables; + +/// +/// The exchange rates of a company (SPEC §11.1): the ECB reference rates loaded by for the +/// currencies of the table, and rates typed by hand. The rate of a day is the last one on or before it. +/// +public sealed class ExchangeRateService +{ + /// The source of the ECB rates. + public const string EcbSource = "ECB"; + + /// The source of the rates typed by hand. + public const string ManualSource = "MANUAL"; + + /// Error: the rate is not positive. + public const string RateInvalid = "tables.exchange-rate.invalid"; + + /// The fields of the grid. + public static readonly ListFields Fields = new ListFields() + .Add("currency", x => x.CurrencyCode, searchable: true) + .Add("date", x => x.RateDate) + .Add("rate", x => x.Rate) + .Add("source", x => x.Source) + .OrderByDefault(new ListSort("date", Descending: true), new ListSort("currency")); + + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly AuditTrail _audit; + + /// Creates the service. + /// Opens the company databases. + /// Checks permissions. + /// Writes the history. + public ExchangeRateService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(audit); + _factory = factory; + _permissions = permissions; + _audit = audit; + } + + /// A page of rates. + /// Who reads. + /// The company. + /// The request. + /// Cancellation. + /// The page. + public async Task> ListAsync(Actor actor, string companyCode, ListQuery query, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(query); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.ReadPermission, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + var filtered = Fields.Apply(Query.For(), query); + var page = await repository.ListAsync(filtered, cancellationToken).ConfigureAwait(false); + return new ListPage(page.Items, page.TotalCount, new Dictionary()); + } + + /// The rate of a currency on a day: the last one on or before it; 1 for the euro. + /// The company. + /// The currency. + /// The day. + /// Cancellation. + /// The rate, or when none is known. + public async Task RateOnAsync(string companyCode, string currency, DateOnly date, CancellationToken cancellationToken = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(currency); + var code = currency.Trim().ToUpperInvariant(); + if (code == "EUR") + { + return new ExchangeRate { CurrencyCode = code, RateDate = date, Rate = 1m, Source = EcbSource }; + } + + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(CompanyCodes.Normalize(companyCode)), cancellationToken).ConfigureAwait(false); + return await uow.Repository() + .FindAsync(Query.For().Where(x => x.CurrencyCode == code && x.RateDate <= date).OrderByDescending(x => x.RateDate), cancellationToken) + .ConfigureAwait(false); + } + + /// Saves a rate typed by hand (replacing the one of the same day). + /// Who saves. + /// The company. + /// The currency. + /// The day. + /// Units of the currency for one euro. + /// Cancellation. + /// The rate. + /// The rate is not positive or the currency is not in the table. + public async Task SetManualAsync(Actor actor, string companyCode, string currency, DateOnly date, decimal rate, CancellationToken cancellationToken = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(currency); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.WritePermission, cancellationToken).ConfigureAwait(false); + var code = currency.Trim().ToUpperInvariant(); + if (rate <= 0) + { + throw new ValidationFailedException([nameof(ExchangeRate.Rate) + ":" + RateInvalid]); + } + + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + if (await uow.Repository().CountAsync(Query.For().Where(x => x.Code == code), cancellationToken).ConfigureAwait(false) == 0) + { + throw new ValidationFailedException([nameof(ExchangeRate.CurrencyCode) + ":" + TableCatalog.ReferenceMissing]); + } + + var saved = await UpsertAsync(uow, new ExchangeRate { CurrencyCode = code, RateDate = date, Rate = rate, Source = ManualSource }, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return saved; + } + + /// Stores ECB rates for the currencies of a company's table (manual rates of the same day are kept). + /// The company. + /// The ECB rates. + /// Cancellation. + /// How many rates were added or changed. + public async Task StoreEcbAsync(string companyCode, IReadOnlyList rates, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(rates); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(CompanyCodes.Normalize(companyCode)), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var currencies = (await uow.Repository().ListAsync(Query.For().Where(x => !x.Disabled), cancellationToken).ConfigureAwait(false)).Items + .Select(c => c.Code) + .ToHashSet(StringComparer.Ordinal); + var changed = 0; + foreach (var rate in rates.Where(r => currencies.Contains(r.Currency))) + { + var existing = await FindAsync(uow, rate.Currency, rate.Date, cancellationToken).ConfigureAwait(false); + if (existing is { Source: ManualSource } || existing?.Rate == rate.Rate) + { + continue; + } + + await UpsertAsync(uow, new ExchangeRate { CurrencyCode = rate.Currency, RateDate = rate.Date, Rate = rate.Rate, Source = EcbSource }, "system", cancellationToken) + .ConfigureAwait(false); + changed++; + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return changed; + } + + private static Task FindAsync(IUnitOfWork uow, string currency, DateOnly date, CancellationToken cancellationToken) => + uow.Repository().FindAsync(Query.For().Where(x => x.CurrencyCode == currency && x.RateDate == date), cancellationToken); + + private async Task UpsertAsync(IUnitOfWork uow, ExchangeRate rate, string userName, CancellationToken cancellationToken) + { + var repository = uow.Repository(); + var existing = await FindAsync(uow, rate.CurrencyCode, rate.RateDate, cancellationToken).ConfigureAwait(false); + if (existing is null) + { + rate.Id = await repository.InsertAsync(rate, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Insert, rate.Id, null, rate, userName, cancellationToken).ConfigureAwait(false); + return rate; + } + + var before = new ExchangeRate { Id = existing.Id, CurrencyCode = existing.CurrencyCode, RateDate = existing.RateDate, Rate = existing.Rate, Source = existing.Source }; + existing.Rate = rate.Rate; + existing.Source = rate.Source; + await repository.UpdateAsync(existing, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, existing.Id, before, existing, userName, cancellationToken).ConfigureAwait(false); + return existing; + } +} + +/// +/// 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. +/// 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"; + + /// + public string Type => JobType; + + /// + public async Task RunAsync(JobContext context, CancellationToken cancellationToken) + { + // The 90-day file also fills the days missed while the instance was stopped. + var downloaded = await client.GetAsync(last90Days: true, cancellationToken).ConfigureAwait(false); + var changed = 0; + foreach (var company in await companies.ListAsync(cancellationToken).ConfigureAwait(false)) + { + 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); + } + } + + var last = downloaded.Max(r => r.Date); + return string.Create(CultureInfo.InvariantCulture, $"Cambi BCE del {last:dd/MM/yyyy}: {changed} valori aggiornati."); + } +} diff --git a/src/Khaemhat.Application/Tables/FiscalYearService.cs b/src/Khaemhat.Application/Tables/FiscalYearService.cs new file mode 100644 index 0000000..30ba46f --- /dev/null +++ b/src/Khaemhat.Application/Tables/FiscalYearService.cs @@ -0,0 +1,321 @@ +using System.Globalization; +using Khaemhat.Application.Audit; +using Khaemhat.Application.Security; +using Khaemhat.Core.Caching; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Tables; + +/// A fiscal year with its months, as mockup 052 shows it. +/// The year. +/// The months, in order. +public sealed record FiscalYearView(FiscalYear Year, IReadOnlyList Periods); + +/// What a date may receive. +public enum PeriodUse +{ + /// A document or entry without VAT (warehouse, quotations, orders). + NoVat = 0, + + /// A document or entry with VAT: refused once the VAT of the period is settled. + Vat = 1, +} + +/// Why a date is refused (or ). +public enum PeriodState +{ + /// The date is in an open period. + Open = 0, + + /// No fiscal year contains the date. + NoYear = 1, + + /// The year is closed or being closed. + YearClosed = 2, + + /// The month is locked. + Locked = 3, + + /// The VAT of the month was settled (only for ). + Settled = 4, +} + +/// +/// Fiscal years and their months (SPEC §11.1, mockup 052): creation of the next year with its twelve months, lock and +/// unlock of months, and the check that a date can receive documents and entries (), used by +/// every service that writes dated records. Years and months are cached per company. +/// +public sealed class FiscalYearService +{ + /// Error: the date of the new year overlaps an existing year. + public const string Overlap = "fiscal.year.overlap"; + + /// Error: the year is closed: its months cannot change. + public const string YearClosedError = "fiscal.year.closed"; + + /// Error: the month cannot become open again because the VAT is settled (reopened with the settlement, M7). + public const string SettledError = "fiscal.period.settled"; + + /// The error code thrown by , followed by the . + public const string DateRefused = "fiscal.date."; + + private static readonly TimeSpan CacheTime = TimeSpan.FromHours(1); + + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly AuditTrail _audit; + private readonly ICacheProvider _cache; + + /// Creates the service. + /// Opens the company databases. + /// Checks permissions. + /// Writes the history. + /// The cache. + public FiscalYearService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, ICacheProvider cache) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(audit); + ArgumentNullException.ThrowIfNull(cache); + _factory = factory; + _permissions = permissions; + _audit = audit; + _cache = cache; + } + + /// The years, newest first, with their months. + /// Who reads. + /// The company. + /// Cancellation. + /// The years. + public async Task> ListAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.ReadPermission, cancellationToken).ConfigureAwait(false); + return [.. (await CalendarAsync(company, cancellationToken).ConfigureAwait(false)).OrderByDescending(y => y.Year.StartDate)]; + } + + /// + /// Creates a year with its months: after the last year, or the one containing when there are + /// none (starting in the month of the profile). + /// + /// Who creates. + /// The company. + /// A day of the first year, when the company has none. + /// Cancellation. + /// The new year. + public async Task CreateNextAsync(Actor actor, string companyCode, DateOnly day, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.WritePermission, cancellationToken).ConfigureAwait(false); + FiscalYearView created; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + created = await CreateAsync(uow, day, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + await InvalidateAsync(company, cancellationToken).ConfigureAwait(false); + return created; + } + + /// Locks or unlocks a month (unlocking a settled month is refused). + /// Who changes it. + /// The company. + /// The month. + /// Lock or unlock. + /// Cancellation. + /// The month. + /// The year is closed, or the month is settled. + public async Task SetLockedAsync(Actor actor, string companyCode, long periodId, bool locked, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.WritePermission, cancellationToken).ConfigureAwait(false); + FiscalPeriod period; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var periods = uow.Repository(); + period = await periods.GetAsync(periodId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TableService.NotFound); + var year = await uow.Repository().GetAsync(period.FiscalYearId, cancellationToken).ConfigureAwait(false) + ?? throw new KeyNotFoundException(TableService.NotFound); + if (year.Status != FiscalYearStatus.Open) + { + throw new ValidationFailedException([YearClosedError]); + } + + if (period.Status == FiscalPeriodStatus.Settled && !locked) + { + throw new ValidationFailedException([SettledError]); + } + + var target = locked ? FiscalPeriodStatus.Locked : FiscalPeriodStatus.Open; + if (period.Status != target) + { + var before = Copy(period); + period.Status = target; + await periods.UpdateAsync(period, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, period.Id, before, period, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + } + + await InvalidateAsync(company, cancellationToken).ConfigureAwait(false); + return period; + } + + /// Whether a date can receive a document or entry. + /// The company. + /// The date. + /// With or without VAT. + /// Cancellation. + /// The state of the date. + public async Task CheckAsync(string companyCode, DateOnly date, PeriodUse use, CancellationToken cancellationToken = default) + { + var calendar = await CalendarAsync(CompanyCodes.Normalize(companyCode), cancellationToken).ConfigureAwait(false); + return StateOf(calendar, date, use); + } + + /// Throws when a date cannot receive a document or entry. + /// The company. + /// The date. + /// With or without VAT. + /// Cancellation. + /// A task. + /// The date is refused: fiscal.date.locked and similar. + public async Task DemandOpenAsync(string companyCode, DateOnly date, PeriodUse use, CancellationToken cancellationToken = default) + { + var state = await CheckAsync(companyCode, date, use, cancellationToken).ConfigureAwait(false); + if (state != PeriodState.Open) + { + throw new ValidationFailedException([ErrorOf(state)]); + } + } + + /// The error code of a refused date, such as fiscal.date.locked. + /// The state. + /// The code. + public static string ErrorOf(PeriodState state) => state switch + { + PeriodState.NoYear => DateRefused + "no-year", + PeriodState.YearClosed => DateRefused + "year-closed", + PeriodState.Locked => DateRefused + "locked", + PeriodState.Settled => DateRefused + "settled", + _ => DateRefused + "open", + }; + + /// The state of a date in a calendar. + /// The years with their months. + /// The date. + /// With or without VAT. + /// The state. + public static PeriodState StateOf(IEnumerable calendar, DateOnly date, PeriodUse use) + { + ArgumentNullException.ThrowIfNull(calendar); + var year = calendar.FirstOrDefault(y => y.Year.StartDate <= date && date <= y.Year.EndDate); + if (year is null) + { + return PeriodState.NoYear; + } + + if (year.Year.Status != FiscalYearStatus.Open) + { + return PeriodState.YearClosed; + } + + var period = year.Periods.FirstOrDefault(p => p.StartDate <= date && date <= p.EndDate); + return period?.Status switch + { + FiscalPeriodStatus.Locked => PeriodState.Locked, + FiscalPeriodStatus.Settled when use == PeriodUse.Vat => PeriodState.Settled, + _ => PeriodState.Open, + }; + } + + /// + /// Creates a year with its months inside a unit of work (the seeder uses it for the current year): after the last + /// year, or the one containing when there are none. + /// + /// The company unit of work. + /// A day of the first year. + /// Who creates. + /// Cancellation. + /// The new year. + internal async Task CreateAsync(IUnitOfWork uow, DateOnly day, string userName, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(uow); + var years = uow.Repository(); + var last = await years.FindAsync(Query.For().OrderByDescending(x => x.StartDate), cancellationToken).ConfigureAwait(false); + DateOnly start; + if (last is not null) + { + start = last.EndDate.AddDays(1); + } + else + { + var profile = await CompanyProfileService.LoadAsync(uow, cancellationToken).ConfigureAwait(false); + var month = profile?.FiscalYearStartMonth ?? 1; + start = new DateOnly(day.Month >= month ? day.Year : day.Year - 1, month, 1); + } + + var end = start.AddYears(1).AddDays(-1); + if (await years.CountAsync(Query.For().Where(x => x.StartDate <= end && x.EndDate >= start), cancellationToken).ConfigureAwait(false) > 0) + { + throw new ValidationFailedException([Overlap]); + } + + var year = new FiscalYear + { + Code = start.Year == end.Year + ? start.Year.ToString(CultureInfo.InvariantCulture) + : string.Create(CultureInfo.InvariantCulture, $"{start.Year}/{end.Year % 100:00}"), + StartDate = start, + EndDate = end, + }; + year.Id = await years.InsertAsync(year, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Insert, year.Id, null, year, userName, cancellationToken).ConfigureAwait(false); + + var periods = new List(); + var repository = uow.Repository(); + for (var i = 0; i < 12; i++) + { + var first = start.AddMonths(i); + var period = new FiscalPeriod { FiscalYearId = year.Id, Number = i + 1, StartDate = first, EndDate = first.AddMonths(1).AddDays(-1) }; + period.Id = await repository.InsertAsync(period, cancellationToken).ConfigureAwait(false); + periods.Add(period); + } + + return new FiscalYearView(year, periods); + } + + /// Forgets the cached calendar of a company. + /// The company. + /// Cancellation. + /// A task. + public ValueTask InvalidateAsync(string companyCode, CancellationToken cancellationToken = default) => + _cache.PublishInvalidationAsync(CacheKeys.For(CompanyCodes.Normalize(companyCode), "fiscal", "calendar"), cancellationToken); + + private static FiscalPeriod Copy(FiscalPeriod period) => new() + { + Id = period.Id, + FiscalYearId = period.FiscalYearId, + Number = period.Number, + StartDate = period.StartDate, + EndDate = period.EndDate, + Status = period.Status, + RowVersion = period.RowVersion, + }; + + private async Task> CalendarAsync(string company, CancellationToken cancellationToken) => + await _cache.GetOrCreateAsync>( + CacheKeys.For(company, "fiscal", "calendar"), + async ct => + { + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), ct).ConfigureAwait(false); + var years = (await uow.Repository().ListAsync(Query.For().OrderBy(x => x.StartDate), ct).ConfigureAwait(false)).Items; + var periods = (await uow.Repository().ListAsync(Query.For().OrderBy(x => x.StartDate), ct).ConfigureAwait(false)).Items; + return [.. years.Select(y => new FiscalYearView(y, [.. periods.Where(p => p.FiscalYearId == y.Id)]))]; + }, + CacheTime, + cancellationToken).ConfigureAwait(false); +} diff --git a/src/Khaemhat.Application/Tables/PaymentTermService.cs b/src/Khaemhat.Application/Tables/PaymentTermService.cs new file mode 100644 index 0000000..8b38fba --- /dev/null +++ b/src/Khaemhat.Application/Tables/PaymentTermService.cs @@ -0,0 +1,159 @@ +using Khaemhat.Application.Audit; +using Khaemhat.Application.Security; +using Khaemhat.Core.Caching; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Tables; + +/// +/// The installments of a payment term (SPEC §11.1): days from the document date, end of month, fixed day and share of +/// the amount. They are saved all together, because only the whole set has to add up to 100%. +/// +public sealed class PaymentTermService +{ + /// The installments do not add up to 100%. + public const string PercentTotal = "tables.payment-term.percent-total"; + + /// A payment term needs at least one installment. + public const string LinesRequired = "tables.payment-term.lines-required"; + + /// The days are negative or beyond a year and a half. + public const string DaysRange = "tables.payment-term.days"; + + /// The fixed day is not a day of the month. + public const string FixedDayRange = "tables.payment-term.fixed-day"; + + /// The field the errors of the installments are reported on. + public const string LinesField = "Lines"; + + private const int MaxDays = 540; + + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly AuditTrail _audit; + private readonly ICacheProvider _cache; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The audit trail. + /// The cache of the tables. + public PaymentTermService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, ICacheProvider cache) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(audit); + ArgumentNullException.ThrowIfNull(cache); + _factory = factory; + _permissions = permissions; + _audit = audit; + _cache = cache; + } + + /// The installments of a payment term, in order. + /// Who reads. + /// The company. + /// The payment term. + /// Cancellation. + /// The installments. + public async Task> LinesAsync(Actor actor, string companyCode, long paymentTermId, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.ReadPermission, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await ReadAsync(uow, paymentTermId, cancellationToken).ConfigureAwait(false); + } + + /// Checks a set of installments. + /// The installments. + /// The errors, on . + public static IReadOnlyList Validate(IReadOnlyList lines) + { + ArgumentNullException.ThrowIfNull(lines); + var problems = new List(); + if (lines.Count == 0) + { + problems.Add(new(LinesField, LinesRequired)); + return problems; + } + + if (lines.Any(l => l.Days < 0 || l.Days > MaxDays)) + { + problems.Add(new(LinesField, DaysRange)); + } + + if (lines.Any(l => l.FixedDay is < 1 or > 31)) + { + problems.Add(new(LinesField, FixedDayRange)); + } + + if (lines.Any(l => l.Percent <= 0) || lines.Sum(l => l.Percent) != 100m) + { + problems.Add(new(LinesField, PercentTotal)); + } + + return problems; + } + + /// Replaces the installments of a payment term, numbering them 1, 2, 3 in the given order. + /// Who saves. + /// The company. + /// The payment term. + /// The installments. + /// Cancellation. + /// The saved installments. + /// The installments are not valid (Lines:code). + public async Task> SaveLinesAsync(Actor actor, string companyCode, long paymentTermId, IReadOnlyList lines, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(lines); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.WritePermission, cancellationToken).ConfigureAwait(false); + var problems = Validate(lines); + if (problems.Count > 0) + { + throw new ValidationFailedException([.. problems.Select(p => p.Field + ":" + p.Code)]); + } + + IReadOnlyList saved; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + _ = await uow.Repository().GetAsync(paymentTermId, cancellationToken).ConfigureAwait(false) + ?? throw new KeyNotFoundException(TableService.NotFound); + var repository = uow.Repository(); + foreach (var old in await ReadAsync(uow, paymentTermId, cancellationToken).ConfigureAwait(false)) + { + await repository.DeleteAsync(old.Id, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Delete, old.Id, old, null, actor.UserName, cancellationToken).ConfigureAwait(false); + } + + var number = 0; + foreach (var line in lines) + { + var row = new PaymentTermLine + { + PaymentTermId = paymentTermId, + Number = ++number, + Days = line.Days, + EndOfMonth = line.EndOfMonth, + FixedDay = line.FixedDay, + Percent = line.Percent, + }; + var id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Insert, id, null, row, actor.UserName, cancellationToken).ConfigureAwait(false); + } + + saved = await ReadAsync(uow, paymentTermId, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + await _cache.PublishInvalidationAsync(CacheKeys.Prefix(company, "tables"), cancellationToken).ConfigureAwait(false); + return saved; + } + + private static async Task> ReadAsync(IUnitOfWork uow, long paymentTermId, CancellationToken cancellationToken) => + (await uow.Repository() + .ListAsync(Query.For().Where(x => x.PaymentTermId == paymentTermId).OrderBy(x => x.Number), cancellationToken) + .ConfigureAwait(false)).Items; +} diff --git a/src/Khaemhat.Application/Tables/TableCatalog.cs b/src/Khaemhat.Application/Tables/TableCatalog.cs new file mode 100644 index 0000000..b50a8fe --- /dev/null +++ b/src/Khaemhat.Application/Tables/TableCatalog.cs @@ -0,0 +1,520 @@ +using System.Globalization; +using System.Text.RegularExpressions; +using Khaemhat.Core.Tables; +using Khaemhat.Core.Validation; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Application.Tables; + +/// +/// The company tables of SPEC §11.1 handled by , each with its rules. Keys are in English +/// (tax-codes); the interface gives them Italian addresses and names through the resources. +/// +public sealed partial class TableCatalog +{ + /// Error: a percentage outside 0-100. + public const string PercentRange = "tables.percent.range"; + + /// Error: the end of validity is before the start. + public const string ValidityOrder = "tables.validity.order"; + + /// Error: the code does not follow the pattern of the table. + public const string CodePattern = "tables.code.pattern"; + + /// Error: a value not in the fiscal pack's code list. + public const string NotInCodeList = "tables.code-list.unknown"; + + /// Warning: a value that the code list marks obsolete. + public const string ObsoleteInCodeList = "tables.code-list.obsolete"; + + /// Error: decimals outside the allowed range. + public const string DecimalsRange = "tables.decimals.range"; + + /// Error: the IBAN is not valid. + public const string IbanInvalid = "tables.iban.invalid"; + + /// Error: the BIC is not valid. + public const string BicInvalid = "tables.bic.invalid"; + + /// Error: the e-mail address is not valid. + public const string EmailInvalid = "tables.email.invalid"; + + /// Error: the VAT number is not valid. + public const string VatNumberInvalid = "tables.vat-number.invalid"; + + /// Error: the parent does not exist, is the row itself or is too deep. + public const string ParentInvalid = "tables.parent.invalid"; + + /// Error: a referenced row does not exist. + public const string ReferenceMissing = "tables.reference.missing"; + + /// Error: the discount formula cannot be read. + public const string FormulaInvalid = "tables.discount.formula"; + + /// Error: the numerator format has no {number}. + public const string FormatInvalid = "tables.numerator.format"; + + /// Error: the year is outside 2000-2100. + public const string YearRange = "tables.year.range"; + + /// Error: the last number is negative. + public const string NumberRange = "tables.number.range"; + + /// Error: a transfer reason must not change quantities by itself. + public const string TransferEffect = "tables.inventory-reason.transfer"; + + /// Error: another price list is already the base one. + public const string BaseDuplicate = "tables.price-list.base-duplicate"; + + /// The maximum depth of item categories. + public const int MaxCategoryLevel = 3; + + private readonly Dictionary _byType = []; + private readonly Dictionary _byKey = new(StringComparer.Ordinal); + + /// Creates the catalog. + public TableCatalog() + { + Add(new TableDefinition("countries", "countries") { CodeLength = 2 } + .Field("eu", x => x.EuMember) + .Rule((x, c) => Pattern(x.Code, TwoLetters(), c)) + .Rule((x, c) => + { + if (x.VatPrefix is { Length: > 0 } && !TwoLetters().IsMatch(x.VatPrefix)) + { + c.Error(nameof(Country.VatPrefix), CodePattern); + } + })); + Add(new TableDefinition("provinces", "provinces") { CodeLength = 2 } + .Field("region", x => x.Region, searchable: true) + .Rule((x, c) => Pattern(x.Code, TwoLetters(), c))); + Add(new TableDefinition("municipalities", "municipalities") { CodeLength = 4 } + .Field("province", x => x.ProvinceCode, searchable: true) + .Field("postal-codes", x => x.PostalCodes, searchable: true) + .Rule((x, c) => Pattern(x.Code, CadastralCode(), c)) + .Rule((x, c) => + { + x.ProvinceCode = x.ProvinceCode.Trim().ToUpperInvariant(); + if (!TwoLetters().IsMatch(x.ProvinceCode)) + { + c.Error(nameof(Municipality.ProvinceCode), CodePattern); + } + })); + Add(new TableDefinition("currencies", "currencies") { CodeLength = 3 } + .Rule((x, c) => Pattern(x.Code, ThreeLetters(), c)) + .Rule((x, c) => Decimals(x.Decimals, 0, 4, nameof(Currency.Decimals), c))); + Add(new TableDefinition("units", "units_of_measure") + .Rule((x, c) => Decimals(x.Decimals, 0, 6, nameof(UnitOfMeasure.Decimals), c))); + Add(new TableDefinition("tax-codes", "tax_codes") + { + Complete = (x, pack) => + { + x.Nature = string.IsNullOrWhiteSpace(x.Nature) ? null : x.Nature.Trim().ToUpperInvariant(); + x.Kind = pack.TaxCodes.KindOf(x.Rate, x.Nature); + }, + } + .Field("rate", x => x.Rate) + .Field("nature", x => x.Nature, searchable: true) + .Field("kind", x => x.Kind) + .Rule((x, c) => + { + var definition = new TaxCodeDefinition(x.Code, x.Description, x.Rate, x.Nature, x.Exigibility, x.NonDeductiblePercent, x.LegalReference); + foreach (var problem in c.Pack.TaxCodes.Validate(definition)) + { + if (problem.Severity == FiscalProblemSeverity.Error) + { + c.Error(problem.Field, problem.Code); + } + else + { + c.Warning(problem.Field, problem.Code); + } + } + + Validity(x.ValidFrom, x.ValidTo, nameof(TaxCode.ValidTo), c); + })); + Add(new TableDefinition("payment-methods", "payment_methods") + .Field("einvoice", x => x.EInvoiceCode) + .Rule((x, c) => InCodeList(x.EInvoiceCode, c.Pack.GetFeature()?.PaymentMethods, nameof(PaymentMethod.EInvoiceCode), c))); + Add(new TableDefinition("payment-terms", "payment_terms") + .Field("condition", x => x.Condition) + .Rule((x, c) => InCodeList(x.Condition, c.Pack.GetFeature()?.PaymentConditions, nameof(PaymentTerm.Condition), c)) + .Rule(async (x, c, ct) => + { + if (x.PaymentMethodId is { } id && await c.GetAsync(id, ct).ConfigureAwait(false) is null) + { + c.Error(nameof(PaymentTerm.PaymentMethodId), ReferenceMissing); + } + })); + Add(new TableDefinition("bank-accounts", "bank_accounts") { SingleDefault = x => x.IsDefault } + .Field("iban", x => x.Iban, searchable: true) + .Field("default", x => x.IsDefault) + .Rule((x, c) => + { + if (!string.IsNullOrWhiteSpace(x.Iban)) + { + x.Iban = IbanValidator.Normalize(x.Iban); + if (!IbanValidator.IsValid(x.Iban)) + { + c.Error(nameof(BankAccount.Iban), IbanInvalid); + } + } + else + { + x.Iban = null; + } + + if (!string.IsNullOrWhiteSpace(x.Bic)) + { + x.Bic = x.Bic.Trim().ToUpperInvariant(); + if (!Bic().IsMatch(x.Bic)) + { + c.Error(nameof(BankAccount.Bic), BicInvalid); + } + } + })); + Add(new TableDefinition("salespeople", "salespeople") + .Field("commission", x => x.CommissionPercent) + .Rule((x, c) => + { + Percent(x.CommissionPercent, nameof(Salesperson.CommissionPercent), c); + Email(x.Email, nameof(Salesperson.Email), c); + })); + Add(new TableDefinition("carriers", "carriers") + .Field("vat-number", x => x.VatNumber, searchable: true) + .Rule((x, c) => + { + Email(x.Email, nameof(Carrier.Email), c); + if (!string.IsNullOrWhiteSpace(x.VatNumber) && c.Pack.GetFeature() is { } rules) + { + x.VatNumber = rules.NormalizeVatNumber(x.VatNumber); + if (!rules.IsValidVatNumber(x.VatNumber)) + { + c.Error(nameof(Carrier.VatNumber), VatNumberInvalid); + } + } + })); + Add(new TableDefinition("shipping-terms", "shipping_terms")); + Add(new TableDefinition("transport-means", "transport_means")); + Add(new TableDefinition("goods-appearances", "goods_appearances")); + Add(new TableDefinition("delivery-terms", "delivery_terms")); + Add(new TableDefinition("transport-reasons", "transport_reasons")); + Add(new TableDefinition("inventory-reasons", "inventory_reasons") + .Field("effect", x => x.Effect) + .Rule((x, c) => + { + if (x.IsTransfer && x.Effect != StockEffect.None) + { + c.Error(nameof(InventoryReason.Effect), TransferEffect); + } + })); + Add(new TableDefinition("warehouses", "warehouses") { SingleDefault = x => x.IsDefault } + .Field("default", x => x.IsDefault)); + Add(new TableDefinition("item-categories", "item_categories") { CodeLength = 20 } + .Field("level", x => x.Level) + .Rule(async (x, c, ct) => + { + x.Level = 1; + if (x.ParentId is not { } parentId) + { + return; + } + + var parent = parentId == x.Id ? null : await c.GetAsync(parentId, ct).ConfigureAwait(false); + if (parent is null || parent.Level >= MaxCategoryLevel) + { + c.Error(nameof(ItemCategory.ParentId), ParentInvalid); + return; + } + + x.Level = parent.Level + 1; + })); + Add(new TableDefinition("party-categories", "party_categories")); + Add(new TableDefinition("price-lists", "price_lists") + .Field("currency", x => x.CurrencyCode) + .Rule(async (x, c, ct) => + { + x.CurrencyCode = x.CurrencyCode.Trim().ToUpperInvariant(); + if (!ThreeLetters().IsMatch(x.CurrencyCode)) + { + c.Error(nameof(PriceList.CurrencyCode), CodePattern); + } + + Validity(x.ValidFrom, x.ValidTo, nameof(PriceList.ValidTo), c); + if (x.RoundingStep < 0) + { + c.Error(nameof(PriceList.RoundingStep), NumberRange); + } + + if (x.BasePriceListId is { } baseId && (baseId == x.Id || await c.GetAsync(baseId, ct).ConfigureAwait(false) is null)) + { + c.Error(nameof(PriceList.BasePriceListId), ParentInvalid); + } + + var id = x.Id; + if (x.IsBase && await c.CountAsync(p => p.IsBase && p.Id != id, ct).ConfigureAwait(false) > 0) + { + c.Error(nameof(PriceList.IsBase), BaseDuplicate); + } + })); + Add(new TableDefinition("discount-policies", "discount_policies") + .Field("formula", x => x.Formula) + .Rule((x, c) => + { + if (DiscountFormula.TryParse(x.Formula, out var steps)) + { + x.Formula = DiscountFormula.Format(steps); + } + else + { + c.Error(nameof(DiscountPolicy.Formula), FormulaInvalid); + } + })); + Add(new TableDefinition("numerators", "document_numerators") { SameKey = row => x => x.Year == row.Year } + .Field("year", x => x.Year) + .Field("kind", x => x.Kind) + .Field("section", x => x.Section) + .Field("last", x => x.LastNumber) + .Rule((x, c) => + { + if (x.Year is < 2000 or > 2100) + { + c.Error(nameof(DocumentNumerator.Year), YearRange); + } + + if (x.LastNumber < 0) + { + c.Error(nameof(DocumentNumerator.LastNumber), NumberRange); + } + + if (!DocumentNumberFormat.IsValid(x.Format)) + { + c.Error(nameof(DocumentNumerator.Format), FormatInvalid); + } + + // Invoices, credit notes and final entries are numbered without gaps (SPEC §11.1). + if (x.Kind is NumeratorKind.SalesInvoice or NumeratorKind.Journal) + { + x.GapsAllowed = false; + } + })); + Add(new TableDefinition("document-types", "document_types") + .Field("kind", x => x.Kind) + .Field("einvoice", x => x.EInvoiceType) + .Rule(async (x, c, ct) => + { + if (!string.IsNullOrWhiteSpace(x.EInvoiceType)) + { + x.EInvoiceType = x.EInvoiceType.Trim().ToUpperInvariant(); + InCodeList(x.EInvoiceType, c.Pack.GetFeature()?.DocumentTypes, nameof(DocumentType.EInvoiceType), c); + } + else + { + x.EInvoiceType = null; + } + + if (x.NumeratorId is { } numeratorId && await c.GetAsync(numeratorId, ct).ConfigureAwait(false) is null) + { + c.Error(nameof(DocumentType.NumeratorId), ReferenceMissing); + } + + if (x.InventoryReasonId is { } reasonId && await c.GetAsync(reasonId, ct).ConfigureAwait(false) is null) + { + c.Error(nameof(DocumentType.InventoryReasonId), ReferenceMissing); + } + })); + Add(new TableDefinition("cost-centers", "cost_centers") { CodeLength = 20 } + .Rule(async (x, c, ct) => + { + if (x.ParentId is { } parentId && (parentId == x.Id || await c.GetAsync(parentId, ct).ConfigureAwait(false) is null)) + { + c.Error(nameof(CostCenter.ParentId), ParentInvalid); + } + })); + Add(new TableDefinition("jobs", "jobs") { CodeLength = 20 } + .Field("status", x => x.Status) + .Rule((x, c) => Validity(x.StartDate, x.EndDate, nameof(Job.EndDate), c))); + } + + /// Every table, in the order of SPEC §11.1. + public IEnumerable All => _byKey.Values; + + /// The definition of an entity. + /// The entity. + /// The definition. + public TableDefinition Get() + where T : CodedEntity, new() => + (TableDefinition)(_byType.GetValueOrDefault(typeof(T)) ?? throw new InvalidOperationException($"{typeof(T).Name} is not a company table.")); + + /// A definition by key. + /// The key, such as tax-codes. + /// The definition, or . + public TableDefinition? Find(string key) => _byKey.GetValueOrDefault(key); + + private static void Pattern(string code, Regex pattern, TableRuleContext context) + { + if (code.Length > 0 && !pattern.IsMatch(code)) + { + context.Error(nameof(CodedEntity.Code), CodePattern); + } + } + + private static void Decimals(int value, int min, int max, string field, TableRuleContext context) + { + if (value < min || value > max) + { + context.Error(field, DecimalsRange); + } + } + + private static void Percent(decimal value, string field, TableRuleContext context) + { + if (value is < 0 or > 100) + { + context.Error(field, PercentRange); + } + } + + private static void Email(string? value, string field, TableRuleContext context) + { + if (!string.IsNullOrWhiteSpace(value) && !EmailValidator.IsValid(value)) + { + context.Error(field, EmailInvalid); + } + } + + private static void Validity(DateOnly? from, DateOnly? to, string field, TableRuleContext context) + { + if (from is { } start && to is { } end && end < start) + { + context.Error(field, ValidityOrder); + } + } + + private static void InCodeList(string? value, CodeList? list, string field, TableRuleContext context) + { + if (list is null || string.IsNullOrEmpty(value)) + { + return; + } + + var entry = list.Find(value); + if (entry is null) + { + context.Error(field, NotInCodeList); + } + else if (entry.Obsolete) + { + context.Warning(field, ObsoleteInCodeList); + } + } + + [GeneratedRegex("^[A-Z]{2}$", RegexOptions.CultureInvariant)] + private static partial Regex TwoLetters(); + + [GeneratedRegex("^[A-Z]{3}$", RegexOptions.CultureInvariant)] + private static partial Regex ThreeLetters(); + + [GeneratedRegex("^[A-Z][0-9]{3}$", RegexOptions.CultureInvariant)] + private static partial Regex CadastralCode(); + + [GeneratedRegex("^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$", RegexOptions.CultureInvariant)] + private static partial Regex Bic(); + + private void Add(TableDefinition definition) + where T : CodedEntity, new() + { + _byType.Add(typeof(T), definition); + _byKey.Add(definition.Key, definition); + } +} + +/// A chain of discounts such as 10+5: each step applies to what the previous left. +public static class DiscountFormula +{ + /// Reads a formula: percentages 0-100 separated by +, decimal comma or point. + /// The formula. + /// The percentages. + /// Whether it could be read. + public static bool TryParse(string? formula, out IReadOnlyList steps) + { + steps = []; + if (string.IsNullOrWhiteSpace(formula)) + { + return false; + } + + var result = new List(); + foreach (var part in formula.Split('+', StringSplitOptions.TrimEntries)) + { + if (!decimal.TryParse(part.Replace(',', '.'), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var step) || step > 100) + { + return false; + } + + result.Add(step); + } + + steps = result; + return true; + } + + /// Writes a formula in the Italian form, such as 10+5,5. + /// The percentages. + /// The formula. + public static string Format(IEnumerable steps) => + string.Join('+', steps.Select(s => s.ToString("0.##", CultureInfo.GetCultureInfo("it-IT")))); + + /// The single discount equal to the chain: 10+5 is 14.5%. + /// The percentages. + /// The equivalent percentage. + public static decimal Equivalent(IEnumerable steps) => + 100m - (steps.Aggregate(1m, (left, step) => left * (1 - (step / 100m))) * 100m); +} + +/// The format of document numbers: {prefix}, {year}, {section} and {number} (with :D6 and similar). +public static partial class DocumentNumberFormat +{ + /// Whether a format has the number and only known placeholders. + /// The format. + /// Whether it is valid. + public static bool IsValid(string? format) => + !string.IsNullOrWhiteSpace(format) && format.Length <= 60 && NumberPlaceholder().IsMatch(format) && + Placeholder().Matches(format).All(m => Known().IsMatch(m.Value)); + + /// Writes a number with a format. + /// The format. + /// The number. + /// The year. + /// The prefix. + /// The section. + /// The document number, such as FV/2026/000123. + public static string Apply(string format, long number, int year, string? prefix, string? section) + { + ArgumentNullException.ThrowIfNull(format); + return Placeholder().Replace(format, m => + { + var token = m.Value[1..^1]; + var colon = token.IndexOf(':', StringComparison.Ordinal); + var name = colon < 0 ? token : token[..colon]; + var spec = colon < 0 ? null : token[(colon + 1)..]; + return name switch + { + "number" => number.ToString(spec, CultureInfo.InvariantCulture), + "year" => year.ToString(CultureInfo.InvariantCulture), + "prefix" => prefix ?? string.Empty, + "section" => section ?? string.Empty, + _ => m.Value, + }; + }); + } + + [GeneratedRegex(@"\{number(:D[1-9])?\}", RegexOptions.CultureInvariant)] + private static partial Regex NumberPlaceholder(); + + [GeneratedRegex(@"\{[^}]*\}", RegexOptions.CultureInvariant)] + private static partial Regex Placeholder(); + + [GeneratedRegex(@"^\{(number(:D[1-9])?|year|prefix|section)\}$", RegexOptions.CultureInvariant)] + private static partial Regex Known(); +} diff --git a/src/Khaemhat.Application/Tables/TableDefinition.cs b/src/Khaemhat.Application/Tables/TableDefinition.cs new file mode 100644 index 0000000..6e0fdb5 --- /dev/null +++ b/src/Khaemhat.Application/Tables/TableDefinition.cs @@ -0,0 +1,214 @@ +using System.Globalization; +using System.Linq.Expressions; +using System.Reflection; +using System.Text.RegularExpressions; +using Khaemhat.Application.Querying; +using Khaemhat.Core.Entities; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Application.Tables; + +/// A problem found on a field of a table row: an error blocks the save, a warning does not. +/// The property, such as Code. +/// The stable code, translated by the interface (tables.code.required). +/// Whether it is only a warning. +public sealed record TableProblem(string Field, string Code, bool IsWarning = false); + +/// What the rules of a table can use: the fiscal pack of the company and the other rows. +public sealed class TableRuleContext +{ + private readonly IUnitOfWork _unitOfWork; + private readonly List _problems = []; + + internal TableRuleContext(IUnitOfWork unitOfWork, IFiscalPack pack) + { + _unitOfWork = unitOfWork; + Pack = pack; + } + + /// The fiscal pack of the company's country. + public IFiscalPack Pack { get; } + + /// The problems found so far. + public IReadOnlyList Problems => _problems; + + /// Adds an error. + /// The property. + /// The code. + public void Error(string field, string code) => _problems.Add(new TableProblem(field, code)); + + /// Adds a warning. + /// The property. + /// The code. + public void Warning(string field, string code) => _problems.Add(new TableProblem(field, code, IsWarning: true)); + + /// Reads another row by id. + /// The entity. + /// The id. + /// Cancellation. + /// The row, or . + public Task GetAsync(long id, CancellationToken cancellationToken) + where TOther : class, IEntity, new() => + _unitOfWork.Repository().GetAsync(id, cancellationToken); + + /// Counts the rows of another table that match. + /// The other table. + /// The condition. + /// Cancellation. + /// How many rows match. + public Task CountAsync(System.Linq.Expressions.Expression> where, CancellationToken cancellationToken) + where TOther : class, IEntity, new() => + _unitOfWork.Repository().CountAsync(Query.For().Where(where), cancellationToken); + + /// Whether a coded row with a code exists. + /// The entity. + /// The code. + /// Cancellation. + /// Whether it exists. + public async Task ExistsAsync(string? code, CancellationToken cancellationToken) + where TOther : CodedEntity, new() => + !string.IsNullOrEmpty(code) && + await _unitOfWork.Repository().CountAsync(Query.For().Where(x => x.Code == code), cancellationToken).ConfigureAwait(false) > 0; +} + +/// A company table that the generic maschera and service handle (SPEC §11.1, mockup 076). +public abstract class TableDefinition +{ + /// Creates the definition. + /// The key used in addresses and resources, such as tax-codes. + /// The database table. + protected TableDefinition(string key, string table) + { + ArgumentException.ThrowIfNullOrWhiteSpace(key); + ArgumentException.ThrowIfNullOrWhiteSpace(table); + Key = key; + Table = table; + } + + /// The key, such as tax-codes. + public string Key { get; } + + /// The database table, such as tax_codes. + public string Table { get; } + + /// The entity type. + public abstract Type EntityType { get; } + + /// The maximum length of the code. + public int CodeLength { get; init; } = 10; + + /// Whether codes are kept as typed instead of upper case (municipality names are not codes). + public bool KeepCodeCase { get; init; } + + /// The CSV columns: header and property. + public abstract IReadOnlyList CsvColumns { get; } +} + +/// A CSV column of a table: the snake_case header and the property. +/// The header. +/// The property. +public sealed record TableCsvColumn(string Header, PropertyInfo Property); + +/// A company table of . +/// The entity. +public sealed partial class TableDefinition : TableDefinition + where T : CodedEntity, new() +{ + private static readonly HashSet NotInCsv = new(StringComparer.Ordinal) + { + nameof(Entity.Id), nameof(IAuditable.CreatedAt), nameof(IAuditable.CreatedBy), nameof(IAuditable.UpdatedAt), nameof(IAuditable.UpdatedBy), + nameof(IAuditable.RowVersion), nameof(CodedEntity.IsDemo), + }; + + private readonly List> _rules = []; + private IReadOnlyList? _csv; + + /// Creates the definition with the list fields code, description, disabled. + /// The key, such as tax-codes. + /// The database table. + public TableDefinition(string key, string table) + : base(key, table) + { + Fields = new ListFields() + .Add("code", x => x.Code, searchable: true) + .Add("description", x => x.Description, searchable: true) + .Add("disabled", x => x.Disabled) + .OrderByDefault(new ListSort("code")); + } + + /// + public override Type EntityType => typeof(T); + + /// The fields of the grid: filters, search and ordering. + public ListFields Fields { get; } + + /// The rules run before every save, after the common ones (code and description). + public IReadOnlyList> Rules => _rules; + + /// The flag that only one row may have (the default bank account, the default warehouse). + public Expression>? SingleDefault { get; init; } + + /// The other fields that, with the code, make a row unique (the year of a numerator). + public Func>>? SameKey { get; init; } + + /// Called before the rules, to fill derived fields (the kind of a VAT code). + public Action? Complete { get; init; } + + /// + public override IReadOnlyList CsvColumns => _csv ??= + [ + .. typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance) + .Where(p => p.CanWrite && !NotInCsv.Contains(p.Name) && !p.Name.EndsWith("Id", StringComparison.Ordinal)) + .OrderBy(p => p.Name switch { nameof(CodedEntity.Code) => 0, nameof(CodedEntity.Description) => 1, _ => 2 }) + .ThenBy(p => p.MetadataToken) + .Select(p => new TableCsvColumn(SnakeCase(p.Name), p)), + ]; + + /// Adds a rule. + /// The rule. + /// This, to chain. + public TableDefinition Rule(Func rule) + { + ArgumentNullException.ThrowIfNull(rule); + _rules.Add(rule); + return this; + } + + /// Adds a rule that needs no other rows. + /// The rule. + /// This, to chain. + public TableDefinition Rule(Action rule) + { + ArgumentNullException.ThrowIfNull(rule); + _rules.Add((row, context, _) => + { + rule(row, context); + return Task.CompletedTask; + }); + return this; + } + + /// Adds a grid field. + /// The type. + /// The id. + /// The property. + /// Whether the search box looks in it. + /// This, to chain. + public TableDefinition Field(string id, Expression> selector, bool searchable = false) + { + Fields.Add(id, selector, searchable); + return this; + } + + internal static string SnakeCase(string name) => + LowerUpper().Replace(UpperUpperLower().Replace(name, "$1_$2"), "$1_$2").ToLower(CultureInfo.InvariantCulture); + + [GeneratedRegex("([A-Z])([A-Z][a-z])")] + private static partial Regex UpperUpperLower(); + + [GeneratedRegex("([a-z0-9])([A-Z])")] + private static partial Regex LowerUpper(); +} diff --git a/src/Khaemhat.Application/Tables/TableService.cs b/src/Khaemhat.Application/Tables/TableService.cs new file mode 100644 index 0000000..5d797d5 --- /dev/null +++ b/src/Khaemhat.Application/Tables/TableService.cs @@ -0,0 +1,622 @@ +using System.Data.Common; +using System.Globalization; +using System.Reflection; +using Khaemhat.Application.Audit; +using Khaemhat.Application.Querying; +using Khaemhat.Application.Security; +using Khaemhat.Core.Caching; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; +using Khaemhat.Infrastructure.Files; + +namespace Khaemhat.Application.Tables; + +/// What a delete did. +public enum TableDeleteOutcome +{ + /// The row is gone. + Deleted = 0, + + /// The row is used elsewhere: it was disabled instead. + Disabled = 1, +} + +/// A row of a CSV import that could not be read or saved. +/// The row number in the file, from 2 (1 is the header). +/// The column, or for the whole row. +/// The problem. +public sealed record TableImportError(int Row, string? Field, string Code); + +/// The result of a CSV import: nothing is saved when there are errors. +/// New rows. +/// Rows changed (found by code). +/// The errors. +public sealed record TableImportResult(int Inserted, int Updated, IReadOnlyList Errors) +{ + /// Whether the import was saved. + public bool Succeeded => Errors.Count == 0; +} + +/// +/// The company tables of SPEC §11.1 through one service (wiki Tabelle azienda): list, read, save with the common +/// rules (code and description required, unique code) and those of the table, delete (or disable when the row is used), +/// CSV export and import. The rows of each table are cached per company and invalidated on every change, also on the +/// other instances when Redis is configured. +/// +/// Reading needs company.settings.read, changing company.settings.write. +public sealed class TableService +{ + /// Permission to see the tables. + public const string ReadPermission = "company.settings.read"; + + /// Permission to change the tables. + public const string WritePermission = "company.settings.write"; + + /// Error: the code is missing. + public const string CodeRequired = "tables.code.required"; + + /// Error: the code is too long. + public const string CodeTooLong = "tables.code.too-long"; + + /// Error: another row has the code. + public const string CodeDuplicate = "tables.code.duplicate"; + + /// Error: the description is missing. + public const string DescriptionRequired = "tables.description.required"; + + /// Error: the row changed or was deleted meanwhile. + public const string NotFound = "tables.not-found"; + + /// Import error: the header has no code column. + public const string CsvNoCode = "tables.csv.no-code"; + + /// Import error: a value cannot be read. + public const string CsvBadValue = "tables.csv.bad-value"; + + /// Import error: unknown column (a warning in the result: the column is ignored). + public const string CsvUnknownColumn = "tables.csv.unknown-column"; + + private static readonly TimeSpan CacheTime = TimeSpan.FromHours(1); + private static readonly NullabilityInfoContext Nullability = new(); + + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly AuditTrail _audit; + private readonly ICacheProvider _cache; + private readonly CompanyFiscalContext _fiscal; + private readonly TableCatalog _catalog; + + /// Creates the service. + /// Opens the company databases. + /// Checks permissions. + /// Writes the history. + /// The cache of the rows. + /// The fiscal pack of each company. + /// The tables. + public TableService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, ICacheProvider cache, CompanyFiscalContext fiscal, TableCatalog catalog) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(audit); + ArgumentNullException.ThrowIfNull(cache); + ArgumentNullException.ThrowIfNull(fiscal); + ArgumentNullException.ThrowIfNull(catalog); + _factory = factory; + _permissions = permissions; + _audit = audit; + _cache = cache; + _fiscal = fiscal; + _catalog = catalog; + } + + /// The tables. + public TableCatalog Catalog => _catalog; + + /// Every row of a table, from the cache (disabled ones included), ordered by code. + /// The entity. + /// Who reads. + /// The company. + /// Cancellation. + /// The rows. + public async Task> AllAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + where T : CodedEntity, new() + { + var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + return await RowsAsync(company, _catalog.Get(), cancellationToken).ConfigureAwait(false); + } + + /// The rows still in use (not disabled), for the choices on other records. + /// The entity. + /// Who reads. + /// The company. + /// Cancellation. + /// The rows. + public async Task> ActiveAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + where T : CodedEntity, new() => + [.. (await AllAsync(actor, companyCode, cancellationToken).ConfigureAwait(false)).Where(r => !r.Disabled)]; + + /// A page of a table for the grid. + /// The entity. + /// Who reads. + /// The company. + /// Search, filters, ordering and page. + /// Cancellation. + /// The page. + public async Task> ListAsync(Actor actor, string companyCode, ListQuery query, CancellationToken cancellationToken = default) + where T : CodedEntity, new() + { + ArgumentNullException.ThrowIfNull(query); + var rows = await AllAsync(actor, companyCode, cancellationToken).ConfigureAwait(false); + return _catalog.Get().Fields.Apply(rows, query); + } + + /// One row, read from the database. + /// The entity. + /// Who reads. + /// The company. + /// The id. + /// Cancellation. + /// The row, or . + public async Task GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + where T : CodedEntity, new() + { + var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false); + } + + /// Checks a row without saving it: the messages next to the fields. + /// The entity. + /// Who checks. + /// The company. + /// The row (normalized in place: trimmed code in upper case, derived fields). + /// Cancellation. + /// Errors and warnings. + public async Task> ValidateAsync(Actor actor, string companyCode, T row, CancellationToken cancellationToken = default) + where T : CodedEntity, new() + { + ArgumentNullException.ThrowIfNull(row); + var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await CheckAsync(uow, pack, _catalog.Get(), row, cancellationToken).ConfigureAwait(false); + } + + /// Saves a row: inserts it when is 0, updates it otherwise. + /// The entity. + /// Who saves. + /// The company. + /// The row. + /// Cancellation. + /// The saved row, with its id and new row version. + /// A rule failed; has Field:code. + /// Someone else changed the row meanwhile. + public async Task SaveAsync(Actor actor, string companyCode, T row, CancellationToken cancellationToken = default) + where T : CodedEntity, new() + { + ArgumentNullException.ThrowIfNull(row); + var company = await DemandAsync(actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false); + var definition = _catalog.Get(); + var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false); + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + Throw(await CheckAsync(uow, pack, definition, row, cancellationToken).ConfigureAwait(false)); + await WriteAsync(uow, definition, row, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + await InvalidateAsync(company, definition, cancellationToken).ConfigureAwait(false); + return row; + } + + /// Deletes a row, or disables it when other records use it. + /// The entity. + /// Who deletes. + /// The company. + /// The row. + /// Cancellation. + /// What happened. + /// No such row. + public async Task DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + where T : CodedEntity, new() + { + var company = await DemandAsync(actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false); + var definition = _catalog.Get(); + var outcome = TableDeleteOutcome.Deleted; + try + { + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + var before = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound); + await repository.DeleteAsync(id, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Delete, id, before, null, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + catch (DbException) + { + // A foreign key refused the delete: the row is used, so it is only hidden from new choices. + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + var row = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound); + if (!row.Disabled) + { + var before = Clone(row); + row.Disabled = true; + await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, id, before, row, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + outcome = TableDeleteOutcome.Disabled; + } + + await InvalidateAsync(company, definition, cancellationToken).ConfigureAwait(false); + return outcome; + } + + /// Writes a table as CSV (Italian format: ;, decimal comma, byte order mark). + /// The entity. + /// Who exports. + /// The company. + /// The stream; left open. + /// Cancellation. + /// The rows written. + public async Task ExportCsvAsync(Actor actor, string companyCode, Stream output, CancellationToken cancellationToken = default) + where T : CodedEntity, new() + { + ArgumentNullException.ThrowIfNull(output); + var rows = await AllAsync(actor, companyCode, cancellationToken).ConfigureAwait(false); + var columns = _catalog.Get().CsvColumns; + await using var writer = new CsvWriter(output, CsvOptions.Italian, leaveOpen: true); + await writer.WriteRowAsync(columns.Select(c => (object?)c.Header), cancellationToken).ConfigureAwait(false); + foreach (var row in rows) + { + await writer.WriteRowAsync(columns.Select(c => Export(c.Property.GetValue(row))), cancellationToken).ConfigureAwait(false); + } + + return rows.Count; + } + + /// + /// Imports a CSV with the columns of the export (any order, missing columns keep their value): rows are matched by + /// code, new codes are inserted. Nothing is saved unless every row passes the rules. + /// + /// The entity. + /// Who imports. + /// The company. + /// The CSV. + /// Cancellation. + /// Counts and errors. + public async Task ImportCsvAsync(Actor actor, string companyCode, Stream content, CancellationToken cancellationToken = default) + where T : CodedEntity, new() + { + ArgumentNullException.ThrowIfNull(content); + var company = await DemandAsync(actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false); + var definition = _catalog.Get(); + var lines = await CsvReader.ReadAsync(content, null, cancellationToken).ConfigureAwait(false); + if (lines.Count == 0) + { + return new TableImportResult(0, 0, [new TableImportError(1, null, CsvNoCode)]); + } + + var byHeader = definition.CsvColumns.ToDictionary(c => c.Header, StringComparer.OrdinalIgnoreCase); + var header = lines[0].Select(h => byHeader.GetValueOrDefault(h.Trim())).ToArray(); + if (!header.Any(c => c?.Property.Name == nameof(CodedEntity.Code))) + { + return new TableImportResult(0, 0, [new TableImportError(1, null, CsvNoCode)]); + } + + var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false); + var errors = new List(); + var inserted = 0; + var updated = 0; + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var existing = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items + .GroupBy(r => r.Code, StringComparer.OrdinalIgnoreCase) + .ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + var pending = new List(); + + for (var i = 1; i < lines.Count; i++) + { + var line = lines[i]; + var rowNumber = i + 1; + var codeIndex = Array.FindIndex(header, c => c?.Property.Name == nameof(CodedEntity.Code)); + var code = codeIndex < line.Count ? line[codeIndex].Trim() : string.Empty; + var row = existing.TryGetValue(code, out var found) ? found : new T(); + var rowErrors = false; + for (var c = 0; c < header.Length && c < line.Count; c++) + { + if (header[c] is not { } column) + { + continue; + } + + if (TryParse(line[c], column.Property, out var value)) + { + column.Property.SetValue(row, value); + } + else + { + errors.Add(new TableImportError(rowNumber, column.Header, CsvBadValue)); + rowErrors = true; + } + } + + if (!seen.Add(row.Code.Trim())) + { + errors.Add(new TableImportError(rowNumber, "code", CodeDuplicate)); + continue; + } + + if (rowErrors) + { + continue; + } + + var problems = await CheckAsync(uow, pack, definition, row, cancellationToken).ConfigureAwait(false); + errors.AddRange(problems.Where(p => !p.IsWarning).Select(p => new TableImportError(rowNumber, TableDefinition.SnakeCase(p.Field), p.Code))); + pending.Add(row); + } + + if (errors.Count > 0) + { + return new TableImportResult(0, 0, errors); + } + + foreach (var row in pending) + { + if (row.Id == 0) + { + inserted++; + } + else + { + updated++; + } + + await WriteAsync(uow, definition, row, actor.UserName, cancellationToken).ConfigureAwait(false); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + await InvalidateAsync(company, definition, cancellationToken).ConfigureAwait(false); + return new TableImportResult(inserted, updated, []); + } + + /// Saves rows without permission checks or rules: the seeders (§14), inside their own unit of work. + /// The entity. + /// The company unit of work. + /// The row. + /// Who writes, such as system. + /// Cancellation. + /// A task. + internal Task WriteAsync(IUnitOfWork unitOfWork, T row, string userName, CancellationToken cancellationToken) + where T : CodedEntity, new() => + WriteAsync(unitOfWork, _catalog.Get(), row, userName, cancellationToken); + + /// Forgets the cached rows of every table of a company (after the seeders). + /// The company. + /// Cancellation. + /// A task. + public ValueTask InvalidateAllAsync(string companyCode, CancellationToken cancellationToken = default) => + _cache.PublishInvalidationAsync(CacheKeys.Prefix(CompanyCodes.Normalize(companyCode), "tables"), cancellationToken); + + private static async Task> CheckAsync( + IUnitOfWork uow, IFiscalPack pack, TableDefinition definition, T row, CancellationToken cancellationToken) + where T : CodedEntity, new() + { + row.Code = definition.KeepCodeCase ? row.Code.Trim() : row.Code.Trim().ToUpperInvariant(); + row.Description = row.Description.Trim(); + definition.Complete?.Invoke(row, pack); + + var context = new TableRuleContext(uow, pack); + if (row.Code.Length == 0) + { + context.Error(nameof(CodedEntity.Code), CodeRequired); + } + else if (row.Code.Length > definition.CodeLength) + { + context.Error(nameof(CodedEntity.Code), CodeTooLong); + } + else + { + var code = row.Code; + var id = row.Id; + var query = Query.For().Where(x => x.Code == code && x.Id != id); + if (definition.SameKey is { } sameKey) + { + query = query.Where(sameKey(row)); + } + + if (await uow.Repository().CountAsync(query, cancellationToken).ConfigureAwait(false) > 0) + { + context.Error(nameof(CodedEntity.Code), CodeDuplicate); + } + } + + if (row.Description.Length == 0) + { + context.Error(nameof(CodedEntity.Description), DescriptionRequired); + } + + foreach (var rule in definition.Rules) + { + await rule(row, context, cancellationToken).ConfigureAwait(false); + } + + return context.Problems; + } + + private static void Throw(IReadOnlyList problems) + { + var errors = problems.Where(p => !p.IsWarning).Select(p => p.Field + ":" + p.Code).ToList(); + if (errors.Count > 0) + { + throw new ValidationFailedException(errors); + } + } + + private static T Clone(T row) + where T : class, new() + { + var copy = new T(); + foreach (var property in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.CanRead && p.CanWrite)) + { + property.SetValue(copy, property.GetValue(row)); + } + + return copy; + } + + private static object? Export(object? value) => value switch + { + bool b => b ? "1" : "0", + DateOnly d => d.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + Enum e => e.ToString(), + _ => value, + }; + + private static bool TryParse(string text, PropertyInfo property, out object? value) + { + text = text.Trim(); + var type = property.PropertyType; + var target = Nullable.GetUnderlyingType(type) ?? type; + value = null; + if (text.Length == 0) + { + if (target == typeof(string)) + { + value = Nullability.Create(property).WriteState == NullabilityState.Nullable ? null : string.Empty; + return true; + } + + if (Nullable.GetUnderlyingType(type) is null) + { + value = Activator.CreateInstance(target); + } + + return true; + } + + if (target == typeof(string)) + { + value = text; + return true; + } + + if (target == typeof(bool)) + { + var lower = text.ToLowerInvariant(); + value = lower is "1" or "true" or "si" or "sì" or "s" or "x" or "vero"; + return value is true || lower is "0" or "false" or "no" or "n" or "falso"; + } + + if (target == typeof(int) || target == typeof(long) || target == typeof(decimal)) + { + // Italian (1.234,5) or invariant (1234.5): a comma is always the decimal point. + var normalized = text.Contains(',', StringComparison.Ordinal) ? text.Replace(".", string.Empty, StringComparison.Ordinal).Replace(',', '.') : text; + if (!decimal.TryParse(normalized, NumberStyles.Number, CultureInfo.InvariantCulture, out var number)) + { + return false; + } + + if (target == typeof(decimal)) + { + value = number; + return true; + } + + if (decimal.Truncate(number) != number) + { + return false; + } + + value = target == typeof(int) ? (object)(int)number : (long)number; + return true; + } + + if (target == typeof(DateOnly)) + { + var ok = DateOnly.TryParseExact(text, ["yyyy-MM-dd", "dd/MM/yyyy", "d/M/yyyy"], CultureInfo.InvariantCulture, DateTimeStyles.None, out var date); + value = date; + return ok; + } + + if (target.IsEnum) + { + var ok = Enum.TryParse(target, text, ignoreCase: true, out var parsed) && Enum.IsDefined(target, parsed!); + value = parsed; + return ok; + } + + return false; + } + + private async Task WriteAsync(IUnitOfWork uow, TableDefinition definition, T row, string userName, CancellationToken cancellationToken) + where T : CodedEntity, new() + { + var repository = uow.Repository(); + if (definition.SingleDefault is { } flag && flag.Compile()(row)) + { + await ClearOtherDefaultsAsync(repository, flag, row.Id, cancellationToken).ConfigureAwait(false); + } + + if (row.Id == 0) + { + row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Insert, row.Id, null, row, userName, cancellationToken).ConfigureAwait(false); + return; + } + + var before = await repository.GetAsync(row.Id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound); + await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, row.Id, before, row, userName, cancellationToken).ConfigureAwait(false); + } + + private static async Task ClearOtherDefaultsAsync(IRepository repository, System.Linq.Expressions.Expression> flag, long id, CancellationToken cancellationToken) + where T : CodedEntity, new() + { + var others = await repository.ListAsync(Query.For().Where(flag).Where(x => x.Id != id), cancellationToken).ConfigureAwait(false); + var property = (PropertyInfo)((System.Linq.Expressions.MemberExpression)flag.Body).Member; + foreach (var other in others.Items) + { + property.SetValue(other, false); + await repository.UpdateAsync(other, cancellationToken).ConfigureAwait(false); + } + } + + private async Task> RowsAsync(string company, TableDefinition definition, CancellationToken cancellationToken) + where T : CodedEntity, new() => + await _cache.GetOrCreateAsync>( + CacheKeys.For(company, "tables", definition.Key), + async ct => + { + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), ct).ConfigureAwait(false); + var page = await uow.Repository().ListAsync(Query.For().OrderBy(x => x.Code), ct).ConfigureAwait(false); + return [.. page.Items]; + }, + CacheTime, + cancellationToken).ConfigureAwait(false); + + private ValueTask InvalidateAsync(string company, TableDefinition definition, CancellationToken cancellationToken) => + _cache.PublishInvalidationAsync(CacheKeys.For(company, "tables", definition.Key), cancellationToken); + + private async Task DemandAsync(Actor actor, string companyCode, string permission, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(actor); + var company = CompanyCodes.Normalize(companyCode); + if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, company, StringComparison.Ordinal)) + { + throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A company user works only in its own company."); + } + + await _permissions.DemandAsync(actor, permission, cancellationToken).ConfigureAwait(false); + return company; + } +} diff --git a/src/Khaemhat.Core/Accounting/AccountNature.cs b/src/Khaemhat.Core/Accounting/AccountNature.cs new file mode 100644 index 0000000..1f69bd5 --- /dev/null +++ b/src/Khaemhat.Core/Accounting/AccountNature.cs @@ -0,0 +1,20 @@ +namespace Khaemhat.Core.Accounting; + +/// The nature of a ledger account: which statement it ends up in. +public enum AccountNature +{ + /// Balance sheet, assets. + Asset = 0, + + /// Balance sheet, liabilities and equity. + Liability = 1, + + /// Income statement, costs. + Cost = 2, + + /// Income statement, revenues. + Revenue = 3, + + /// Memorandum accounts (conti d'ordine), outside both statements. + Memorandum = 4, +} diff --git a/src/Khaemhat.Core/Accounting/AccountType.cs b/src/Khaemhat.Core/Accounting/AccountType.cs new file mode 100644 index 0000000..5f431dc --- /dev/null +++ b/src/Khaemhat.Core/Accounting/AccountType.cs @@ -0,0 +1,26 @@ +namespace Khaemhat.Core.Accounting; + +/// What a ledger account is used for, beyond its nature: the accounts the automatic postings look for. +public enum AccountType +{ + /// Any other account. + Generic = 0, + + /// The customers control account, with a sub-ledger per customer. + Customers = 1, + + /// The suppliers control account, with a sub-ledger per supplier. + Suppliers = 2, + + /// A bank account. + Bank = 3, + + /// Cash. + Cash = 4, + + /// VAT on sales or purchases, or the VAT settlement. + Vat = 5, + + /// Amounts due to or from the tax authority (withholdings, taxes). + Tax = 6, +} diff --git a/src/Khaemhat.Core/Items/Items.cs b/src/Khaemhat.Core/Items/Items.cs new file mode 100644 index 0000000..485ab46 --- /dev/null +++ b/src/Khaemhat.Core/Items/Items.cs @@ -0,0 +1,234 @@ +using Khaemhat.Core.Entities; + +namespace Khaemhat.Core.Items; + +/// What an item is (SPEC §11.2). +public enum ItemKind +{ + /// Goods bought or sold; kept in stock when . + Goods = 0, + + /// A service, such as installation or hours of assistance. + Service = 1, + + /// An ancillary expense on invoices (transport, collection). + Expense = 2, + + /// A recurring descriptive line. + Text = 3, + + /// A fixed asset (linked to the asset register with the ASSET module). + Asset = 4, +} + +/// Where the price proposed on a document line comes from (SPEC §11.3). +public enum PriceSource +{ + /// No price found. + None = 0, + + /// The net price agreed with the party for the item. + PartyNet = 1, + + /// The price list of the party (or of the document). + PartyPriceList = 2, + + /// The base price list of the company. + BasePriceList = 3, + + /// The price written on the item. + Item = 4, +} + +/// An item (items, mockup 017). +public sealed class Item : Entity, IDemoMarkable +{ + /// The code, automatic (ADR 0027, mask {categoria}-{seq:0000}). + public string Code { get; set; } = string.Empty; + + /// What the item is. + public ItemKind Kind { get; set; } + + /// The description used on documents. + public string Description { get; set; } = string.Empty; + + /// A longer description. + public string? ExtendedDescription { get; set; } + + /// The category (item_categories). + public long? CategoryId { get; set; } + + /// The base unit of measure (units_of_measure). + public long? UnitOfMeasureId { get; set; } + + /// The VAT code of sales (tax_codes). + public long? SalesTaxCodeId { get; set; } + + /// The VAT code of purchases (tax_codes). + public long? PurchaseTaxCodeId { get; set; } + + /// The main bar code (EAN/GTIN). + public string? Barcode { get; set; } + + /// The combined nomenclature code (NC8, Intrastat). + public string? CustomsCode { get; set; } + + /// The manufacturer. + public string? Manufacturer { get; set; } + + /// The brand. + public string? Brand { get; set; } + + /// Net weight in kilograms. + public decimal? NetWeight { get; set; } + + /// Gross weight in kilograms. + public decimal? GrossWeight { get; set; } + + /// The item is kept in stock (movements, balances, reorder from M6). + public bool Stocked { get; set; } + + /// The usual warehouse (warehouses). + public long? WarehouseId { get; set; } + + /// The minimum stock. + public decimal? MinimumStock { get; set; } + + /// The reorder point: below it the item is proposed for an order. + public decimal? ReorderPoint { get; set; } + + /// The reorder lot: orders are proposed in multiples of it. + public decimal? ReorderLot { get; set; } + + /// The price written on the item, the last fallback of the price search. + public decimal? Price { get; set; } + + /// The standard cost, set by hand. + public decimal? StandardCost { get; set; } + + /// The last purchase cost (updated by the receipts, M6). + public decimal? LastCost { get; set; } + + /// The weighted average cost (updated by the receipts, M6). + public decimal? AverageCost { get; set; } + + /// The revenue account (chart of accounts, M7). + public string? RevenueAccountCode { get; set; } + + /// The cost account (chart of accounts, M7). + public string? CostAccountCode { get; set; } + + /// Free notes. + public string? Notes { get; set; } + + /// Disabled: no longer proposed in new documents. + public bool Disabled { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// An alternative unit of measure of an item (item_uoms): a box of 10 pieces has factor 10. +public sealed class ItemUnit : Entity +{ + /// The item. + public long ItemId { get; set; } + + /// The unit (units_of_measure). + public long UnitOfMeasureId { get; set; } + + /// How many base units one of this unit holds. + public decimal Factor { get; set; } = 1m; + + /// The bar code of the package. + public string? Barcode { get; set; } +} + +/// An alternative code of an item (item_barcodes): another EAN or an internal code. +public sealed class ItemBarcode : Entity +{ + /// The item. + public long ItemId { get; set; } + + /// The code. + public string Code { get; set; } = string.Empty; + + /// What the code is, such as confezione or codice interno. + public string? Description { get; set; } +} + +/// +/// A price of an item (item_prices): in a price list, or net for a party. A price is valid from a date (none: +/// always); the price at a date is the one with the latest start not after it, so old prices stay for old documents. +/// +public sealed class ItemPrice : Entity +{ + /// The item. + public long ItemId { get; set; } + + /// The price list (price_lists), or none for a net price of a party. + public long? PriceListId { get; set; } + + /// The party of a net price (parties), or none for a price list. + public long? PartyId { get; set; } + + /// The price. + public decimal Price { get; set; } + + /// The price is valid from this day (none: always). + public DateOnly? ValidFrom { get; set; } +} + +/// A supplier of an item (item_suppliers) with its code and price; one is the usual one. +public sealed class ItemSupplier : Entity +{ + /// The item. + public long ItemId { get; set; } + + /// The supplier (parties). + public long PartyId { get; set; } + + /// The code of the item at the supplier. + public string? SupplierCode { get; set; } + + /// The purchase price. + public decimal? Price { get; set; } + + /// The lead time in days. + public int? LeadTimeDays { get; set; } + + /// The minimum quantity of an order. + public decimal? MinimumQuantity { get; set; } + + /// The usual supplier, used by the reorder proposal. + public bool IsDefault { get; set; } +} + +/// An equivalent item proposed when this one is missing (item_substitutes). +public sealed class ItemSubstitute : Entity +{ + /// The item. + public long ItemId { get; set; } + + /// The substitute (items). + public long SubstituteId { get; set; } + + /// Notes, such as the differences. + public string? Notes { get; set; } +} + +/// The code a customer or a supplier uses for one of our items (party_item_codes). +public sealed class PartyItemCode : Entity +{ + /// The party. + public long PartyId { get; set; } + + /// The item. + public long ItemId { get; set; } + + /// The code of the party. + public string Code { get; set; } = string.Empty; + + /// The description of the party. + public string? Description { get; set; } +} diff --git a/src/Khaemhat.Core/Items/PriceRounding.cs b/src/Khaemhat.Core/Items/PriceRounding.cs new file mode 100644 index 0000000..e624f8f --- /dev/null +++ b/src/Khaemhat.Core/Items/PriceRounding.cs @@ -0,0 +1,60 @@ +namespace Khaemhat.Core.Items; + +/// How a price is rounded to a step. +public enum RoundingDirection +{ + /// To the nearest step, halves away from zero. + Nearest = 0, + + /// Up to the next step (per eccesso). + Up = 1, + + /// Down to the previous step (per difetto). + Down = 2, +} + +/// The arithmetic of prices: percent changes and rounding to a step such as 0,10, 0,50 or 1,00. +public static class PriceRounding +{ + /// Rounds a price to a step; with no step, to the cent. + /// The price. + /// The step, such as 0.10; zero or less means cents. + /// Nearest, up or down. + /// The rounded price. + public static decimal Round(decimal value, decimal step, RoundingDirection direction = RoundingDirection.Nearest) + { + if (step <= 0) + { + step = 0.01m; + } + + var units = value / step; + units = direction switch + { + RoundingDirection.Up => decimal.Ceiling(Math.Round(units, 10)), + RoundingDirection.Down => decimal.Floor(Math.Round(units, 10)), + _ => Math.Round(units, MidpointRounding.AwayFromZero), + }; + return Normalize(units * step); + } + + /// Applies a percent change: +10 adds a tenth, -5 takes off a twentieth. + /// The price. + /// The change in percent. + /// The changed price, not rounded. + public static decimal Change(decimal value, decimal percent) => value * (1m + (percent / 100m)); + + /// The margin of a price over a cost, in percent of the price. + /// The price. + /// The cost. + /// The margin, or none without a positive price or a cost. + public static decimal? Margin(decimal? price, decimal? cost) => + price is > 0 && cost is { } c ? Math.Round((price.Value - c) / price.Value * 100m, 1, MidpointRounding.AwayFromZero) : null; + + // Four decimals at most, and two when the rest are zeros (12.3000 becomes 12.30). + private static decimal Normalize(decimal value) + { + var rounded = Math.Round(value, 4, MidpointRounding.AwayFromZero); + return rounded == Math.Round(rounded, 2) ? Math.Round(rounded, 2) : rounded; + } +} diff --git a/src/Khaemhat.Core/Parties/Parties.cs b/src/Khaemhat.Core/Parties/Parties.cs new file mode 100644 index 0000000..63a7e82 --- /dev/null +++ b/src/Khaemhat.Core/Parties/Parties.cs @@ -0,0 +1,475 @@ +using Khaemhat.Core.Entities; + +namespace Khaemhat.Core.Parties; + +/// What a party is to the company (SPEC §11.2): the archive and the code mask follow from it. +public enum PartyKind +{ + /// A customer (it may also be a supplier). + Customer = 0, + + /// A supplier that is not a customer. + Supplier = 1, + + /// A qualified potential customer, without fiscal documents. + Prospect = 2, + + /// A commercial contact still to qualify (CRM). + Lead = 3, +} + +/// The kind of subject: it decides the checks and the values proposed (SDI code, split payment, VAT number). +public enum SubjectType +{ + /// A domestic business. + Company = 0, + + /// A private person (consumer). + Person = 1, + + /// A public administration (split payment, office code of 6 characters). + PublicAdministration = 2, + + /// A business in another EU member state (VIES). + EuCompany = 3, + + /// A business outside the EU. + NonEuCompany = 4, + + /// A domestic business under the flat-rate scheme (no VAT charged, stamp duty). + FlatRate = 5, +} + +/// The outcome of the last check of the VAT number on VIES, saved on the party. +public enum VatCheckStatus +{ + /// Not checked. + None = 0, + + /// Registered for intra-EU operations. + Valid = 1, + + /// Not registered. + Invalid = 2, + + /// The service could not answer; to repeat. + Unavailable = 3, +} + +/// How the documents are sent to a customer. +public enum DocumentDelivery +{ + /// Not sent: printed or downloaded. + None = 0, + + /// By e-mail. + Email = 1, + + /// By certified e-mail (PEC). + Pec = 2, +} + +/// What an address of a party is used for. +public enum PartyAddressKind +{ + /// Delivery address (destination of delivery notes). + Delivery = 0, + + /// Address for invoices, when different from the registered office. + Billing = 1, + + /// A building site or a branch. + Site = 2, + + /// Another address. + Other = 3, +} + +/// +/// A party (SPEC §11.2, wiki Anagrafiche): customer, supplier, prospect or lead, registered once. The code follows +/// the mask of its kind (ADR 0027); converting a lead or prospect into a customer gives it a customer code and keeps the +/// old one in . +/// +public sealed class Party : Entity, IDemoMarkable +{ + /// The code, unique among the parties. + public string Code { get; set; } = string.Empty; + + /// The code it had before a conversion. + public string? PreviousCode { get; set; } + + /// What the party is. + public PartyKind Kind { get; set; } + + /// A customer that also sells to the company. + public bool IsAlsoSupplier { get; set; } + + /// The kind of subject. + public SubjectType SubjectType { get; set; } + + /// The business name, or "last name first name" for a person. + public string Name { get; set; } = string.Empty; + + /// The first name of a person. + public string? FirstName { get; set; } + + /// The last name of a person. + public string? LastName { get; set; } + + /// The name on fiscal documents, when different. + public string? FiscalName { get; set; } + + /// The VAT number, compact, without the country prefix. + public string? VatNumber { get; set; } + + /// The tax code. + public string? TaxCode { get; set; } + + /// The registration in the companies register (REA). + public string? Rea { get; set; } + + /// The category (party_categories). + public long? CategoryId { get; set; } + + /// Street of the registered office. + public string? Address { get; set; } + + /// Street number. + public string? StreetNumber { get; set; } + + /// Postal code. + public string? PostalCode { get; set; } + + /// Municipality or city. + public string? City { get; set; } + + /// Province abbreviation (or region abroad). + public string? Province { get; set; } + + /// Country (ISO 3166-1 alpha-2). + public string CountryCode { get; set; } = "IT"; + + /// Phone. + public string? Phone { get; set; } + + /// E-mail. + public string? Email { get; set; } + + /// Certified e-mail (PEC). + public string? Pec { get; set; } + + /// Web site. + public string? Website { get; set; } + + /// The salesperson (salespeople). + public long? SalespersonId { get; set; } + + /// Language of the documents (ISO 639-1). + public string Language { get; set; } = "it"; + + /// Currency of the documents (ISO 4217). + public string CurrencyCode { get; set; } = "EUR"; + + /// Start of the relationship. + public DateOnly? Since { get; set; } + + /// Privacy notice accepted. + public bool PrivacyAccepted { get; set; } + + /// Consent to marketing. + public bool Marketing { get; set; } + + /// Notes. + public string? Notes { get; set; } + + /// Last VIES outcome. + public VatCheckStatus VatCheck { get; set; } + + /// When VIES answered (or failed), UTC. + public DateTime? VatCheckedAt { get; set; } + + /// The customer sub-account of the ledger, created at the first posting (M7). + public string? CustomerAccountCode { get; set; } + + /// The supplier sub-account of the ledger, created at the first posting (M7). + public string? SupplierAccountCode { get; set; } + + /// Hidden from new documents and default searches; kept with its documents. + public bool Disabled { get; set; } + + /// + public bool IsDemo { get; set; } + + /// Whether the party is a customer (also a supplier that is a customer). + public bool IsCustomer => Kind == PartyKind.Customer; + + /// Whether the party is a supplier, alone or also a customer. + public bool IsSupplier => Kind == PartyKind.Supplier || (Kind == PartyKind.Customer && IsAlsoSupplier); +} + +/// An address of a party besides the registered office. +public sealed class PartyAddress : Entity +{ + /// The party. + public long PartyId { get; set; } + + /// What it is used for. + public PartyAddressKind Kind { get; set; } + + /// The name shown on documents (site, branch). + public string Name { get; set; } = string.Empty; + + /// Street. + public string? Address { get; set; } + + /// Street number. + public string? StreetNumber { get; set; } + + /// Postal code. + public string? PostalCode { get; set; } + + /// City. + public string? City { get; set; } + + /// Province. + public string? Province { get; set; } + + /// Country (ISO 3166-1 alpha-2). + public string CountryCode { get; set; } = "IT"; + + /// The address proposed first for its kind. + public bool IsDefault { get; set; } + + /// Notes (opening hours, how to reach it). + public string? Notes { get; set; } +} + +/// A contact person of a party. +public sealed class PartyContact : Entity +{ + /// The party. + public long PartyId { get; set; } + + /// Name and surname. + public string Name { get; set; } = string.Empty; + + /// Role (purchasing, administration...). + public string? Role { get; set; } + + /// Phone. + public string? Phone { get; set; } + + /// Mobile phone. + public string? Mobile { get; set; } + + /// E-mail. + public string? Email { get; set; } + + /// The main contact. + public bool IsDefault { get; set; } + + /// Notes. + public string? Notes { get; set; } +} + +/// A bank account of a party: the bank of its RiBa, or where the company pays it. +public sealed class PartyBankAccount : Entity +{ + /// The party. + public long PartyId { get; set; } + + /// The IBAN, compact. + public string Iban { get; set; } = string.Empty; + + /// The BIC. + public string? Bic { get; set; } + + /// The bank. + public string? BankName { get; set; } + + /// The national bank code (ABI), read from the IBAN. + public string? BankCode { get; set; } + + /// The branch code (CAB), read from the IBAN. + public string? BranchCode { get; set; } + + /// The account proposed on documents. + public bool IsDefault { get; set; } +} + +/// The sales terms of a customer, proposed on its documents (M5). +public sealed class PartySalesTerms : Entity +{ + /// The party (one row per party). + public long PartyId { get; set; } + + /// The price list (price_lists). + public long? PriceListId { get; set; } + + /// First discount, percent. + public decimal? Discount1 { get; set; } + + /// Second discount, percent. + public decimal? Discount2 { get; set; } + + /// The payment terms (payment_terms). + public long? PaymentTermId { get; set; } + + /// The account of the company where the customer pays (bank_accounts). + public long? CompanyBankAccountId { get; set; } + + /// The carrier (carriers). + public long? CarrierId { get; set; } + + /// The shipping terms (shipping_terms). + public long? ShippingTermId { get; set; } + + /// The warehouse goods leave from (warehouses). + public long? WarehouseId { get; set; } + + /// The credit limit: the most the customer may owe. + public decimal? CreditLimit { get; set; } + + /// Orders and deliveries are blocked. + public bool Blocked { get; set; } + + /// Delivery notes are grouped into one deferred invoice. + public bool GroupDeliveryNotes { get; set; } = true; + + /// The day of the month the deferred invoices are issued, if fixed. + public int? InvoiceDay { get; set; } + + /// How the documents are sent. + public DocumentDelivery SendDocuments { get; set; } + + /// Where the documents are sent, when not the main e-mail or PEC. + public string? DocumentsEmail { get; set; } +} + +/// The purchase terms of a supplier, proposed on its orders (M6). +public sealed class PartyPurchaseTerms : Entity +{ + /// The party (one row per party). + public long PartyId { get; set; } + + /// The payment terms (payment_terms). + public long? PaymentTermId { get; set; } + + /// Days between order and delivery. + public int? LeadTimeDays { get; set; } + + /// The smallest order accepted. + public decimal? MinimumOrder { get; set; } + + /// Discount, percent. + public decimal? Discount { get; set; } + + /// The shipping terms (shipping_terms). + public long? ShippingTermId { get; set; } + + /// The VAT register of the purchases (M7). + public string? VatRegisterCode { get; set; } + + /// The cost account proposed (M7). + public string? CostAccountCode { get; set; } + + /// The e-mail for the orders. + public string? OrdersEmail { get; set; } +} + +/// +/// The fiscal data of a party (mockup 015, 016): e-invoicing, VAT regime, withholding and contributions, the declaration +/// of intent of a habitual exporter and the identifiers. +/// +public sealed class PartyFiscal : Entity +{ + /// The party (one row per party). + public long PartyId { get; set; } + + /// The SDI recipient code (7 characters, 6 for a public administration). + public string? RecipientCode { get; set; } + + /// The PEC the e-invoices go to, without a recipient code. + public string? RecipientPec { get; set; } + + /// The reference of the administration (public administrations). + public string? AdministrationReference { get; set; } + + /// A courtesy PDF goes with the e-invoice. + public bool AttachPdf { get; set; } = true; + + /// A copy is sent by e-mail when the invoice is issued. + public bool SendCopy { get; set; } + + /// Split payment (art. 17-ter DPR 633/72). + public bool SplitPayment { get; set; } + + /// Reverse charge by default. + public bool ReverseCharge { get; set; } + + /// The VAT code proposed (tax_codes). + public long? TaxCodeId { get; set; } + + /// VAT exigibility: I immediate, D deferred, S split payment. + public string? Exigibility { get; set; } + + /// The stamp duty is charged to the customer. + public bool StampDutyCharged { get; set; } = true; + + /// Subject to withholding tax (professionals). + public bool Withholding { get; set; } + + /// Withholding rate, percent. + public decimal? WithholdingRate { get; set; } + + /// Withholding reason of the e-invoice (A, M, Q...). + public string? WithholdingReason { get; set; } + + /// Pension fund of the e-invoice (TC01-TC22). + public string? PensionFund { get; set; } + + /// Pension fund rate, percent. + public decimal? PensionFundRate { get; set; } + + /// Agent subject to ENASARCO. + public bool Enasarco { get; set; } + + /// Declaration of intent active. + public bool IntentActive { get; set; } + + /// Number of the declaration. + public string? IntentNumber { get; set; } + + /// Date of the declaration. + public DateOnly? IntentDate { get; set; } + + /// Protocol of the revenue agency. + public string? IntentProtocol { get; set; } + + /// The non-taxable VAT code used under the declaration (tax_codes, nature N3.5). + public long? IntentTaxCodeId { get; set; } + + /// The ceiling of the declaration. + public decimal? IntentCeiling { get; set; } + + /// The amount already invoiced under the declaration (updated by the invoices, M5). + public decimal IntentUsed { get; set; } + + /// The declaration is valid from. + public DateOnly? IntentFrom { get; set; } + + /// The declaration is valid until. + public DateOnly? IntentTo { get; set; } + + /// Global location number. + public string? Gln { get; set; } + + /// Economic operators registration and identification number (customs). + public string? Eori { get; set; } + + /// The code of the company at the party. + public string? OurCode { get; set; } + + /// What remains of the ceiling of the declaration. + public decimal? IntentRemaining => IntentCeiling is { } ceiling ? ceiling - IntentUsed : null; +} diff --git a/src/Khaemhat.Core/Tables/BaseTables.cs b/src/Khaemhat.Core/Tables/BaseTables.cs new file mode 100644 index 0000000..77326c5 --- /dev/null +++ b/src/Khaemhat.Core/Tables/BaseTables.cs @@ -0,0 +1,472 @@ +using Khaemhat.Core.Entities; +using Khaemhat.Core.Tax; + +namespace Khaemhat.Core.Tables; + +/// A row of a company table with a code the users type and a description (SPEC §11.1). +public interface ICodedRecord : IEntity +{ + /// The code, unique in the table. + string Code { get; set; } + + /// The description (or the name). + string Description { get; set; } + + /// Hidden from choices on new records; kept for old ones. + bool Disabled { get; set; } +} + +/// Base class of the coded tables. +public abstract class CodedEntity : Entity, ICodedRecord, IDemoMarkable +{ + /// + public string Code { get; set; } = string.Empty; + + /// + public string Description { get; set; } = string.Empty; + + /// + public bool Disabled { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// A country (ISO 3166-1). +public sealed class Country : CodedEntity +{ + /// ISO 3166-1 alpha-3 code. + public string? Iso3 { get; set; } + + /// Member of the European Union (VIES, Intrastat, intra-EU VAT). + public bool EuMember { get; set; } + + /// The prefix of VAT numbers, when different from the code (Greece: EL). + public string? VatPrefix { get; set; } + + /// The usual currency (ISO 4217). + public string? CurrencyCode { get; set; } +} + +/// An Italian province (code = the two-letter abbreviation). +public sealed class Province : CodedEntity +{ + /// The region. + public string? Region { get; set; } +} + +/// An Italian municipality (code = cadastral code, used by the fiscal code). +public sealed class Municipality : CodedEntity +{ + /// The province abbreviation. + public string ProvinceCode { get; set; } = string.Empty; + + /// The region. + public string? Region { get; set; } + + /// The ISTAT code (6 digits). + public string? IstatCode { get; set; } + + /// The postal codes, comma separated (one for most municipalities, a range for large cities). + public string? PostalCodes { get; set; } +} + +/// A currency (ISO 4217). +public sealed class Currency : CodedEntity +{ + /// The symbol, such as €. + public string? Symbol { get; set; } + + /// Decimals of amounts. + public int Decimals { get; set; } = 2; +} + +/// An exchange rate: units of the currency for one euro on a day (ECB reference rate or manual). +public sealed class ExchangeRate : Entity +{ + /// The currency (ISO 4217). + public string CurrencyCode { get; set; } = string.Empty; + + /// The day. + public DateOnly RateDate { get; set; } + + /// Units of the currency for one euro. + public decimal Rate { get; set; } + + /// Where the rate comes from: ECB or MANUAL. + public string Source { get; set; } = "MANUAL"; +} + +/// A unit of measure. +public sealed class UnitOfMeasure : CodedEntity +{ + /// Decimals allowed in quantities. + public int Decimals { get; set; } + + /// The text written in UnitaMisura of the e-invoice, when different from the code. + public string? EInvoiceCode { get; set; } +} + +/// A VAT code (mockup 076). +public sealed class TaxCode : CodedEntity +{ + /// The rate in percent. + public decimal Rate { get; set; } + + /// The nature for zero-rate operations (N1...N7). + public string? Nature { get; set; } + + /// The kind of operation, from rate and nature. + public TaxCodeKind Kind { get; set; } + + /// When the tax becomes due. + public TaxExigibility Exigibility { get; set; } + + /// Share of the purchase tax that cannot be deducted. + public decimal NonDeductiblePercent { get; set; } + + /// The law printed on the invoice. + public string? LegalReference { get; set; } + + /// First day of validity. + public DateOnly? ValidFrom { get; set; } + + /// Last day of validity. + public DateOnly? ValidTo { get; set; } + + /// The VAT account for sales (ledger, M7). + public string? SalesAccountCode { get; set; } + + /// The VAT account for purchases (ledger, M7). + public string? PurchaseAccountCode { get; set; } +} + +/// A payment method (MP01...MP23). +public sealed class PaymentMethod : CodedEntity +{ + /// The FatturaPA code, such as MP05. + public string EInvoiceCode { get; set; } = "MP05"; + + /// Whether a bank of the customer (RiBa, direct debit) or of the company (transfer) is needed. + public bool NeedsBank { get; set; } +} + +/// Payment terms with their installments (lines). +public sealed class PaymentTerm : CodedEntity +{ + /// The payment method. + public long? PaymentMethodId { get; set; } + + /// The FatturaPA condition: TP01 installments, TP02 full, TP03 advance. + public string Condition { get; set; } = "TP02"; + + /// All the VAT on the first installment. + public bool VatOnFirstInstallment { get; set; } +} + +/// An installment of payment terms. +public sealed class PaymentTermLine : Entity +{ + /// The payment terms. + public long PaymentTermId { get; set; } + + /// The order of the installment, from 1. + public int Number { get; set; } + + /// Days from the document date. + public int Days { get; set; } + + /// Move the due date to the end of the month. + public bool EndOfMonth { get; set; } + + /// A fixed day of the month after the end-of-month move, such as 10. + public int? FixedDay { get; set; } + + /// Share of the amount, in percent. + public decimal Percent { get; set; } +} + +/// A bank account of the company. +public sealed class BankAccount : CodedEntity +{ + /// The bank. + public string? BankName { get; set; } + + /// The IBAN, compact. + public string? Iban { get; set; } + + /// The BIC. + public string? Bic { get; set; } + + /// The SIA code for RiBa files. + public string? SiaCode { get; set; } + + /// The CBI CUC code. + public string? CucCode { get; set; } + + /// The ledger account (M7). + public string? AccountCode { get; set; } + + /// The account proposed on documents. + public bool IsDefault { get; set; } +} + +/// A sales agent (code + name in ). +public sealed class Salesperson : CodedEntity +{ + /// The e-mail address. + public string? Email { get; set; } + + /// The phone. + public string? Phone { get; set; } + + /// The usual commission, in percent. + public decimal CommissionPercent { get; set; } + + /// Subject to ENASARCO contributions. + public bool Enasarco { get; set; } +} + +/// A carrier (code + name). +public sealed class Carrier : CodedEntity +{ + /// The VAT number. + public string? VatNumber { get; set; } + + /// The address. + public string? Address { get; set; } + + /// The town. + public string? City { get; set; } + + /// The phone. + public string? Phone { get; set; } + + /// The e-mail address. + public string? Email { get; set; } + + /// The registration number in the haulage register. + public string? RegisterNumber { get; set; } +} + +/// Who pays the transport (porto: franco, assegnato...). +public sealed class ShippingTerm : CodedEntity; + +/// Who carries the goods (mittente, destinatario, vettore). +public sealed class TransportMean : CodedEntity; + +/// The appearance of the goods on the delivery note (cartoni, bancali...). +public sealed class GoodsAppearance : CodedEntity; + +/// An Incoterms rule. +public sealed class DeliveryTerm : CodedEntity; + +/// The reason of the transport (vendita, conto visione...). +public sealed class TransportReason : CodedEntity; + +/// What a stock movement does to the quantity on hand. +public enum StockEffect +{ + /// No effect on quantities. + None = 0, + + /// Increases the stock (load). + Load = 1, + + /// Decreases the stock (unload). + Unload = 2, +} + +/// A warehouse movement reason. +public sealed class InventoryReason : CodedEntity +{ + /// The effect on the quantity. + public StockEffect Effect { get; set; } + + /// Whether it changes the stock value (purchases, sales) or only quantities (transfers). + public bool AffectsValue { get; set; } = true; + + /// Whether it is a transfer between warehouses (needs a destination). + public bool IsTransfer { get; set; } +} + +/// A warehouse. +public sealed class Warehouse : CodedEntity +{ + /// The address. + public string? Address { get; set; } + + /// The town. + public string? City { get; set; } + + /// The province abbreviation. + public string? ProvinceCode { get; set; } + + /// The warehouse proposed on documents. + public bool IsDefault { get; set; } +} + +/// A category of items, on up to three levels. +public sealed class ItemCategory : CodedEntity +{ + /// The parent category. + public long? ParentId { get; set; } + + /// The level, 1 to 3. + public int Level { get; set; } = 1; +} + +/// A category of customers and suppliers. +public sealed class PartyCategory : CodedEntity; + +/// A price list (the prices are in item_prices, mockup 018). +public sealed class PriceList : CodedEntity +{ + /// The currency (ISO 4217). + public string CurrencyCode { get; set; } = "EUR"; + + /// Prices include VAT (retail). + public bool VatIncluded { get; set; } + + /// First day of validity. + public DateOnly? ValidFrom { get; set; } + + /// Last day of validity. + public DateOnly? ValidTo { get; set; } + + /// The list this one derives from. + public long? BasePriceListId { get; set; } + + /// Change applied to the base list, in percent (negative for a discount). + public decimal MarkupPercent { get; set; } + + /// Rounding step of derived prices, such as 0.05; zero for none. + public decimal RoundingStep { get; set; } + + /// The base price list of the company: the third step of the price search (SPEC §11.3, ADR 0030). + public bool IsBase { get; set; } +} + +/// A discount policy: a chain of discounts such as 10+5. +public sealed class DiscountPolicy : CodedEntity +{ + /// The chain of discounts in percent, separated by +. + public string Formula { get; set; } = string.Empty; +} + +/// The family of a document numerator. +public enum NumeratorKind +{ + /// Quotations. + Quotation = 0, + + /// Customer orders. + SalesOrder = 1, + + /// Delivery notes. + DeliveryNote = 2, + + /// Sales invoices and credit notes (no gaps). + SalesInvoice = 3, + + /// Supplier orders. + PurchaseOrder = 4, + + /// Purchase protocol. + PurchaseInvoice = 5, + + /// Warehouse movements. + Inventory = 6, + + /// Journal entries (no gaps). + Journal = 7, + + /// Anything else. + Other = 8, +} + +/// A document numerator for a year (assignment at confirmation arrives with the documents, M5). +public sealed class DocumentNumerator : CodedEntity +{ + /// The family. + public NumeratorKind Kind { get; set; } + + /// The section (sezionale), such as A; empty for the main one. + public string? Section { get; set; } + + /// The year. + public int Year { get; set; } + + /// The prefix. + public string? Prefix { get; set; } + + /// The format, such as {prefix}/{year}/{number:D6}. + public string Format { get; set; } = "{number}/{year}"; + + /// The last number assigned. + public long LastNumber { get; set; } + + /// Whether gaps are allowed (never for invoices, credit notes and final entries). + public bool GapsAllowed { get; set; } +} + +/// A type of document: the links between a document and its numerator, warehouse reason and SDI type. +public sealed class DocumentType : CodedEntity +{ + /// The family of document. + public NumeratorKind Kind { get; set; } + + /// The numerator. + public long? NumeratorId { get; set; } + + /// The warehouse reason. + public long? InventoryReasonId { get; set; } + + /// The SDI document type (TD01...). + public string? EInvoiceType { get; set; } + + /// The journal template (ledger, M7). + public string? JournalTemplateCode { get; set; } + + /// The VAT register (ledger, M7). + public string? VatRegisterCode { get; set; } + + /// The print template. + public string? PrintTemplate { get; set; } +} + +/// A cost centre. +public sealed class CostCenter : CodedEntity +{ + /// The parent cost centre. + public long? ParentId { get; set; } +} + +/// The state of a job. +public enum JobStatus +{ + /// Open. + Open = 0, + + /// Suspended. + Suspended = 1, + + /// Closed. + Closed = 2, +} + +/// A job (commessa). +public sealed class Job : CodedEntity +{ + /// The customer, when the job is for one. + public long? PartyId { get; set; } + + /// The start. + public DateOnly? StartDate { get; set; } + + /// The end. + public DateOnly? EndDate { get; set; } + + /// The state. + public JobStatus Status { get; set; } +} 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.Core/Tables/CompanyProfile.cs b/src/Khaemhat.Core/Tables/CompanyProfile.cs new file mode 100644 index 0000000..e3b3d34 --- /dev/null +++ b/src/Khaemhat.Core/Tables/CompanyProfile.cs @@ -0,0 +1,180 @@ +using Khaemhat.Core.Entities; +using Khaemhat.Core.Tax; + +namespace Khaemhat.Core.Tables; + +/// The data of the company itself, one row per company database (SPEC §11.1, mockup 075). +public sealed class CompanyProfile : Entity +{ + /// The company name. + public string LegalName { get; set; } = string.Empty; + + /// The name written on fiscal documents, when different. + public string? FiscalName { get; set; } + + /// The VAT number, without the country prefix. + public string? VatNumber { get; set; } + + /// The tax code. + public string? TaxCode { get; set; } + + /// The province of the business register (REA). + public string? ReaOffice { get; set; } + + /// The number in the business register (REA). + public string? ReaNumber { get; set; } + + /// The share capital. + public decimal? ShareCapital { get; set; } + + /// Sole shareholder: SU one, SM more; empty when it does not apply. + public string? Shareholders { get; set; } + + /// Liquidation: LN not in liquidation, LS in liquidation. + public string? LiquidationStatus { get; set; } + + /// The street. + public string? Address { get; set; } + + /// The street number. + public string? StreetNumber { get; set; } + + /// The postal code. + public string? PostalCode { get; set; } + + /// The town. + public string? City { get; set; } + + /// The province abbreviation. + public string? ProvinceCode { get; set; } + + /// The country of the address (ISO 3166-1). + public string? AddressCountry { get; set; } + + /// The phone. + public string? Phone { get; set; } + + /// The e-mail address. + public string? Email { get; set; } + + /// The certified e-mail address. + public string? Pec { get; set; } + + /// The web site. + public string? Website { get; set; } + + /// The tax regime, such as RF01. + public string TaxRegime { get; set; } = "RF01"; + + /// The company's own recipient code for incoming e-invoices. + public string? RecipientCode { get; set; } + + /// The logo (an attachment of entity company_profile). + public long? LogoAttachmentId { get; set; } + + /// The bank account proposed on documents. + public long? DefaultBankAccountId { get; set; } + + /// The accounting currency (ISO 4217). + public string CurrencyCode { get; set; } = "EUR"; + + /// The country whose fiscal pack applies (ISO 3166-1), from KHAEMHAT_COUNTRY at creation. + public string Country { get; set; } = "IT"; + + /// The VAT settlement periodicity. + public VatPeriodicity VatPeriodicity { get; set; } + + /// The deductible share for companies with exempt operations (pro-rata), in percent; 100 when it does not apply. + public decimal ProRataPercent { get; set; } = 100m; + + /// VAT on cash basis (art. 32-bis DL 83/2012). + public bool CashVat { get; set; } + + /// The first month of the fiscal year (1 for calendar years). + public int FiscalYearStartMonth { get; set; } = 1; + + /// The transmitter of e-invoices, when not the company: country. + public string? TransmitterCountry { get; set; } + + /// The transmitter of e-invoices: tax identifier. + public string? TransmitterId { get; set; } + + /// The intermediary that sends the returns (LIPE, F24): name. + public string? IntermediaryName { get; set; } + + /// The intermediary: tax code. + public string? IntermediaryTaxCode { get; set; } + + /// The text printed at the bottom of documents. + public string? FooterNotes { get; set; } +} + +/// The state of a fiscal year (SPEC §11.1, mockup 052). +public enum FiscalYearStatus +{ + /// Entries allowed. + Open = 0, + + /// Closing entries in progress: only closing entries. + Closing = 1, + + /// Read only. + Closed = 2, +} + +/// A fiscal year. +public sealed class FiscalYear : Entity +{ + /// The code, such as 2026 or 2026/27. + public string Code { get; set; } = string.Empty; + + /// The first day. + public DateOnly StartDate { get; set; } + + /// The last day. + public DateOnly EndDate { get; set; } + + /// The state. + public FiscalYearStatus Status { get; set; } + + /// The first page number of the journal printed for this year. + public int JournalFirstPage { get; set; } = 1; + + /// The number of the last final journal entry. + public long LastFinalEntryNumber { get; set; } + + /// The date of the last final journal entry. + public DateOnly? LastFinalEntryDate { get; set; } +} + +/// The state of a fiscal period. +public enum FiscalPeriodStatus +{ + /// Documents and entries allowed. + Open = 0, + + /// The VAT of the period was settled: no new entries with VAT. + Settled = 1, + + /// Locked: no new documents or entries dated in the period. + Locked = 2, +} + +/// A month of a fiscal year. +public sealed class FiscalPeriod : Entity +{ + /// The fiscal year. + public long FiscalYearId { get; set; } + + /// The number in the year, from 1. + public int Number { get; set; } + + /// The first day. + public DateOnly StartDate { get; set; } + + /// The last day. + public DateOnly EndDate { get; set; } + + /// The state. + public FiscalPeriodStatus Status { get; set; } +} diff --git a/src/Khaemhat.Core/Tax/TaxEnums.cs b/src/Khaemhat.Core/Tax/TaxEnums.cs new file mode 100644 index 0000000..79b7630 --- /dev/null +++ b/src/Khaemhat.Core/Tax/TaxEnums.cs @@ -0,0 +1,52 @@ +namespace Khaemhat.Core.Tax; + +/// When the VAT of an operation becomes due (FatturaPA EsigibilitaIVA: I, D, S). +public enum TaxExigibility +{ + /// Due when the invoice is issued (I). + Immediate = 0, + + /// Due when the invoice is paid, as with cash VAT or deferred VAT for public bodies (D). + Deferred = 1, + + /// Paid by the public body that buys (split payment, S). + SplitPayment = 2, +} + +/// What a tax code means for the VAT return, independent of the country's code for it. +public enum TaxCodeKind +{ + /// Taxable with a rate above zero. + Taxable = 0, + + /// Not taxable (exports, intra-EU supplies, letters of intent). + NonTaxable = 1, + + /// Exempt. + Exempt = 2, + + /// Excluded from the taxable amount. + Excluded = 3, + + /// Outside the scope of VAT. + NotSubject = 4, + + /// VAT paid by the buyer (reverse charge). + ReverseCharge = 5, + + /// Margin scheme: VAT not shown on the invoice. + Margin = 6, + + /// VAT paid in another EU country. + OtherEuVat = 7, +} + +/// How often the company settles VAT. +public enum VatPeriodicity +{ + /// Every month. + Monthly = 0, + + /// Every quarter, with interest where the country requires it. + Quarterly = 1, +} diff --git a/src/Khaemhat.Core/Validation/Validators.cs b/src/Khaemhat.Core/Validation/Validators.cs new file mode 100644 index 0000000..23bc7b6 --- /dev/null +++ b/src/Khaemhat.Core/Validation/Validators.cs @@ -0,0 +1,149 @@ +using System.Globalization; +using System.Text; + +namespace Khaemhat.Core.Validation; + +/// +/// International Bank Account Numbers (ISO 13616): country, length of the country and the mod-97 check. Spaces and +/// case do not matter. +/// +public static class IbanValidator +{ + // Lengths of the SEPA countries and their neighbours; other countries are checked for 15-34 characters only. + private static readonly Dictionary Lengths = new(StringComparer.Ordinal) + { + ["AD"] = 24, ["AT"] = 20, ["BE"] = 16, ["BG"] = 22, ["CH"] = 21, ["CY"] = 28, ["CZ"] = 24, ["DE"] = 22, + ["DK"] = 18, ["EE"] = 20, ["ES"] = 24, ["FI"] = 18, ["FR"] = 27, ["GB"] = 22, ["GI"] = 23, ["GR"] = 27, + ["HR"] = 21, ["HU"] = 28, ["IE"] = 22, ["IS"] = 26, ["IT"] = 27, ["LI"] = 21, ["LT"] = 20, ["LU"] = 20, + ["LV"] = 21, ["MC"] = 27, ["MT"] = 31, ["NL"] = 18, ["NO"] = 15, ["PL"] = 28, ["PT"] = 25, ["RO"] = 24, + ["SE"] = 24, ["SI"] = 19, ["SK"] = 24, ["SM"] = 27, ["VA"] = 22, + }; + + /// The IBAN without spaces, in capitals. + /// The IBAN as typed. + /// The compact form, or an empty string. + public static string Normalize(string? iban) => + iban is null ? string.Empty : string.Concat(iban.Where(c => !char.IsWhiteSpace(c))).ToUpperInvariant(); + + /// The IBAN in groups of four characters, as printed. + /// The IBAN. + /// The printed form. + public static string Format(string? iban) + { + var compact = Normalize(iban); + var builder = new StringBuilder(compact.Length + (compact.Length / 4)); + for (var i = 0; i < compact.Length; i++) + { + if (i > 0 && i % 4 == 0) + { + builder.Append(' '); + } + + builder.Append(compact[i]); + } + + return builder.ToString(); + } + + /// Whether an IBAN is well formed and its check digits are right. + /// The IBAN, with or without spaces. + /// for a valid IBAN. + public static bool IsValid(string? iban) + { + var value = Normalize(iban); + if (value.Length is < 15 or > 34 || !char.IsAsciiLetterUpper(value[0]) || !char.IsAsciiLetterUpper(value[1]) + || !char.IsAsciiDigit(value[2]) || !char.IsAsciiDigit(value[3]) || !value.All(char.IsAsciiLetterOrDigit)) + { + return false; + } + + if (Lengths.TryGetValue(value[..2], out var length) && value.Length != length) + { + return false; + } + + // Move the first four characters to the end, turn letters into 10-35 and compute mod 97 digit by digit. + var remainder = 0; + foreach (var c in value[4..] + value[..4]) + { + var digits = char.IsAsciiDigit(c) ? (c - '0').ToString(CultureInfo.InvariantCulture) : (c - 'A' + 10).ToString(CultureInfo.InvariantCulture); + foreach (var d in digits) + { + remainder = ((remainder * 10) + (d - '0')) % 97; + } + } + + return remainder == 1; + } +} + +/// GTIN barcodes: EAN-8, UPC-A (12), EAN-13 and GTIN-14, with the mod-10 check digit. +public static class EanValidator +{ + /// Whether a barcode has a valid length and check digit. + /// The digits of the barcode. + /// for a valid code. + public static bool IsValid(string? code) + { + var value = code?.Trim() ?? string.Empty; + if (value.Length is not (8 or 12 or 13 or 14) || !value.All(char.IsAsciiDigit)) + { + return false; + } + + return CheckDigit(value[..^1]) == value[^1] - '0'; + } + + /// The check digit for the digits of a code without it. + /// The digits before the check digit. + /// The check digit, 0-9. + public static int CheckDigit(string digits) + { + ArgumentNullException.ThrowIfNull(digits); + var sum = 0; + + // Weights 3 and 1 alternate starting from the rightmost digit. + for (var i = 0; i < digits.Length; i++) + { + var digit = digits[digits.Length - 1 - i] - '0'; + sum += i % 2 == 0 ? digit * 3 : digit; + } + + return (10 - (sum % 10)) % 10; + } +} + +/// +/// E-mail addresses as people type them for invoices and reminders: one @, a local part of up to 64 characters +/// and a domain with at least one dot. Quoted local parts and IP literals are refused on purpose. +/// +public static class EmailValidator +{ + private const string LocalSpecials = ".!#$%&'*+/=?^_`{|}~-"; + + /// Whether an address is acceptable. + /// The address. + /// for a valid address. + public static bool IsValid(string? address) + { + var value = address?.Trim() ?? string.Empty; + var at = value.IndexOf('@', StringComparison.Ordinal); + if (value.Length > 254 || at <= 0 || at != value.LastIndexOf('@')) + { + return false; + } + + var local = value[..at]; + var domain = value[(at + 1)..]; + if (local.Length > 64 || local[0] == '.' || local[^1] == '.' || local.Contains("..", StringComparison.Ordinal) + || !local.All(c => char.IsAsciiLetterOrDigit(c) || LocalSpecials.Contains(c, StringComparison.Ordinal))) + { + return false; + } + + var labels = domain.Split('.'); + return labels.Length >= 2 + && labels.All(l => l.Length is > 0 and <= 63 && l[0] != '-' && l[^1] != '-' && l.All(c => char.IsLetterOrDigit(c) || c == '-')) + && labels[^1].Length >= 2 && !labels[^1].All(char.IsAsciiDigit); + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/ItemMaps.cs b/src/Khaemhat.Data/CompanyDatabase/ItemMaps.cs new file mode 100644 index 0000000..2beac5d --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/ItemMaps.cs @@ -0,0 +1,86 @@ +using Khaemhat.Core.Items; +using Khaemhat.Data.Mapping; + +namespace Khaemhat.Data.CompanyDatabase; + +/// Map of to items. +public sealed class ItemMap : EntityMap +{ + /// Creates the map. + public ItemMap() + { + ToTable("items"); + Map(x => x.Code).MaxLength(30); + Map(x => x.Description).MaxLength(200); + Map(x => x.Barcode).MaxLength(20); + Map(x => x.CustomsCode).MaxLength(10); + Map(x => x.Manufacturer).MaxLength(100); + Map(x => x.Brand).MaxLength(100); + Map(x => x.RevenueAccountCode).MaxLength(20); + Map(x => x.CostAccountCode).MaxLength(20); + } +} + +/// Map of to item_uoms. +public sealed class ItemUnitMap : EntityMap +{ + /// Creates the map. + public ItemUnitMap() + { + ToTable("item_uoms"); + Map(x => x.Barcode).MaxLength(20); + } +} + +/// Map of to item_barcodes. +public sealed class ItemBarcodeMap : EntityMap +{ + /// Creates the map. + public ItemBarcodeMap() + { + ToTable("item_barcodes"); + Map(x => x.Code).MaxLength(40); + Map(x => x.Description).MaxLength(100); + } +} + +/// Map of to item_prices. +public sealed class ItemPriceMap : EntityMap +{ + /// Creates the map. + public ItemPriceMap() => ToTable("item_prices"); +} + +/// Map of to item_suppliers. +public sealed class ItemSupplierMap : EntityMap +{ + /// Creates the map. + public ItemSupplierMap() + { + ToTable("item_suppliers"); + Map(x => x.SupplierCode).MaxLength(40); + } +} + +/// Map of to item_substitutes. +public sealed class ItemSubstituteMap : EntityMap +{ + /// Creates the map. + public ItemSubstituteMap() + { + ToTable("item_substitutes"); + Map(x => x.Notes).MaxLength(200); + } +} + +/// Map of to party_item_codes. +public sealed class PartyItemCodeMap : EntityMap +{ + /// Creates the map. + public PartyItemCodeMap() + { + ToTable("party_item_codes"); + Map(x => x.Code).MaxLength(40); + Map(x => x.Description).MaxLength(200); + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_010_CreateCompanyProfile.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_010_CreateCompanyProfile.cs new file mode 100644 index 0000000..04df548 --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_010_CreateCompanyProfile.cs @@ -0,0 +1,83 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// The company data and the fiscal years with their periods (SPEC §11.1, mockup 075 and 052). +[Migration(20261111_010, "create_company_profile")] +public sealed class M20261111_010_CreateCompanyProfile : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("company_profile", t => + { + t.Id(); + t.String("legal_name", 200).NotNull(); + t.String("fiscal_name", 200); + t.String("vat_number", 28); + t.String("tax_code", 16); + t.String("rea_office", 2); + t.String("rea_number", 20); + t.Decimal("share_capital"); + t.String("shareholders", 2); + t.String("liquidation_status", 2); + t.String("address", 200); + t.String("street_number", 8); + t.String("postal_code", 10); + t.String("city", 100); + t.String("province_code", 2); + t.String("address_country", 2); + t.String("phone", 30); + t.String("email", 254); + t.String("pec", 254); + t.String("website", 200); + t.String("tax_regime", 4).NotNull(); + t.String("recipient_code", 7); + t.Int64("logo_attachment_id"); + t.Int64("default_bank_account_id"); + t.String("currency_code", 3).NotNull(); + t.String("country", 2).NotNull(); + t.String("vat_periodicity", 40).NotNull(); + t.Decimal("pro_rata_percent").NotNull(); + t.Bool("cash_vat").NotNull().Default(false); + t.Int32("fiscal_year_start_month").NotNull(); + t.String("transmitter_country", 2); + t.String("transmitter_id", 28); + t.String("intermediary_name", 200); + t.String("intermediary_tax_code", 16); + t.Text("footer_notes"); + t.AuditColumns(); + }); + + schema.CreateTable("fiscal_years", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.Date("start_date").NotNull(); + t.Date("end_date").NotNull(); + t.String("status", 40).NotNull(); + t.Int32("journal_first_page").NotNull(); + t.Int64("last_final_entry_number").NotNull(); + t.Date("last_final_entry_date"); + t.AuditColumns(); + t.Unique("ux_fiscal_years_code", "code"); + t.Unique("ux_fiscal_years_start_date", "start_date"); + }); + + schema.CreateTable("fiscal_periods", t => + { + t.Id(); + t.Int64("fiscal_year_id").NotNull(); + t.Int32("number").NotNull(); + t.Date("start_date").NotNull(); + t.Date("end_date").NotNull(); + t.String("status", 40).NotNull(); + t.AuditColumns(); + t.Unique("ux_fiscal_periods_fiscal_year_id_number", "fiscal_year_id", "number"); + t.Index("ix_fiscal_periods_start_date", "start_date"); + t.ForeignKey("fk_fiscal_periods_fiscal_year", "fiscal_year_id", "fiscal_years", ReferentialAction.Cascade); + }); + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_011_CreateGeographyAndCurrencies.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_011_CreateGeographyAndCurrencies.cs new file mode 100644 index 0000000..f52af45 --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_011_CreateGeographyAndCurrencies.cs @@ -0,0 +1,95 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// Countries, provinces, municipalities, currencies, exchange rates and units of measure (SPEC §11.1). +[Migration(20261111_011, "create_geography_and_currencies")] +public sealed class M20261111_011_CreateGeographyAndCurrencies : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("countries", t => + { + t.Id(); + t.String("code", 2).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.String("iso3", 3); + t.Bool("eu_member").NotNull().Default(false); + t.String("vat_prefix", 2); + t.String("currency_code", 3); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_countries_code", "code"); + }); + + schema.CreateTable("provinces", t => + { + t.Id(); + t.String("code", 2).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.String("region", 60); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_provinces_code", "code"); + }); + + schema.CreateTable("municipalities", t => + { + t.Id(); + t.String("code", 4).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.String("province_code", 2).NotNull(); + t.String("region", 60); + t.String("istat_code", 6); + t.String("postal_codes", 400); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_municipalities_code", "code"); + t.Index("ix_municipalities_description", "description"); + t.Index("ix_municipalities_province_code", "province_code"); + }); + + schema.CreateTable("currencies", t => + { + t.Id(); + t.String("code", 3).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.String("symbol", 5); + t.Int32("decimals").NotNull(); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_currencies_code", "code"); + }); + + schema.CreateTable("exchange_rates", t => + { + t.Id(); + t.String("currency_code", 3).NotNull(); + t.Date("rate_date").NotNull(); + t.Decimal("rate").NotNull(); + t.String("source", 10).NotNull(); + t.AuditColumns(); + t.Unique("ux_exchange_rates_currency_code_rate_date", "currency_code", "rate_date"); + }); + + schema.CreateTable("units_of_measure", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.Int32("decimals").NotNull(); + t.String("e_invoice_code", 10); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_units_of_measure_code", "code"); + }); + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_012_CreateTaxAndPaymentTables.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_012_CreateTaxAndPaymentTables.cs new file mode 100644 index 0000000..c431495 --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_012_CreateTaxAndPaymentTables.cs @@ -0,0 +1,110 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// VAT codes, payment methods and terms, bank accounts and salespeople (SPEC §11.1, mockup 076). +[Migration(20261111_012, "create_tax_and_payment_tables")] +public sealed class M20261111_012_CreateTaxAndPaymentTables : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("tax_codes", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.Decimal("rate").NotNull(); + t.String("nature", 5); + t.String("kind", 40).NotNull(); + t.String("exigibility", 40).NotNull(); + t.Decimal("non_deductible_percent").NotNull(); + t.String("legal_reference", 200); + t.Date("valid_from"); + t.Date("valid_to"); + t.String("sales_account_code", 20); + t.String("purchase_account_code", 20); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_tax_codes_code", "code"); + }); + + schema.CreateTable("payment_methods", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.String("e_invoice_code", 4).NotNull(); + t.Bool("needs_bank").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_payment_methods_code", "code"); + }); + + schema.CreateTable("payment_terms", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.Int64("payment_method_id"); + t.String("condition", 4).NotNull(); + t.Bool("vat_on_first_installment").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_payment_terms_code", "code"); + t.ForeignKey("fk_payment_terms_payment_method", "payment_method_id", "payment_methods", ReferentialAction.Restrict); + }); + + schema.CreateTable("payment_term_lines", t => + { + t.Id(); + t.Int64("payment_term_id").NotNull(); + t.Int32("number").NotNull(); + t.Int32("days").NotNull(); + t.Bool("end_of_month").NotNull().Default(false); + t.Int32("fixed_day"); + t.Decimal("percent").NotNull(); + t.AuditColumns(); + t.Unique("ux_payment_term_lines_payment_term_id_number", "payment_term_id", "number"); + t.ForeignKey("fk_payment_term_lines_payment_term", "payment_term_id", "payment_terms", ReferentialAction.Cascade); + }); + + schema.CreateTable("bank_accounts", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.String("bank_name", 100); + t.String("iban", 34); + t.String("bic", 11); + t.String("sia_code", 5); + t.String("cuc_code", 8); + t.String("account_code", 20); + t.Bool("is_default").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_bank_accounts_code", "code"); + }); + + schema.CreateTable("salespeople", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.String("email", 254); + t.String("phone", 30); + t.Decimal("commission_percent").NotNull(); + t.Bool("enasarco").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_salespeople_code", "code"); + }); + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_013_CreateLogisticsTables.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_013_CreateLogisticsTables.cs new file mode 100644 index 0000000..d643c5c --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_013_CreateLogisticsTables.cs @@ -0,0 +1,115 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// Carriers, transport tables, warehouse reasons and warehouses (SPEC §11.1). +[Migration(20261111_013, "create_logistics_tables")] +public sealed class M20261111_013_CreateLogisticsTables : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("carriers", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.String("vat_number", 28); + t.String("address", 200); + t.String("city", 100); + t.String("phone", 30); + t.String("email", 254); + t.String("register_number", 30); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_carriers_code", "code"); + }); + + schema.CreateTable("shipping_terms", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_shipping_terms_code", "code"); + }); + + schema.CreateTable("transport_means", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_transport_means_code", "code"); + }); + + schema.CreateTable("goods_appearances", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_goods_appearances_code", "code"); + }); + + schema.CreateTable("delivery_terms", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_delivery_terms_code", "code"); + }); + + schema.CreateTable("transport_reasons", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_transport_reasons_code", "code"); + }); + + schema.CreateTable("inventory_reasons", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.String("effect", 40).NotNull(); + t.Bool("affects_value").NotNull().Default(false); + t.Bool("is_transfer").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_inventory_reasons_code", "code"); + }); + + schema.CreateTable("warehouses", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.String("address", 200); + t.String("city", 100); + t.String("province_code", 2); + t.Bool("is_default").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_warehouses_code", "code"); + }); + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_014_CreateCatalogTables.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_014_CreateCatalogTables.cs new file mode 100644 index 0000000..921750a --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_014_CreateCatalogTables.cs @@ -0,0 +1,135 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// Categories, price lists, discounts, numerators, document types, cost centres and jobs (SPEC §11.1). +[Migration(20261111_014, "create_catalog_tables")] +public sealed class M20261111_014_CreateCatalogTables : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("item_categories", t => + { + t.Id(); + t.String("code", 20).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.Int64("parent_id"); + t.Int32("level").NotNull(); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_item_categories_code", "code"); + t.ForeignKey("fk_item_categories_parent", "parent_id", "item_categories", ReferentialAction.Restrict); + }); + + schema.CreateTable("party_categories", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_party_categories_code", "code"); + }); + + schema.CreateTable("price_lists", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.String("currency_code", 3).NotNull(); + t.Bool("vat_included").NotNull().Default(false); + t.Date("valid_from"); + t.Date("valid_to"); + t.Int64("base_price_list_id"); + t.Decimal("markup_percent").NotNull(); + t.Decimal("rounding_step").NotNull(); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_price_lists_code", "code"); + t.ForeignKey("fk_price_lists_base_price_list", "base_price_list_id", "price_lists", ReferentialAction.Restrict); + }); + + schema.CreateTable("discount_policies", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.String("formula", 60).NotNull(); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_discount_policies_code", "code"); + }); + + schema.CreateTable("document_numerators", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.String("kind", 40).NotNull(); + t.String("section", 10); + t.Int32("year").NotNull(); + t.String("prefix", 10); + t.String("format", 60).NotNull(); + t.Int64("last_number").NotNull(); + t.Bool("gaps_allowed").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_document_numerators_code_year", "code", "year"); + }); + + schema.CreateTable("document_types", t => + { + t.Id(); + t.String("code", 10).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.String("kind", 40).NotNull(); + t.Int64("numerator_id"); + t.Int64("inventory_reason_id"); + t.String("e_invoice_type", 4); + t.String("journal_template_code", 10); + t.String("vat_register_code", 10); + t.String("print_template", 60); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_document_types_code", "code"); + t.ForeignKey("fk_document_types_inventory_reason", "inventory_reason_id", "inventory_reasons", ReferentialAction.Restrict); + }); + + schema.CreateTable("cost_centers", t => + { + t.Id(); + t.String("code", 20).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.Int64("parent_id"); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_cost_centers_code", "code"); + t.ForeignKey("fk_cost_centers_parent", "parent_id", "cost_centers", ReferentialAction.Restrict); + }); + + schema.CreateTable("jobs", t => + { + t.Id(); + t.String("code", 20).NotNull(); + t.String("description", 100).NotNull(); + t.Bool("disabled").NotNull().Default(false); + t.Int64("party_id"); + t.Date("start_date"); + t.Date("end_date"); + t.String("status", 40).NotNull(); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_jobs_code", "code"); + }); + } +} 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/Migrations/M20261112_001_CreateParties.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261112_001_CreateParties.cs new file mode 100644 index 0000000..3c2181b --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261112_001_CreateParties.cs @@ -0,0 +1,203 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// +/// Parties and their details (SPEC §11.2, issue #41): addresses, contacts, bank accounts, sales and purchase terms and +/// fiscal data. The details go with the party; the company tables they point to cannot be deleted while used. +/// +[Migration(20261112_001, "create_parties")] +public sealed class M20261112_001_CreateParties : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("parties", t => + { + t.Id(); + t.String("code", 30).NotNull(); + t.String("previous_code", 30); + t.String("kind", 40).NotNull(); + t.Bool("is_also_supplier").NotNull().Default(false); + t.String("subject_type", 40).NotNull(); + t.String("name", 200).NotNull(); + t.String("first_name", 80); + t.String("last_name", 80); + t.String("fiscal_name", 200); + t.String("vat_number", 30); + t.String("tax_code", 30); + t.String("rea", 20); + t.Int64("category_id"); + t.String("address", 200); + t.String("street_number", 20); + t.String("postal_code", 10); + t.String("city", 100); + t.String("province", 10); + t.String("country_code", 2).NotNull(); + t.String("phone", 40); + t.String("email", 200); + t.String("pec", 200); + t.String("website", 200); + t.Int64("salesperson_id"); + t.String("language", 5).NotNull(); + t.String("currency_code", 3).NotNull(); + t.Date("since"); + t.Bool("privacy_accepted").NotNull().Default(false); + t.Bool("marketing").NotNull().Default(false); + t.Text("notes"); + t.String("vat_check", 40).NotNull(); + t.DateTimeUtc("vat_checked_at"); + t.String("customer_account_code", 20); + t.String("supplier_account_code", 20); + t.Bool("disabled").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_parties_code", "code"); + t.Index("ix_parties_name", "name"); + t.Index("ix_parties_vat_number", "vat_number"); + t.Index("ix_parties_tax_code", "tax_code"); + t.Index("ix_parties_kind", "kind"); + t.ForeignKey("fk_parties_category", "category_id", "party_categories", ReferentialAction.Restrict); + t.ForeignKey("fk_parties_salesperson", "salesperson_id", "salespeople", ReferentialAction.Restrict); + }); + + schema.CreateTable("party_addresses", t => + { + t.Id(); + t.Int64("party_id").NotNull(); + t.String("kind", 40).NotNull(); + t.String("name", 200).NotNull(); + t.String("address", 200); + t.String("street_number", 20); + t.String("postal_code", 10); + t.String("city", 100); + t.String("province", 10); + t.String("country_code", 2).NotNull(); + t.Bool("is_default").NotNull().Default(false); + t.Text("notes"); + t.AuditColumns(); + t.Index("ix_party_addresses_party", "party_id"); + t.ForeignKey("fk_party_addresses_party", "party_id", "parties", ReferentialAction.Cascade); + }); + + schema.CreateTable("party_contacts", t => + { + t.Id(); + t.Int64("party_id").NotNull(); + t.String("name", 120).NotNull(); + t.String("role", 80); + t.String("phone", 40); + t.String("mobile", 40); + t.String("email", 200); + t.Bool("is_default").NotNull().Default(false); + t.Text("notes"); + t.AuditColumns(); + t.Index("ix_party_contacts_party", "party_id"); + t.ForeignKey("fk_party_contacts_party", "party_id", "parties", ReferentialAction.Cascade); + }); + + schema.CreateTable("party_bank_accounts", t => + { + t.Id(); + t.Int64("party_id").NotNull(); + t.String("iban", 34).NotNull(); + t.String("bic", 11); + t.String("bank_name", 100); + t.String("bank_code", 10); + t.String("branch_code", 10); + t.Bool("is_default").NotNull().Default(false); + t.AuditColumns(); + t.Index("ix_party_bank_accounts_party", "party_id"); + t.ForeignKey("fk_party_bank_accounts_party", "party_id", "parties", ReferentialAction.Cascade); + }); + + schema.CreateTable("party_sales_terms", t => + { + t.Id(); + t.Int64("party_id").NotNull(); + t.Int64("price_list_id"); + t.Decimal("discount1"); + t.Decimal("discount2"); + t.Int64("payment_term_id"); + t.Int64("company_bank_account_id"); + t.Int64("carrier_id"); + t.Int64("shipping_term_id"); + t.Int64("warehouse_id"); + t.Decimal("credit_limit"); + t.Bool("blocked").NotNull().Default(false); + t.Bool("group_delivery_notes").NotNull().Default(true); + t.Int32("invoice_day"); + t.String("send_documents", 40).NotNull(); + t.String("documents_email", 200); + t.AuditColumns(); + t.Unique("ux_party_sales_terms_party", "party_id"); + t.ForeignKey("fk_party_sales_terms_party", "party_id", "parties", ReferentialAction.Cascade); + t.ForeignKey("fk_party_sales_terms_price_list", "price_list_id", "price_lists", ReferentialAction.Restrict); + t.ForeignKey("fk_party_sales_terms_payment_term", "payment_term_id", "payment_terms", ReferentialAction.Restrict); + t.ForeignKey("fk_party_sales_terms_bank_account", "company_bank_account_id", "bank_accounts", ReferentialAction.Restrict); + t.ForeignKey("fk_party_sales_terms_carrier", "carrier_id", "carriers", ReferentialAction.Restrict); + t.ForeignKey("fk_party_sales_terms_shipping_term", "shipping_term_id", "shipping_terms", ReferentialAction.Restrict); + t.ForeignKey("fk_party_sales_terms_warehouse", "warehouse_id", "warehouses", ReferentialAction.Restrict); + }); + + schema.CreateTable("party_purchase_terms", t => + { + t.Id(); + t.Int64("party_id").NotNull(); + t.Int64("payment_term_id"); + t.Int32("lead_time_days"); + t.Decimal("minimum_order"); + t.Decimal("discount"); + t.Int64("shipping_term_id"); + t.String("vat_register_code", 10); + t.String("cost_account_code", 20); + t.String("orders_email", 200); + t.AuditColumns(); + t.Unique("ux_party_purchase_terms_party", "party_id"); + t.ForeignKey("fk_party_purchase_terms_party", "party_id", "parties", ReferentialAction.Cascade); + t.ForeignKey("fk_party_purchase_terms_payment_term", "payment_term_id", "payment_terms", ReferentialAction.Restrict); + t.ForeignKey("fk_party_purchase_terms_shipping_term", "shipping_term_id", "shipping_terms", ReferentialAction.Restrict); + }); + + schema.CreateTable("party_fiscal", t => + { + t.Id(); + t.Int64("party_id").NotNull(); + t.String("recipient_code", 7); + t.String("recipient_pec", 200); + t.String("administration_reference", 20); + t.Bool("attach_pdf").NotNull().Default(true); + t.Bool("send_copy").NotNull().Default(false); + t.Bool("split_payment").NotNull().Default(false); + t.Bool("reverse_charge").NotNull().Default(false); + t.Int64("tax_code_id"); + t.String("exigibility", 1); + t.Bool("stamp_duty_charged").NotNull().Default(true); + t.Bool("withholding").NotNull().Default(false); + t.Decimal("withholding_rate"); + t.String("withholding_reason", 4); + t.String("pension_fund", 4); + t.Decimal("pension_fund_rate"); + t.Bool("enasarco").NotNull().Default(false); + t.Bool("intent_active").NotNull().Default(false); + t.String("intent_number", 40); + t.Date("intent_date"); + t.String("intent_protocol", 40); + t.Int64("intent_tax_code_id"); + t.Decimal("intent_ceiling"); + t.Decimal("intent_used").NotNull().Default(0m); + t.Date("intent_from"); + t.Date("intent_to"); + t.String("gln", 13); + t.String("eori", 17); + t.String("our_code", 40); + t.AuditColumns(); + t.Unique("ux_party_fiscal_party", "party_id"); + t.ForeignKey("fk_party_fiscal_party", "party_id", "parties", ReferentialAction.Cascade); + t.ForeignKey("fk_party_fiscal_tax_code", "tax_code_id", "tax_codes", ReferentialAction.Restrict); + t.ForeignKey("fk_party_fiscal_intent_tax_code", "intent_tax_code_id", "tax_codes", ReferentialAction.Restrict); + }); + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261112_002_CreateItems.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261112_002_CreateItems.cs new file mode 100644 index 0000000..13e69c5 --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261112_002_CreateItems.cs @@ -0,0 +1,146 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// +/// Items and their details (SPEC §11.2, issue #42): alternative units and codes, prices of the price lists and net +/// prices of the parties, suppliers, substitutes, and the codes the parties use for our items. The details go with the +/// item; an item used as a substitute or a party with prices cannot be deleted. +/// +[Migration(20261112_002, "create_items")] +public sealed class M20261112_002_CreateItems : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.AlterTable("price_lists", t => t.Bool("is_base").NotNull().Default(false)); + schema.Sql(d => "UPDATE price_lists SET is_base = " + d.Literal(true, ColumnType.Bool) + " WHERE code = 'BASE'"); + schema.CreateTable("items", t => + { + t.Id(); + t.String("code", 30).NotNull(); + t.String("kind", 40).NotNull(); + t.String("description", 200).NotNull(); + t.Text("extended_description"); + t.Int64("category_id"); + t.Int64("unit_of_measure_id"); + t.Int64("sales_tax_code_id"); + t.Int64("purchase_tax_code_id"); + t.String("barcode", 20); + t.String("customs_code", 10); + t.String("manufacturer", 100); + t.String("brand", 100); + t.Decimal("net_weight"); + t.Decimal("gross_weight"); + t.Bool("stocked").NotNull().Default(false); + t.Int64("warehouse_id"); + t.Decimal("minimum_stock"); + t.Decimal("reorder_point"); + t.Decimal("reorder_lot"); + t.Decimal("price"); + t.Decimal("standard_cost"); + t.Decimal("last_cost"); + t.Decimal("average_cost"); + t.String("revenue_account_code", 20); + t.String("cost_account_code", 20); + t.Text("notes"); + t.Bool("disabled").NotNull().Default(false); + t.DemoColumn(); + t.AuditColumns(); + t.Unique("ux_items_code", "code"); + t.Index("ix_items_description", "description"); + t.Index("ix_items_barcode", "barcode"); + t.Index("ix_items_category", "category_id"); + t.ForeignKey("fk_items_category", "category_id", "item_categories", ReferentialAction.Restrict); + t.ForeignKey("fk_items_unit", "unit_of_measure_id", "units_of_measure", ReferentialAction.Restrict); + t.ForeignKey("fk_items_sales_tax_code", "sales_tax_code_id", "tax_codes", ReferentialAction.Restrict); + t.ForeignKey("fk_items_purchase_tax_code", "purchase_tax_code_id", "tax_codes", ReferentialAction.Restrict); + t.ForeignKey("fk_items_warehouse", "warehouse_id", "warehouses", ReferentialAction.Restrict); + }); + + schema.CreateTable("item_uoms", t => + { + t.Id(); + t.Int64("item_id").NotNull(); + t.Int64("unit_of_measure_id").NotNull(); + t.Decimal("factor").NotNull().Default(1m); + t.String("barcode", 20); + t.AuditColumns(); + t.Unique("ux_item_uoms_item_unit", "item_id", "unit_of_measure_id"); + t.ForeignKey("fk_item_uoms_item", "item_id", "items", ReferentialAction.Cascade); + t.ForeignKey("fk_item_uoms_unit", "unit_of_measure_id", "units_of_measure", ReferentialAction.Restrict); + }); + + schema.CreateTable("item_barcodes", t => + { + t.Id(); + t.Int64("item_id").NotNull(); + t.String("code", 40).NotNull(); + t.String("description", 100); + t.AuditColumns(); + t.Index("ix_item_barcodes_code", "code"); + t.ForeignKey("fk_item_barcodes_item", "item_id", "items", ReferentialAction.Cascade); + }); + + schema.CreateTable("item_prices", t => + { + t.Id(); + t.Int64("item_id").NotNull(); + t.Int64("price_list_id"); + t.Int64("party_id"); + t.Decimal("price").NotNull(); + t.Date("valid_from"); + t.AuditColumns(); + t.Index("ix_item_prices_item", "item_id"); + t.Index("ix_item_prices_price_list", "price_list_id"); + t.Index("ix_item_prices_party", "party_id"); + t.ForeignKey("fk_item_prices_item", "item_id", "items", ReferentialAction.Cascade); + t.ForeignKey("fk_item_prices_price_list", "price_list_id", "price_lists", ReferentialAction.Restrict); + t.ForeignKey("fk_item_prices_party", "party_id", "parties", ReferentialAction.Restrict); + }); + + schema.CreateTable("item_suppliers", t => + { + t.Id(); + t.Int64("item_id").NotNull(); + t.Int64("party_id").NotNull(); + t.String("supplier_code", 40); + t.Decimal("price"); + t.Int32("lead_time_days"); + t.Decimal("minimum_quantity"); + t.Bool("is_default").NotNull().Default(false); + t.AuditColumns(); + t.Unique("ux_item_suppliers_item_party", "item_id", "party_id"); + t.ForeignKey("fk_item_suppliers_item", "item_id", "items", ReferentialAction.Cascade); + t.ForeignKey("fk_item_suppliers_party", "party_id", "parties", ReferentialAction.Restrict); + }); + + schema.CreateTable("item_substitutes", t => + { + t.Id(); + t.Int64("item_id").NotNull(); + t.Int64("substitute_id").NotNull(); + t.String("notes", 200); + t.AuditColumns(); + t.Unique("ux_item_substitutes_pair", "item_id", "substitute_id"); + t.ForeignKey("fk_item_substitutes_item", "item_id", "items", ReferentialAction.Cascade); + t.ForeignKey("fk_item_substitutes_substitute", "substitute_id", "items", ReferentialAction.Restrict); + }); + + schema.CreateTable("party_item_codes", t => + { + t.Id(); + t.Int64("party_id").NotNull(); + t.Int64("item_id").NotNull(); + t.String("code", 40).NotNull(); + t.String("description", 200); + t.AuditColumns(); + t.Unique("ux_party_item_codes_party_code", "party_id", "code"); + t.Index("ix_party_item_codes_item", "item_id"); + t.ForeignKey("fk_party_item_codes_party", "party_id", "parties", ReferentialAction.Cascade); + t.ForeignKey("fk_party_item_codes_item", "item_id", "items", ReferentialAction.Cascade); + }); + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/PartyMaps.cs b/src/Khaemhat.Data/CompanyDatabase/PartyMaps.cs new file mode 100644 index 0000000..a3808d5 --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/PartyMaps.cs @@ -0,0 +1,129 @@ +using Khaemhat.Core.Parties; +using Khaemhat.Data.Mapping; + +namespace Khaemhat.Data.CompanyDatabase; + +/// Map of to parties. +public sealed class PartyMap : EntityMap +{ + /// Creates the map. + public PartyMap() + { + ToTable("parties"); + Map(x => x.Code).MaxLength(30); + Map(x => x.PreviousCode).MaxLength(30); + Map(x => x.Name).MaxLength(200); + Map(x => x.FirstName).MaxLength(80); + Map(x => x.LastName).MaxLength(80); + Map(x => x.FiscalName).MaxLength(200); + Map(x => x.VatNumber).MaxLength(30); + Map(x => x.TaxCode).MaxLength(30); + Map(x => x.Rea).MaxLength(20); + Map(x => x.Address).MaxLength(200); + Map(x => x.StreetNumber).MaxLength(20); + Map(x => x.PostalCode).MaxLength(10); + Map(x => x.City).MaxLength(100); + Map(x => x.Province).MaxLength(10); + Map(x => x.CountryCode).MaxLength(2); + Map(x => x.Phone).MaxLength(40); + Map(x => x.Email).MaxLength(200); + Map(x => x.Pec).MaxLength(200); + Map(x => x.Website).MaxLength(200); + Map(x => x.Language).MaxLength(5); + Map(x => x.CurrencyCode).MaxLength(3); + Map(x => x.CustomerAccountCode).MaxLength(20); + Map(x => x.SupplierAccountCode).MaxLength(20); + } +} + +/// Map of to party_addresses. +public sealed class PartyAddressMap : EntityMap +{ + /// Creates the map. + public PartyAddressMap() + { + ToTable("party_addresses"); + Map(x => x.Name).MaxLength(200); + Map(x => x.Address).MaxLength(200); + Map(x => x.StreetNumber).MaxLength(20); + Map(x => x.PostalCode).MaxLength(10); + Map(x => x.City).MaxLength(100); + Map(x => x.Province).MaxLength(10); + Map(x => x.CountryCode).MaxLength(2); + } +} + +/// Map of to party_contacts. +public sealed class PartyContactMap : EntityMap +{ + /// Creates the map. + public PartyContactMap() + { + ToTable("party_contacts"); + Map(x => x.Name).MaxLength(120); + Map(x => x.Role).MaxLength(80); + Map(x => x.Phone).MaxLength(40); + Map(x => x.Mobile).MaxLength(40); + Map(x => x.Email).MaxLength(200); + } +} + +/// Map of to party_bank_accounts. +public sealed class PartyBankAccountMap : EntityMap +{ + /// Creates the map. + public PartyBankAccountMap() + { + ToTable("party_bank_accounts"); + Map(x => x.Iban).MaxLength(34); + Map(x => x.Bic).MaxLength(11); + Map(x => x.BankName).MaxLength(100); + Map(x => x.BankCode).MaxLength(10); + Map(x => x.BranchCode).MaxLength(10); + } +} + +/// Map of to party_sales_terms. +public sealed class PartySalesTermsMap : EntityMap +{ + /// Creates the map. + public PartySalesTermsMap() + { + ToTable("party_sales_terms"); + Map(x => x.DocumentsEmail).MaxLength(200); + } +} + +/// Map of to party_purchase_terms. +public sealed class PartyPurchaseTermsMap : EntityMap +{ + /// Creates the map. + public PartyPurchaseTermsMap() + { + ToTable("party_purchase_terms"); + Map(x => x.VatRegisterCode).MaxLength(10); + Map(x => x.CostAccountCode).MaxLength(20); + Map(x => x.OrdersEmail).MaxLength(200); + } +} + +/// Map of to party_fiscal. +public sealed class PartyFiscalMap : EntityMap +{ + /// Creates the map. + public PartyFiscalMap() + { + ToTable("party_fiscal"); + Map(x => x.RecipientCode).MaxLength(7); + Map(x => x.RecipientPec).MaxLength(200); + Map(x => x.AdministrationReference).MaxLength(20); + Map(x => x.Exigibility).MaxLength(1); + Map(x => x.WithholdingReason).MaxLength(4); + Map(x => x.PensionFund).MaxLength(4); + Map(x => x.IntentNumber).MaxLength(40); + Map(x => x.IntentProtocol).MaxLength(40); + Map(x => x.Gln).MaxLength(13); + Map(x => x.Eori).MaxLength(17); + Map(x => x.OurCode).MaxLength(40); + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/TableMaps.cs b/src/Khaemhat.Data/CompanyDatabase/TableMaps.cs new file mode 100644 index 0000000..32419c1 --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/TableMaps.cs @@ -0,0 +1,448 @@ +using Khaemhat.Core.Tables; +using Khaemhat.Data.Mapping; + +namespace Khaemhat.Data.CompanyDatabase; + +/// Map of to company_profile. +public sealed class CompanyProfileMap : EntityMap +{ + /// Creates the map. + public CompanyProfileMap() + { + ToTable("company_profile"); + Map(x => x.LegalName).MaxLength(200); + Map(x => x.FiscalName).MaxLength(200); + Map(x => x.VatNumber).MaxLength(28); + Map(x => x.TaxCode).MaxLength(16); + Map(x => x.ReaOffice).MaxLength(2); + Map(x => x.ReaNumber).MaxLength(20); + Map(x => x.Shareholders).MaxLength(2); + Map(x => x.LiquidationStatus).MaxLength(2); + Map(x => x.Address).MaxLength(200); + Map(x => x.StreetNumber).MaxLength(8); + Map(x => x.PostalCode).MaxLength(10); + Map(x => x.City).MaxLength(100); + Map(x => x.ProvinceCode).MaxLength(2); + Map(x => x.AddressCountry).MaxLength(2); + Map(x => x.Phone).MaxLength(30); + Map(x => x.Email).MaxLength(254); + Map(x => x.Pec).MaxLength(254); + Map(x => x.Website).MaxLength(200); + Map(x => x.TaxRegime).MaxLength(4); + Map(x => x.RecipientCode).MaxLength(7); + Map(x => x.CurrencyCode).MaxLength(3); + Map(x => x.Country).MaxLength(2); + Map(x => x.TransmitterCountry).MaxLength(2); + Map(x => x.TransmitterId).MaxLength(28); + Map(x => x.IntermediaryName).MaxLength(200); + Map(x => x.IntermediaryTaxCode).MaxLength(16); + } +} + +/// Map of to fiscal_years. +public sealed class FiscalYearMap : EntityMap +{ + /// Creates the map. + public FiscalYearMap() + { + ToTable("fiscal_years"); + Map(x => x.Code).MaxLength(10); + } +} + +/// Map of to fiscal_periods. +public sealed class FiscalPeriodMap : EntityMap +{ + /// Creates the map. + public FiscalPeriodMap() + { + ToTable("fiscal_periods"); + } +} + +/// Map of to countries. +public sealed class CountryMap : EntityMap +{ + /// Creates the map. + public CountryMap() + { + ToTable("countries"); + Map(x => x.Code).MaxLength(2); + Map(x => x.Description).MaxLength(100); + Map(x => x.Iso3).MaxLength(3); + Map(x => x.VatPrefix).MaxLength(2); + Map(x => x.CurrencyCode).MaxLength(3); + } +} + +/// Map of to provinces. +public sealed class ProvinceMap : EntityMap +{ + /// Creates the map. + public ProvinceMap() + { + ToTable("provinces"); + Map(x => x.Code).MaxLength(2); + Map(x => x.Description).MaxLength(100); + Map(x => x.Region).MaxLength(60); + } +} + +/// Map of to municipalities. +public sealed class MunicipalityMap : EntityMap +{ + /// Creates the map. + public MunicipalityMap() + { + ToTable("municipalities"); + Map(x => x.Code).MaxLength(4); + Map(x => x.Description).MaxLength(100); + Map(x => x.ProvinceCode).MaxLength(2); + Map(x => x.Region).MaxLength(60); + Map(x => x.IstatCode).MaxLength(6); + Map(x => x.PostalCodes).MaxLength(400); + } +} + +/// Map of to currencies. +public sealed class CurrencyMap : EntityMap +{ + /// Creates the map. + public CurrencyMap() + { + ToTable("currencies"); + Map(x => x.Code).MaxLength(3); + Map(x => x.Description).MaxLength(100); + Map(x => x.Symbol).MaxLength(5); + } +} + +/// Map of to exchange_rates. +public sealed class ExchangeRateMap : EntityMap +{ + /// Creates the map. + public ExchangeRateMap() + { + ToTable("exchange_rates"); + Map(x => x.CurrencyCode).MaxLength(3); + Map(x => x.Source).MaxLength(10); + } +} + +/// Map of to units_of_measure. +public sealed class UnitOfMeasureMap : EntityMap +{ + /// Creates the map. + public UnitOfMeasureMap() + { + ToTable("units_of_measure"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + Map(x => x.EInvoiceCode).MaxLength(10); + } +} + +/// Map of to tax_codes. +public sealed class TaxCodeMap : EntityMap +{ + /// Creates the map. + public TaxCodeMap() + { + ToTable("tax_codes"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + Map(x => x.Nature).MaxLength(5); + Map(x => x.LegalReference).MaxLength(200); + Map(x => x.SalesAccountCode).MaxLength(20); + Map(x => x.PurchaseAccountCode).MaxLength(20); + } +} + +/// Map of to payment_methods. +public sealed class PaymentMethodMap : EntityMap +{ + /// Creates the map. + public PaymentMethodMap() + { + ToTable("payment_methods"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + Map(x => x.EInvoiceCode).MaxLength(4); + } +} + +/// Map of to payment_terms. +public sealed class PaymentTermMap : EntityMap +{ + /// Creates the map. + public PaymentTermMap() + { + ToTable("payment_terms"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + Map(x => x.Condition).MaxLength(4); + } +} + +/// Map of to payment_term_lines. +public sealed class PaymentTermLineMap : EntityMap +{ + /// Creates the map. + public PaymentTermLineMap() + { + ToTable("payment_term_lines"); + } +} + +/// Map of to bank_accounts. +public sealed class BankAccountMap : EntityMap +{ + /// Creates the map. + public BankAccountMap() + { + ToTable("bank_accounts"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + Map(x => x.BankName).MaxLength(100); + Map(x => x.Iban).MaxLength(34); + Map(x => x.Bic).MaxLength(11); + Map(x => x.SiaCode).MaxLength(5); + Map(x => x.CucCode).MaxLength(8); + Map(x => x.AccountCode).MaxLength(20); + } +} + +/// Map of to salespeople. +public sealed class SalespersonMap : EntityMap +{ + /// Creates the map. + public SalespersonMap() + { + ToTable("salespeople"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + Map(x => x.Email).MaxLength(254); + Map(x => x.Phone).MaxLength(30); + } +} + +/// Map of to carriers. +public sealed class CarrierMap : EntityMap +{ + /// Creates the map. + public CarrierMap() + { + ToTable("carriers"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + Map(x => x.VatNumber).MaxLength(28); + Map(x => x.Address).MaxLength(200); + Map(x => x.City).MaxLength(100); + Map(x => x.Phone).MaxLength(30); + Map(x => x.Email).MaxLength(254); + Map(x => x.RegisterNumber).MaxLength(30); + } +} + +/// Map of to shipping_terms. +public sealed class ShippingTermMap : EntityMap +{ + /// Creates the map. + public ShippingTermMap() + { + ToTable("shipping_terms"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + } +} + +/// Map of to transport_means. +public sealed class TransportMeanMap : EntityMap +{ + /// Creates the map. + public TransportMeanMap() + { + ToTable("transport_means"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + } +} + +/// Map of to goods_appearances. +public sealed class GoodsAppearanceMap : EntityMap +{ + /// Creates the map. + public GoodsAppearanceMap() + { + ToTable("goods_appearances"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + } +} + +/// Map of to delivery_terms. +public sealed class DeliveryTermMap : EntityMap +{ + /// Creates the map. + public DeliveryTermMap() + { + ToTable("delivery_terms"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + } +} + +/// Map of to transport_reasons. +public sealed class TransportReasonMap : EntityMap +{ + /// Creates the map. + public TransportReasonMap() + { + ToTable("transport_reasons"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + } +} + +/// Map of to inventory_reasons. +public sealed class InventoryReasonMap : EntityMap +{ + /// Creates the map. + public InventoryReasonMap() + { + ToTable("inventory_reasons"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + } +} + +/// Map of to warehouses. +public sealed class WarehouseMap : EntityMap +{ + /// Creates the map. + public WarehouseMap() + { + ToTable("warehouses"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + Map(x => x.Address).MaxLength(200); + Map(x => x.City).MaxLength(100); + Map(x => x.ProvinceCode).MaxLength(2); + } +} + +/// Map of to item_categories. +public sealed class ItemCategoryMap : EntityMap +{ + /// Creates the map. + public ItemCategoryMap() + { + ToTable("item_categories"); + Map(x => x.Code).MaxLength(20); + Map(x => x.Description).MaxLength(100); + } +} + +/// Map of to party_categories. +public sealed class PartyCategoryMap : EntityMap +{ + /// Creates the map. + public PartyCategoryMap() + { + ToTable("party_categories"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + } +} + +/// Map of to price_lists. +public sealed class PriceListMap : EntityMap +{ + /// Creates the map. + public PriceListMap() + { + ToTable("price_lists"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + Map(x => x.CurrencyCode).MaxLength(3); + } +} + +/// Map of to discount_policies. +public sealed class DiscountPolicyMap : EntityMap +{ + /// Creates the map. + public DiscountPolicyMap() + { + ToTable("discount_policies"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + Map(x => x.Formula).MaxLength(60); + } +} + +/// Map of to document_numerators. +public sealed class DocumentNumeratorMap : EntityMap +{ + /// Creates the map. + public DocumentNumeratorMap() + { + ToTable("document_numerators"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + Map(x => x.Section).MaxLength(10); + Map(x => x.Prefix).MaxLength(10); + Map(x => x.Format).MaxLength(60); + } +} + +/// Map of to document_types. +public sealed class DocumentTypeMap : EntityMap +{ + /// Creates the map. + public DocumentTypeMap() + { + ToTable("document_types"); + Map(x => x.Code).MaxLength(10); + Map(x => x.Description).MaxLength(100); + Map(x => x.EInvoiceType).MaxLength(4); + Map(x => x.JournalTemplateCode).MaxLength(10); + Map(x => x.VatRegisterCode).MaxLength(10); + Map(x => x.PrintTemplate).MaxLength(60); + } +} + +/// Map of to cost_centers. +public sealed class CostCenterMap : EntityMap +{ + /// Creates the map. + public CostCenterMap() + { + ToTable("cost_centers"); + Map(x => x.Code).MaxLength(20); + Map(x => x.Description).MaxLength(100); + } +} + +/// Map of to jobs. +public sealed class JobMap : EntityMap +{ + /// Creates the map. + public JobMap() + { + ToTable("jobs"); + Map(x => x.Code).MaxLength(20); + 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/Calendar.cs b/src/Khaemhat.Fiscal.Abstractions/Calendar.cs new file mode 100644 index 0000000..1c68082 --- /dev/null +++ b/src/Khaemhat.Fiscal.Abstractions/Calendar.cs @@ -0,0 +1,71 @@ +using Khaemhat.Core.Tax; + +namespace Khaemhat.Fiscal.Abstractions; + +/// A tax period: a month or a quarter of a year. +/// The year. +/// The month (1-12) or the quarter (1-4). +/// Monthly or quarterly. +/// The first day. +/// The last day. +public sealed record TaxPeriod(int Year, int Number, VatPeriodicity Periodicity, DateOnly Start, DateOnly End) +{ + /// The period of a periodicity that contains a date. + /// The date. + /// Monthly or quarterly. + /// The period. + public static TaxPeriod Containing(DateOnly date, VatPeriodicity periodicity) => + periodicity == VatPeriodicity.Monthly + ? Of(date.Year, date.Month, periodicity) + : Of(date.Year, ((date.Month - 1) / 3) + 1, periodicity); + + /// A period by number. + /// The year. + /// The month (1-12) or the quarter (1-4). + /// Monthly or quarterly. + /// The period. + public static TaxPeriod Of(int year, int number, VatPeriodicity periodicity) + { + var months = periodicity == VatPeriodicity.Monthly ? 1 : 3; + ArgumentOutOfRangeException.ThrowIfLessThan(number, 1); + ArgumentOutOfRangeException.ThrowIfGreaterThan(number, 12 / months); + var start = new DateOnly(year, ((number - 1) * months) + 1, 1); + return new TaxPeriod(year, number, periodicity, start, start.AddMonths(months).AddDays(-1)); + } + + /// Every period of a year. + /// The year. + /// Monthly or quarterly. + /// 12 months or 4 quarters. + public static IReadOnlyList OfYear(int year, VatPeriodicity periodicity) => + [.. Enumerable.Range(1, periodicity == VatPeriodicity.Monthly ? 12 : 4).Select(n => Of(year, n, periodicity))]; + + /// Whether a date falls in the period. + /// The date. + /// inside the period. + public bool Contains(DateOnly date) => date >= Start && date <= End; +} + +/// Tax deadlines and the days on which they move. +public interface IFiscalCalendar +{ + /// The day by which the VAT of a period must be paid, already moved past holidays. + /// The period. + /// The due date. + DateOnly VatPaymentDue(TaxPeriod period); + + /// The interest added to the VAT of a period, in percent (Italy: 1% for quarterly payers). + /// Monthly or quarterly. + /// The rate in percent. + decimal VatInterestRate(VatPeriodicity periodicity); + + /// Whether no tax payment can fall on a day (weekend or public holiday). + /// The day. + /// for a non-working day. + bool IsNonWorkingDay(DateOnly day); + + /// The day itself, or the next working day if it is not one. + /// The day. + /// A working day. + DateOnly NextWorkingDay(DateOnly day); +} diff --git a/src/Khaemhat.Fiscal.Abstractions/CodeList.cs b/src/Khaemhat.Fiscal.Abstractions/CodeList.cs new file mode 100644 index 0000000..d67f267 --- /dev/null +++ b/src/Khaemhat.Fiscal.Abstractions/CodeList.cs @@ -0,0 +1,71 @@ +namespace Khaemhat.Fiscal.Abstractions; + +/// One code of an official code list, such as TD01 or MP05. +/// The code as written in files and messages. +/// The official description, in the country's language. +/// Kept to read old documents; not accepted on new ones. +public sealed record CodeListEntry(string Code, string Description, bool Obsolete = false); + +/// An official code list of a country (document types, payment methods, tax natures...). +public sealed class CodeList +{ + private readonly Dictionary _byCode; + + /// Creates the list. + /// A stable name, such as DocumentTypes. + /// The entries in their official order; codes are unique, compared without case. + public CodeList(string name, IEnumerable entries) + { + ArgumentException.ThrowIfNullOrWhiteSpace(name); + ArgumentNullException.ThrowIfNull(entries); + Name = name; + Entries = [.. entries]; + _byCode = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var entry in Entries) + { + if (!_byCode.TryAdd(entry.Code, entry)) + { + throw new ArgumentException($"Code '{entry.Code}' appears twice in {name}.", nameof(entries)); + } + } + } + + /// The name of the list. + public string Name { get; } + + /// Every entry, obsolete ones included, in the official order. + public IReadOnlyList Entries { get; } + + /// The entries accepted on new documents. + public IEnumerable Active => Entries.Where(e => !e.Obsolete); + + /// An entry by code, obsolete ones included. + /// The code, compared without case. + /// The entry, or . + public CodeListEntry? Find(string? code) => + code is not null && _byCode.TryGetValue(code.Trim(), out var entry) ? entry : null; + + /// Whether a code exists and is accepted on new documents. + /// The code. + /// for an active code. + public bool IsActive(string? code) => Find(code) is { Obsolete: false }; +} + +/// How serious a is. +public enum FiscalProblemSeverity +{ + /// The record cannot be saved. + Error = 0, + + /// The record can be saved, but the user should check it. + Warning = 1, +} + +/// +/// A rule of the country that a record breaks. is a stable key (such as +/// fiscal.tax.nature-required) that the interface translates; names the property at fault. +/// +/// The property name, such as Nature. +/// The problem code. +/// Error or warning. +public sealed record FiscalProblem(string Field, string Code, FiscalProblemSeverity Severity = FiscalProblemSeverity.Error); diff --git a/src/Khaemhat.Fiscal.Abstractions/Features.cs b/src/Khaemhat.Fiscal.Abstractions/Features.cs new file mode 100644 index 0000000..2f5cbc2 --- /dev/null +++ b/src/Khaemhat.Fiscal.Abstractions/Features.cs @@ -0,0 +1,273 @@ +using Khaemhat.Core.Accounting; +using Khaemhat.Core.Tax; + +namespace Khaemhat.Fiscal.Abstractions; + +// The optional features of a country pack. Each interface starts with what the current milestone needs and grows with +// the milestone that uses it (writer and reader of e-invoices in M9, statements in M10...), see ADR 0025. + +/// The country's electronic invoice format: version and code lists (Italy: FatturaPA). +public interface IEInvoiceFormat +{ + /// The name of the format, such as FatturaPA. + string Name { get; } + + /// The version of the official technical specifications that this pack follows. + string SpecVersion { get; } + + /// The transmission formats (Italy: FPR12, FPA12, FSM10). + CodeList TransmissionFormats { get; } + + /// The document types (Italy: TD01...). + CodeList DocumentTypes { get; } + + /// The payment methods (Italy: MP01...). + CodeList PaymentMethods { get; } + + /// The payment conditions (Italy: TP01...). + CodeList PaymentConditions { get; } + + /// The tax regimes of the seller (Italy: RF01...). + CodeList TaxRegimes { get; } +} + +/// A kind of withholding tax the company applies or suffers. +/// A stable code, such as PROF. +/// The description. +/// The rate in percent. +/// The share of the amount the rate applies to, in percent. +/// The tax payment code (Italy: F24 1040). +/// The type written in the e-invoice (Italy: RT01). +/// The default reason written in the e-invoice (Italy: A). +public sealed record WithholdingKind( + string Code, + string Description, + decimal Rate, + decimal TaxableBasePercent, + string PaymentCode, + string InvoiceType, + string PaymentReason); + +/// Withholding taxes and social security funds. +public interface IWithholdingRules +{ + /// The usual kinds of withholding. + IReadOnlyList Kinds { get; } + + /// The withholding types of the e-invoice (Italy: RT01...). + CodeList InvoiceTypes { get; } + + /// The payment reasons of the e-invoice (Italy: A, B... ZO). + CodeList PaymentReasons { get; } + + /// The social security funds (Italy: TC01...). + CodeList SocialSecurityFunds { get; } + + /// The tax withheld on an amount. + /// The amount the withholding is computed on (fee, commission). + /// The kind of withholding. + /// The withheld tax, rounded to the cent. + decimal Compute(decimal amount, WithholdingKind kind); +} + +/// Depreciation rules for fixed assets. +public interface IFixedAssetRules +{ + /// The share of the yearly rate allowed in the first year (Italy: 0.5). + decimal FirstYearFactor { get; } + + /// The cost up to which an asset may be expensed in one year (Italy: 516.46). + decimal LowValueThreshold { get; } + + /// The tax limit on the cost of a passenger car (Italy: 18,075.99). + decimal PassengerCarCostLimit { get; } + + /// The depreciation of one year, never more than what is left to depreciate. + /// The depreciable cost. + /// The yearly rate in percent. + /// Whether this is the first year of use. + /// The depreciation of the previous years. + /// The depreciation, rounded to the cent. + decimal YearlyDepreciation(decimal cost, decimal ratePercent, bool firstYear, decimal alreadyDepreciated); +} + +/// A tax payment code of the country's payment form (Italy: codice tributo F24). +/// The code, such as 6001. +/// What it pays. +public sealed record TaxPaymentCode(string Code, string Description); + +/// The country's tax payment form (Italy: F24); the file export arrives with the VAT settlement (M7). +public interface ITaxPaymentFormExporter +{ + /// The name of the form, such as F24. + string FormName { get; } + + /// The payment codes the product uses. + IReadOnlyList Codes { get; } + + /// The code for the VAT of a period. + /// The period. + /// The payment code. + string VatCode(TaxPeriod period); + + /// The code for the VAT advance of December. + /// Monthly or quarterly. + /// The payment code. + string VatAdvanceCode(VatPeriodicity periodicity); + + /// The code for the stamp duty on e-invoices of a quarter. + /// The quarter, 1-4. + /// The payment code. + string StampDutyCode(int quarter); +} + +/// Which statement a schema line belongs to. +public enum FinancialStatementKind +{ + /// Balance sheet (Italy: art. 2424 c.c.). + BalanceSheet = 0, + + /// Income statement (Italy: art. 2425 c.c.). + IncomeStatement = 1, +} + +/// A line of the legal financial statements. +/// The code of the line, such as B.II.1. +/// The legal description. +/// The line it adds up into, if any. +/// Whether accounts can be mapped to it. +public sealed record FinancialStatementLine(string Code, string Description, string? ParentCode, bool Postable); + +/// The legal schema of the financial statements (arrives with the statements, M10). +public interface IFinancialStatementsSchema +{ + /// The lines of a statement, in legal order. + /// The statement. + /// The lines. + IReadOnlyList Lines(FinancialStatementKind kind); +} + +/// An account of the country's model chart of accounts. +/// The hierarchical code, such as 01.01.001. +/// The description. +/// The parent account, if any. +/// The statement it ends up in. +/// The financial statement line it maps to, if any. +public sealed record AccountTemplate(string Code, string Description, string? ParentCode, AccountNature Nature, string? StatementLine); + +/// The model chart of accounts loaded into a new company (arrives with the ledger, M7). +public interface IChartOfAccountsTemplate +{ + /// The name of the model, such as PMI standard. + string Name { get; } + + /// The accounts, parents before children. + IReadOnlyList Accounts { get; } +} + +/// A line of an Intrastat return. +/// The country of the counterparty. +/// The VAT number of the counterparty, without country prefix. +/// The amount in euro. +/// The combined nomenclature code (goods) or CPA code (services). +/// The nature of the transaction. +public sealed record IntrastatLine(string CountryCode, string VatNumber, decimal Amount, string? NomenclatureCode, string? TransactionNature); + +/// An Intrastat return of a period. +/// The form, such as INTRA-1 bis. +/// The period. +/// The lines. +public sealed record IntrastatReturn(string Form, TaxPeriod Period, IReadOnlyList Lines); + +/// Writes Intrastat returns in the customs format (arrives with Intrastat, M10). +public interface IIntrastatExporter +{ + /// The forms the exporter writes. + IReadOnlyList Forms { get; } + + /// Writes a return. + /// The return. + /// The stream to write to. + /// Cancels the write. + /// A task that completes when the file is written. + Task WriteAsync(IntrastatReturn intrastatReturn, Stream output, CancellationToken cancellationToken); +} + +/// A payment method of the base data. +/// The code. +/// The description. +/// The code of the e-invoice format. +/// Whether a bank is needed (transfer, bank receipt, direct debit). +public sealed record PaymentMethodTemplate(string Code, string Description, string EInvoiceCode, bool NeedsBank); + +/// An installment of payment terms of the base data. +/// Days from the document date. +/// Whether the due date moves to the end of the month. +/// Share of the amount, in percent. +public sealed record InstallmentTemplate(int Days, bool EndOfMonth, decimal Percent); + +/// Payment terms of the base data. +/// The code. +/// The description. +/// The payment method (a ). +/// The condition of the e-invoice format (installments, full, advance). +/// The installments. +public sealed record PaymentTermTemplate(string Code, string Description, string PaymentMethodCode, string Condition, IReadOnlyList Installments); + +/// A document type of the base data. +/// The code. +/// The description. +/// The family. +/// The numerator of the base data (FAT, DDT...), if the document is numbered by the company. +/// The warehouse reason of the base data (SCA, CAR...), if the document moves goods. +/// The type of the e-invoice format, if the document is sent electronically. +public sealed record DocumentTypeTemplate( + string Code, string Description, Khaemhat.Core.Tables.NumeratorKind Kind, string? NumeratorCode, string? InventoryReasonCode, string? EInvoiceType); + +/// +/// The rows of the base tables that depend on the country's rules (SPEC §14): payment methods and terms with the codes +/// of the e-invoice format, and document types with their electronic type. The rest of the base data is the same in +/// every country. +/// +public interface IBaseTablesTemplate +{ + /// The payment methods. + IReadOnlyList PaymentMethods { get; } + + /// The payment terms. + IReadOnlyList PaymentTerms { get; } + + /// The document types. + IReadOnlyList DocumentTypes { get; } +} + +/// A province (or equivalent first-level area) of the country's official list. +/// The abbreviation, such as TO. +/// The name. +/// The region. +public sealed record ProvinceTemplate(string Code, string Name, string Region); + +/// A municipality of the country's official list. +/// The code used by the tax rules (the Italian cadastral code, such as L219). +/// The name. +/// The province (a ). +/// The region. +/// The code of the national statistics office, if any. +/// The postal codes, comma separated, when the list has them. +public sealed record MunicipalityTemplate(string Code, string Name, string ProvinceCode, string Region, string? StatisticalCode, string? PostalCodes); + +/// +/// The official list of provinces and municipalities shipped with the pack, loaded into the base tables (ADR 0026, +/// ADR 0028). Like the rest of the base data it only adds the codes a company is missing. +/// +public interface IPlaceDirectory +{ + /// Where the list comes from and its date, shown in the documentation and the logs. + string Source { get; } + + /// The provinces. + IReadOnlyList Provinces { get; } + + /// The municipalities. + IReadOnlyList Municipalities { get; } +} diff --git a/src/Khaemhat.Fiscal.Abstractions/FiscalPackCatalog.cs b/src/Khaemhat.Fiscal.Abstractions/FiscalPackCatalog.cs new file mode 100644 index 0000000..730fec5 --- /dev/null +++ b/src/Khaemhat.Fiscal.Abstractions/FiscalPackCatalog.cs @@ -0,0 +1,77 @@ +namespace Khaemhat.Fiscal.Abstractions; + +/// +/// The country packs registered at start-up, found by country code. The composition root registers the concrete packs; +/// application code receives this catalog and never names a country's implementation. +/// +public sealed class FiscalPackCatalog +{ + private readonly Dictionary _byCountry; + + /// Creates the catalog. + /// The packs; two packs for the same country are a configuration error. + public FiscalPackCatalog(IEnumerable packs) + { + ArgumentNullException.ThrowIfNull(packs); + _byCountry = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var pack in packs) + { + if (!_byCountry.TryAdd(pack.CountryCode, pack)) + { + throw new ArgumentException($"Two fiscal packs for country '{pack.CountryCode}'.", nameof(packs)); + } + } + + Packs = [.. _byCountry.Values.OrderBy(p => p.CountryCode, StringComparer.Ordinal)]; + } + + /// Every registered pack, by country code. + public IReadOnlyList Packs { get; } + + /// The pack of a country. + /// ISO 3166-1 alpha-2 code, case-insensitive. + /// The pack. + /// No pack for that country. + public IFiscalPack ForCountry(string? countryCode) => + TryForCountry(countryCode, out var pack) ? pack : throw new FiscalPackNotFoundException(countryCode ?? string.Empty); + + /// The pack of a country, if registered. + /// ISO 3166-1 alpha-2 code, case-insensitive. + /// The pack, when found. + /// Whether a pack was found. + public bool TryForCountry(string? countryCode, out IFiscalPack pack) + { + if (!string.IsNullOrWhiteSpace(countryCode) && _byCountry.TryGetValue(countryCode.Trim(), out var found)) + { + pack = found; + return true; + } + + pack = null!; + return false; + } +} + +/// No fiscal pack is registered for the country of the company. +public sealed class FiscalPackNotFoundException : Exception +{ + /// Creates the exception. + public FiscalPackNotFoundException() + : this(string.Empty) + { + } + + /// Creates the exception. + /// The country without a pack. + public FiscalPackNotFoundException(string countryCode) + : base($"No fiscal pack for country '{countryCode}'.") => CountryCode = countryCode; + + /// Creates the exception. + /// The message. + /// The cause. + public FiscalPackNotFoundException(string message, Exception innerException) + : base(message, innerException) => CountryCode = string.Empty; + + /// The country without a pack. + public string CountryCode { get; } +} diff --git a/src/Khaemhat.Fiscal.Abstractions/IFiscalPack.cs b/src/Khaemhat.Fiscal.Abstractions/IFiscalPack.cs new file mode 100644 index 0000000..abe0cf9 --- /dev/null +++ b/src/Khaemhat.Fiscal.Abstractions/IFiscalPack.cs @@ -0,0 +1,157 @@ +namespace Khaemhat.Fiscal.Abstractions; + +/// +/// Everything a country's tax rules contribute (SPEC §1.10, §3, ADR 0007). The rest of the product talks to these +/// interfaces only; the country's pack is chosen by company_profile.country through . +/// +/// +/// Taxes and a calendar exist everywhere, so they are properties. The other features (e-invoicing, withholding taxes, +/// Intrastat...) depend on the country and on the milestone that delivers them: ask for them with +/// or . +/// +public interface IFiscalPack +{ + /// ISO 3166-1 alpha-2 code of the country, such as IT. + string CountryCode { get; } + + /// The name of the country in the interface language. + string Name { get; } + + /// The version of the pack's data (code lists, base tables), such as IT 2026.2. + string DataVersion { get; } + + /// Tax natures, base tax codes and their rules. + ITaxCodeCatalog TaxCodes { get; } + + /// Tax computation and rounding. + ITaxEngine TaxEngine { get; } + + /// Tax periods, deadlines and holidays. + IFiscalCalendar Calendar { get; } + + /// A feature of the pack, or if the country (or this version) has none. + /// The feature interface, such as . + /// The feature, or . + T? GetFeature() + where T : class; +} + +/// Helpers over . +public static class FiscalPackExtensions +{ + /// A feature the caller cannot work without. + /// The feature interface. + /// The pack. + /// The feature. + /// The pack has no such feature. + public static T Require(this IFiscalPack pack) + where T : class + { + ArgumentNullException.ThrowIfNull(pack); + return pack.GetFeature() ?? throw new FiscalFeatureNotAvailableException(pack.CountryCode, typeof(T).Name); + } + + /// Whether the pack has a feature. + /// The feature interface. + /// The pack. + /// if returns it. + public static bool Supports(this IFiscalPack pack) + where T : class + { + ArgumentNullException.ThrowIfNull(pack); + return pack.GetFeature() is not null; + } +} + +/// +/// Base class for country packs: the three mandatory parts plus a table of optional features registered with +/// . +/// +public abstract class FiscalPackBase : IFiscalPack +{ + private readonly Dictionary _features = []; + + /// + public abstract string CountryCode { get; } + + /// + public abstract string Name { get; } + + /// + public abstract string DataVersion { get; } + + /// + public abstract ITaxCodeCatalog TaxCodes { get; } + + /// + public abstract ITaxEngine TaxEngine { get; } + + /// + public abstract IFiscalCalendar Calendar { get; } + + /// + public T? GetFeature() + where T : class + { + object? feature = typeof(T) == typeof(ITaxCodeCatalog) ? TaxCodes + : typeof(T) == typeof(ITaxEngine) ? TaxEngine + : typeof(T) == typeof(IFiscalCalendar) ? Calendar + : _features.GetValueOrDefault(typeof(T)); + return feature as T; + } + + /// Registers an optional feature; call it from the constructor of the pack. + /// The feature interface. + /// The implementation. + protected void AddFeature(T feature) + where T : class + { + ArgumentNullException.ThrowIfNull(feature); + _features[typeof(T)] = feature; + } +} + +/// A feature the country's pack does not provide (yet). +public sealed class FiscalFeatureNotAvailableException : Exception +{ + /// Creates the exception. + public FiscalFeatureNotAvailableException() + : this(string.Empty, string.Empty) + { + } + + /// Creates the exception. + /// The message. + public FiscalFeatureNotAvailableException(string message) + : base(message) + { + CountryCode = string.Empty; + Feature = string.Empty; + } + + /// Creates the exception. + /// The message. + /// The cause. + public FiscalFeatureNotAvailableException(string message, Exception innerException) + : base(message, innerException) + { + CountryCode = string.Empty; + Feature = string.Empty; + } + + /// Creates the exception. + /// The country of the pack. + /// The name of the missing feature interface. + public FiscalFeatureNotAvailableException(string countryCode, string feature) + : base($"The fiscal pack for '{countryCode}' has no {feature}.") + { + CountryCode = countryCode; + Feature = feature; + } + + /// The country of the pack. + public string CountryCode { get; } + + /// The name of the missing feature interface. + public string Feature { get; } +} diff --git a/src/Khaemhat.Fiscal.Abstractions/Identifiers.cs b/src/Khaemhat.Fiscal.Abstractions/Identifiers.cs new file mode 100644 index 0000000..ed657e2 --- /dev/null +++ b/src/Khaemhat.Fiscal.Abstractions/Identifiers.cs @@ -0,0 +1,103 @@ +namespace Khaemhat.Fiscal.Abstractions; + +/// The sex written in a personal tax code. +public enum PersonSex +{ + /// Male. + Male = 0, + + /// Female. + Female = 1, +} + +/// What a personal tax code is computed from. +/// The surname. +/// The given name (all given names, as in the registry). +/// The date of birth. +/// The sex. +/// The code of the place of birth (Italy: cadastral code of the municipality, or Z... for a foreign country). +public sealed record PersonalTaxCodeData(string Surname, string GivenName, DateOnly BirthDate, PersonSex Sex, string BirthPlaceCode); + +/// What can be read back from a personal tax code. +/// The date of birth (century guessed from the reference date). +/// The sex. +/// The code of the place of birth. +public sealed record PersonalTaxCodeInfo(DateOnly BirthDate, PersonSex Sex, string BirthPlaceCode); + +/// Who receives an e-invoice, for the recipient code rules. +public enum RecipientKind +{ + /// A business with its own channel, or without (then the default code). + Business = 0, + + /// A public administration (Italy: office code of 6 characters). + PublicAdministration = 1, + + /// A private consumer. + Consumer = 2, + + /// A customer abroad. + Foreign = 3, +} + +/// The country's tax identifiers: VAT number, personal tax code and e-invoice recipient code. +public interface ITaxIdentifierRules +{ + /// The VAT number without spaces and without the country prefix. + /// The number as typed. + /// The compact number. + string NormalizeVatNumber(string? vatNumber); + + /// Whether a domestic VAT number is valid (format and check digit). + /// The number, with or without prefix. + /// when valid. + bool IsValidVatNumber(string? vatNumber); + + /// Whether a personal or company tax code is valid. + /// The code. + /// when valid. + bool IsValidTaxCode(string? taxCode); + + /// Computes the personal tax code of a person. + /// The personal data. + /// The code. + string ComputePersonalTaxCode(PersonalTaxCodeData data); + + /// Reads birth date, sex and place back from a personal tax code. + /// The code. + /// The reference date that decides the century. + /// The data, or if the code is not a valid personal code. + PersonalTaxCodeInfo? DecodePersonalTaxCode(string? taxCode, DateOnly today); + + /// The rules an e-invoice recipient code breaks for a kind of customer; empty when valid. + /// The code. + /// The kind of customer. + /// Errors and warnings with field RecipientCode. + IReadOnlyList CheckRecipientCode(string? recipientCode, RecipientKind kind); + + /// The recipient code to propose for a kind of customer without one. + /// The kind of customer. + /// The default code, or if the customer must give one. + string? DefaultRecipientCode(RecipientKind kind); +} + +/// A bank found from its national code. +/// The national bank code (Italy: ABI). +/// 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); + +/// The country's directory of banks, to fill bank name and BIC from an IBAN. +public interface IBankDirectory +{ + /// The bank of a domestic IBAN. + /// 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.Abstractions/Taxes.cs b/src/Khaemhat.Fiscal.Abstractions/Taxes.cs new file mode 100644 index 0000000..804bca2 --- /dev/null +++ b/src/Khaemhat.Fiscal.Abstractions/Taxes.cs @@ -0,0 +1,109 @@ +using Khaemhat.Core.Tax; + +namespace Khaemhat.Fiscal.Abstractions; + +/// +/// The fiscal content of a tax code (SPEC §11.1, mockup 076): the parts the country's rules check. The table +/// tax_codes adds validity, accounts and the other company data. +/// +/// The company's code, such as 22 or NI8. +/// The description shown on documents. +/// The rate in percent, such as 22. +/// The country's nature code for zero-rate operations (Italy: N1...N7). +/// When the tax becomes due. +/// Share of the purchase tax that cannot be deducted, 0-100. +/// The law the operation is based on, printed on the invoice. +public sealed record TaxCodeDefinition( + string Code, + string Description, + decimal Rate, + string? Nature = null, + TaxExigibility Exigibility = TaxExigibility.Immediate, + decimal NonDeductiblePercent = 0m, + string? LegalReference = null); + +/// The country's tax natures and base tax codes, and the rules a tax code must follow. +public interface ITaxCodeCatalog +{ + /// The nature codes for operations without tax. + CodeList Natures { get; } + + /// The tax codes loaded by the base data (SPEC §14). + IReadOnlyList BaseCodes { get; } + + /// The kind of operation a rate and nature describe. + /// The rate in percent. + /// The nature code, if any. + /// The kind. + TaxCodeKind KindOf(decimal rate, string? nature); + + /// The rules a tax code breaks; empty when it is valid. + /// The tax code. + /// Errors and warnings. + IReadOnlyList Validate(TaxCodeDefinition code); +} + +/// An amount of a document subject to one tax code. +/// The taxable amount, already net of discounts. +/// The rate in percent. +/// The nature code for zero-rate operations. +/// When the tax becomes due. +/// Share of the tax that cannot be deducted (purchases). +public sealed record TaxableAmount( + decimal Amount, + decimal Rate, + string? Nature = null, + TaxExigibility Exigibility = TaxExigibility.Immediate, + decimal NonDeductiblePercent = 0m); + +/// One line of the tax summary of a document (castelletto IVA). +/// The rate in percent. +/// The nature code, if any. +/// When the tax becomes due. +/// Share of the tax that cannot be deducted. +/// The sum of the taxable amounts. +/// The tax, rounded to the cent. +/// The part of that cannot be deducted. +public sealed record TaxSummaryLine( + decimal Rate, + string? Nature, + TaxExigibility Exigibility, + decimal NonDeductiblePercent, + decimal Taxable, + decimal Tax, + decimal NonDeductibleTax); + +/// Whether a document needs stamp duty, and how much. +/// The document must carry the duty. +/// The duty, zero when not required. +/// The sum of the amounts without tax that the rule counts. +/// The amount above which the duty is due. +public sealed record StampDutyAssessment(bool Required, decimal Amount, decimal ExemptTotal, decimal Threshold); + +/// Tax computation with the country's rounding rules. +public interface ITaxEngine +{ + /// Rounds an amount of money as the country's tax rules require. + /// The amount. + /// The amount rounded to the cent. + decimal Round(decimal amount); + + /// The tax on a taxable amount. + /// The taxable amount. + /// The rate in percent. + /// The tax, rounded. + decimal ComputeTax(decimal taxable, decimal rate); + + /// + /// The tax summary of a document: one line per rate, nature, exigibility and non-deductible share, with the tax + /// computed on the total of the line (not summed from the rows). + /// + /// The taxable amounts of the document rows. + /// The summary lines, by rate (highest first) and then by nature. + IReadOnlyList Summarize(IEnumerable amounts); + + /// Whether the document needs stamp duty. + /// The tax summary of the document. + /// The assessment. + StampDutyAssessment AssessStampDuty(IEnumerable summary); +} diff --git a/src/Khaemhat.Fiscal.Italy/Data/comuni.csv b/src/Khaemhat.Fiscal.Italy/Data/comuni.csv new file mode 100644 index 0000000..e3603f1 --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/Data/comuni.csv @@ -0,0 +1,7895 @@ +codice_catastale;denominazione;sigla;regione;codice_istat;cap +A074;Agliè;TO;Piemonte;001001;10011 +A109;Airasca;TO;Piemonte;001002;10060 +A117;Ala di Stura;TO;Piemonte;001003;10070 +A157;Albiano d'Ivrea;TO;Piemonte;001004;10010 +A218;Almese;TO;Piemonte;001006;10040 +A221;Alpette;TO;Piemonte;001007;10080 +A222;Alpignano;TO;Piemonte;001008;10091 +A275;Andezeno;TO;Piemonte;001009;10020 +A282;Andrate;TO;Piemonte;001010;10010 +A295;Angrogna;TO;Piemonte;001011;10060 +A405;Arignano;TO;Piemonte;001012;10020 +A518;Avigliana;TO;Piemonte;001013;10051 +A525;Azeglio;TO;Piemonte;001014;10010 +A584;Bairo;TO;Piemonte;001015;10010 +A587;Balangero;TO;Piemonte;001016;10070 +A590;Baldissero Canavese;TO;Piemonte;001017;10080 +A591;Baldissero Torinese;TO;Piemonte;001018;10020 +A599;Balme;TO;Piemonte;001019;10070 +A607;Banchette;TO;Piemonte;001020;10010 +A625;Barbania;TO;Piemonte;001021;10070 +A651;Bardonecchia;TO;Piemonte;001022;10052 +A673;Barone Canavese;TO;Piemonte;001023;10010 +A734;Beinasco;TO;Piemonte;001024;10092 +A853;Bibiana;TO;Piemonte;001025;10060 +A910;Bobbio Pellice;TO;Piemonte;001026;10060 +A941;Bollengo;TO;Piemonte;001027;10012 +A990;Borgaro Torinese;TO;Piemonte;001028;10071 +B003;Borgiallo;TO;Piemonte;001029;10080 +B015;Borgofranco d'Ivrea;TO;Piemonte;001030;10013 +B021;Borgomasino;TO;Piemonte;001031;10031 +B024;Borgone Susa;TO;Piemonte;001032;10050 +B075;Bosconero;TO;Piemonte;001033;10080 +B121;Brandizzo;TO;Piemonte;001034;10032 +B171;Bricherasio;TO;Piemonte;001035;10060 +B205;Brosso;TO;Piemonte;001036;10080 +B209;Brozolo;TO;Piemonte;001037;10020 +B216;Bruino;TO;Piemonte;001038;10090 +B225;Brusasco;TO;Piemonte;001039;10020 +B232;Bruzolo;TO;Piemonte;001040;10050 +B278;Buriasco;TO;Piemonte;001041;10060 +B279;Burolo;TO;Piemonte;001042;10010 +B284;Busano;TO;Piemonte;001043;10080 +B297;Bussoleno;TO;Piemonte;001044;10053 +B305;Buttigliera Alta;TO;Piemonte;001045;10090 +B350;Cafasse;TO;Piemonte;001046;10070 +B435;Caluso;TO;Piemonte;001047;10014 +B462;Cambiano;TO;Piemonte;001048;10020 +B512;Campiglione Fenile;TO;Piemonte;001049;10060 +B588;Candia Canavese;TO;Piemonte;001050;10010 +B592;Candiolo;TO;Piemonte;001051;10060 +B605;Canischio;TO;Piemonte;001052;10080 +B628;Cantalupa;TO;Piemonte;001053;10060 +B637;Cantoira;TO;Piemonte;001054;10070 +B705;Caprie;TO;Piemonte;001055;10040 +B733;Caravino;TO;Piemonte;001056;10010 +B762;Carema;TO;Piemonte;001057;10010 +B777;Carignano;TO;Piemonte;001058;10041 +B791;Carmagnola;TO;Piemonte;001059;10022 +B867;Casalborgone;TO;Piemonte;001060;10020 +B953;Cascinette d'Ivrea;TO;Piemonte;001061;10010 +B955;Caselette;TO;Piemonte;001062;10040 +B960;Caselle Torinese;TO;Piemonte;001063;10072 +C045;Castagneto Po;TO;Piemonte;001064;10090 +C048;Castagnole Piemonte;TO;Piemonte;001065;10060 +C133;Castellamonte;TO;Piemonte;001066;10081 +C241;Castelnuovo Nigra;TO;Piemonte;001067;10080 +C307;Castiglione Torinese;TO;Piemonte;001068;10090 +C369;Cavagnolo;TO;Piemonte;001069;10020 +C404;Cavour;TO;Piemonte;001070;10061 +C487;Cercenasco;TO;Piemonte;001071;10060 +C497;Ceres;TO;Piemonte;001072;10070 +C505;Ceresole Reale;TO;Piemonte;001073;10080 +C564;Cesana Torinese;TO;Piemonte;001074;10054 +C604;Chialamberto;TO;Piemonte;001075;10070 +C610;Chianocco;TO;Piemonte;001076;10050 +C624;Chiaverano;TO;Piemonte;001077;10010 +C627;Chieri;TO;Piemonte;001078;10023 +C629;Chiesanuova;TO;Piemonte;001079;10080 +C639;Chiomonte;TO;Piemonte;001080;10050 +C655;Chiusa di San Michele;TO;Piemonte;001081;10050 +C665;Chivasso;TO;Piemonte;001082;10034 +C679;Ciconio;TO;Piemonte;001083;10080 +C711;Cintano;TO;Piemonte;001084;10080 +C715;Cinzano;TO;Piemonte;001085;10090 +C722;Ciriè;TO;Piemonte;001086;10073 +C793;Claviere;TO;Piemonte;001087;10050 +C801;Coassolo Torinese;TO;Piemonte;001088;10070 +C803;Coazze;TO;Piemonte;001089;10050 +C860;Collegno;TO;Piemonte;001090;10093 +C867;Colleretto Castelnuovo;TO;Piemonte;001091;10080 +C868;Colleretto Giacosa;TO;Piemonte;001092;10010 +C955;Condove;TO;Piemonte;001093;10055 +D008;Corio;TO;Piemonte;001094;10070 +D092;Cossano Canavese;TO;Piemonte;001095;10010 +D197;Cuceglio;TO;Piemonte;001096;10090 +D202;Cumiana;TO;Piemonte;001097;10040 +D208;Cuorgnè;TO;Piemonte;001098;10082 +D373;Druento;TO;Piemonte;001099;10040 +D433;Exilles;TO;Piemonte;001100;10050 +D520;Favria;TO;Piemonte;001101;10083 +D524;Feletto;TO;Piemonte;001102;10080 +D532;Fenestrelle;TO;Piemonte;001103;10060 +D562;Fiano;TO;Piemonte;001104;10070 +D608;Fiorano Canavese;TO;Piemonte;001105;10010 +D646;Foglizzo;TO;Piemonte;001106;10090 +D725;Forno Canavese;TO;Piemonte;001107;10084 +D781;Frassinetto;TO;Piemonte;001108;10080 +D805;Front;TO;Piemonte;001109;10070 +D812;Frossasco;TO;Piemonte;001110;10060 +D931;Garzigliana;TO;Piemonte;001111;10060 +D933;Gassino Torinese;TO;Piemonte;001112;10090 +D983;Germagnano;TO;Piemonte;001113;10070 +E009;Giaglione;TO;Piemonte;001114;10050 +E020;Giaveno;TO;Piemonte;001115;10094 +E067;Givoletto;TO;Piemonte;001116;10040 +E154;Gravere;TO;Piemonte;001117;10050 +E199;Groscavallo;TO;Piemonte;001118;10070 +E203;Grosso;TO;Piemonte;001119;10070 +E216;Grugliasco;TO;Piemonte;001120;10095 +E301;Ingria;TO;Piemonte;001121;10080 +E311;Inverso Pinasca;TO;Piemonte;001122;10060 +E345;Isolabella;TO;Piemonte;001123;10046 +E368;Issiglio;TO;Piemonte;001124;10080 +E379;Ivrea;TO;Piemonte;001125;10015 +E394;La Cassa;TO;Piemonte;001126;10040 +E423;La Loggia;TO;Piemonte;001127;10040 +E445;Lanzo Torinese;TO;Piemonte;001128;10074 +E484;Lauriano;TO;Piemonte;001129;10020 +E518;Leini;TO;Piemonte;001130;10040 +E520;Lemie;TO;Piemonte;001131;10070 +E551;Lessolo;TO;Piemonte;001132;10010 +E566;Levone;TO;Piemonte;001133;10070 +E635;Locana;TO;Piemonte;001134;10080 +E660;Lombardore;TO;Piemonte;001135;10040 +E661;Lombriasco;TO;Piemonte;001136;10040 +E683;Loranzè;TO;Piemonte;001137;10010 +E758;Luserna San Giovanni;TO;Piemonte;001139;10062 +E759;Lusernetta;TO;Piemonte;001140;10060 +E763;Lusigliè;TO;Piemonte;001141;10080 +E782;Macello;TO;Piemonte;001142;10060 +E817;Maglione;TO;Piemonte;001143;10030 +E941;Marentino;TO;Piemonte;001144;10020 +F041;Massello;TO;Piemonte;001145;10060 +F053;Mathi;TO;Piemonte;001146;10075 +F058;Mattie;TO;Piemonte;001147;10050 +F067;Mazzè;TO;Piemonte;001148;10035 +F074;Meana di Susa;TO;Piemonte;001149;10050 +F140;Mercenasco;TO;Piemonte;001150;10010 +F182;Mezzenile;TO;Piemonte;001152;10070 +F315;Mombello di Torino;TO;Piemonte;001153;10020 +F318;Mompantero;TO;Piemonte;001154;10059 +F327;Monastero di Lanzo;TO;Piemonte;001155;10070 +F335;Moncalieri;TO;Piemonte;001156;10024 +D553;Moncenisio;TO;Piemonte;001157;10050 +F407;Montaldo Torinese;TO;Piemonte;001158;10020 +F411;Montalenghe;TO;Piemonte;001159;10090 +F420;Montalto Dora;TO;Piemonte;001160;10016 +F422;Montanaro;TO;Piemonte;001161;10017 +F651;Monteu da Po;TO;Piemonte;001162;10020 +F733;Moriondo Torinese;TO;Piemonte;001163;10020 +F889;Nichelino;TO;Piemonte;001164;10042 +F906;Noasca;TO;Piemonte;001165;10080 +F925;Nole;TO;Piemonte;001166;10076 +F927;Nomaglio;TO;Piemonte;001167;10010 +F931;None;TO;Piemonte;001168;10060 +F948;Novalesa;TO;Piemonte;001169;10050 +G010;Oglianico;TO;Piemonte;001170;10080 +G087;Orbassano;TO;Piemonte;001171;10043 +G109;Orio Canavese;TO;Piemonte;001172;10010 +G151;Osasco;TO;Piemonte;001173;10060 +G152;Osasio;TO;Piemonte;001174;10040 +G196;Oulx;TO;Piemonte;001175;10056 +G202;Ozegna;TO;Piemonte;001176;10080 +G262;Palazzo Canavese;TO;Piemonte;001177;10010 +G303;Pancalieri;TO;Piemonte;001178;10060 +G330;Parella;TO;Piemonte;001179;10010 +G387;Pavarolo;TO;Piemonte;001180;10020 +G392;Pavone Canavese;TO;Piemonte;001181;10018 +G398;Pecetto Torinese;TO;Piemonte;001183;10020 +G463;Perosa Argentina;TO;Piemonte;001184;10063 +G462;Perosa Canavese;TO;Piemonte;001185;10010 +G465;Perrero;TO;Piemonte;001186;10060 +G477;Pertusio;TO;Piemonte;001187;10080 +G505;Pessinetto;TO;Piemonte;001188;10070 +G559;Pianezza;TO;Piemonte;001189;10044 +G672;Pinasca;TO;Piemonte;001190;10060 +G674;Pinerolo;TO;Piemonte;001191;10064 +G678;Pino Torinese;TO;Piemonte;001192;10025 +G684;Piobesi Torinese;TO;Piemonte;001193;10040 +G691;Piossasco;TO;Piemonte;001194;10045 +G705;Piscina;TO;Piemonte;001195;10060 +G719;Piverone;TO;Piemonte;001196;10010 +G777;Poirino;TO;Piemonte;001197;10046 +G805;Pomaretto;TO;Piemonte;001198;10063 +G826;Pont Canavese;TO;Piemonte;001199;10085 +G900;Porte;TO;Piemonte;001200;10060 +G973;Pragelato;TO;Piemonte;001201;10060 +G978;Prali;TO;Piemonte;001202;10060 +G979;Pralormo;TO;Piemonte;001203;10040 +G982;Pramollo;TO;Piemonte;001204;10065 +G986;Prarostino;TO;Piemonte;001205;10060 +G988;Prascorsano;TO;Piemonte;001206;10080 +G997;Pratiglione;TO;Piemonte;001207;10080 +H100;Quagliuzzo;TO;Piemonte;001208;10010 +H120;Quassolo;TO;Piemonte;001209;10010 +H127;Quincinetto;TO;Piemonte;001210;10010 +H207;Reano;TO;Piemonte;001211;10090 +H270;Ribordone;TO;Piemonte;001212;10080 +H333;Rivalba;TO;Piemonte;001213;10090 +H335;Rivalta di Torino;TO;Piemonte;001214;10040 +H337;Riva presso Chieri;TO;Piemonte;001215;10020 +H338;Rivara;TO;Piemonte;001216;10080 +H340;Rivarolo Canavese;TO;Piemonte;001217;10086 +H344;Rivarossa;TO;Piemonte;001218;10040 +H355;Rivoli;TO;Piemonte;001219;10098 +H367;Robassomero;TO;Piemonte;001220;10070 +H386;Rocca Canavese;TO;Piemonte;001221;10070 +H498;Roletto;TO;Piemonte;001222;10060 +H511;Romano Canavese;TO;Piemonte;001223;10090 +H539;Ronco Canavese;TO;Piemonte;001224;10080 +H547;Rondissone;TO;Piemonte;001225;10030 +H554;Rorà;TO;Piemonte;001226;10060 +H555;Roure;TO;Piemonte;001227;10060 +H583;Rosta;TO;Piemonte;001228;10090 +H627;Rubiana;TO;Piemonte;001229;10040 +H631;Rueglio;TO;Piemonte;001230;10010 +H691;Salassa;TO;Piemonte;001231;10080 +H684;Salbertrand;TO;Piemonte;001232;10050 +H702;Salerano Canavese;TO;Piemonte;001233;10010 +H734;Salza di Pinerolo;TO;Piemonte;001234;10060 +H753;Samone;TO;Piemonte;001235; +H775;San Benigno Canavese;TO;Piemonte;001236;10080 +H789;San Carlo Canavese;TO;Piemonte;001237;10070 +H804;San Colombano Belmonte;TO;Piemonte;001238;10080 +H820;San Didero;TO;Piemonte;001239;10050 +H847;San Francesco al Campo;TO;Piemonte;001240;10070 +H855;Sangano;TO;Piemonte;001241;10090 +H862;San Germano Chisone;TO;Piemonte;001242;10065 +H873;San Gillio;TO;Piemonte;001243;10040 +H890;San Giorgio Canavese;TO;Piemonte;001244;10090 +H900;San Giorio di Susa;TO;Piemonte;001245;10050 +H936;San Giusto Canavese;TO;Piemonte;001246;10090 +H997;San Martino Canavese;TO;Piemonte;001247;10010 +I024;San Maurizio Canavese;TO;Piemonte;001248;10077 +I030;San Mauro Torinese;TO;Piemonte;001249;10099 +I090;San Pietro Val Lemina;TO;Piemonte;001250;10060 +I126;San Ponso;TO;Piemonte;001251;10080 +I137;San Raffaele Cimena;TO;Piemonte;001252;10090 +I152;San Sebastiano da Po;TO;Piemonte;001253;10020 +I154;San Secondo di Pinerolo;TO;Piemonte;001254;10060 +I258;Sant'Ambrogio di Torino;TO;Piemonte;001255;10057 +I296;Sant'Antonino di Susa;TO;Piemonte;001256;10050 +I327;Santena;TO;Piemonte;001257;10026 +I465;Sauze di Cesana;TO;Piemonte;001258;10054 +I466;Sauze d'Oulx;TO;Piemonte;001259;10050 +I490;Scalenghe;TO;Piemonte;001260;10060 +I511;Scarmagno;TO;Piemonte;001261;10010 +I539;Sciolze;TO;Piemonte;001262;10090 +I692;Sestriere;TO;Piemonte;001263;10058 +I701;Settimo Rottaro;TO;Piemonte;001264;10010 +I703;Settimo Torinese;TO;Piemonte;001265;10036 +I702;Settimo Vittone;TO;Piemonte;001266;10010 +I886;Sparone;TO;Piemonte;001267;10080 +I969;Strambinello;TO;Piemonte;001268;10010 +I970;Strambino;TO;Piemonte;001269;10019 +L013;Susa;TO;Piemonte;001270;10059 +L066;Tavagnasco;TO;Piemonte;001271;10010 +L219;Torino;TO;Piemonte;001272;10100,10121-10156 +L238;Torrazza Piemonte;TO;Piemonte;001273;10037 +L247;Torre Canavese;TO;Piemonte;001274;10010 +L277;Torre Pellice;TO;Piemonte;001275;10066 +L327;Trana;TO;Piemonte;001276;10090 +L345;Traversella;TO;Piemonte;001278;10080 +L340;Traves;TO;Piemonte;001279;10070 +L445;Trofarello;TO;Piemonte;001280;10028 +L515;Usseaux;TO;Piemonte;001281;10060 +L516;Usseglio;TO;Piemonte;001282;10070 +L538;Vaie;TO;Piemonte;001283;10050 +L555;Val della Torre;TO;Piemonte;001284;10040 +L578;Valgioie;TO;Piemonte;001285;10094 +L629;Vallo Torinese;TO;Piemonte;001286;10070 +L644;Valperga;TO;Piemonte;001287;10087 +B510;Valprato Soana;TO;Piemonte;001288;10080 +L685;Varisella;TO;Piemonte;001289;10070 +L698;Vauda Canavese;TO;Piemonte;001290;10070 +L726;Venaus;TO;Piemonte;001291;10050 +L727;Venaria Reale;TO;Piemonte;001292;10078 +L779;Verolengo;TO;Piemonte;001293;10038 +L787;Verrua Savoia;TO;Piemonte;001294;10020 +L811;Vestignè;TO;Piemonte;001295;10030 +L830;Vialfrè;TO;Piemonte;001296;10090 +L857;Vidracco;TO;Piemonte;001298;10080 +L898;Vigone;TO;Piemonte;001299;10067 +L948;Villafranca Piemonte;TO;Piemonte;001300;10068 +L982;Villanova Canavese;TO;Piemonte;001301;10070 +M002;Villarbasse;TO;Piemonte;001302;10090 +L999;Villar Dora;TO;Piemonte;001303;10040 +M004;Villareggia;TO;Piemonte;001304;10030 +M007;Villar Focchiardo;TO;Piemonte;001305;10050 +M013;Villar Pellice;TO;Piemonte;001306;10060 +M014;Villar Perosa;TO;Piemonte;001307;10069 +M027;Villastellone;TO;Piemonte;001308;10029 +M060;Vinovo;TO;Piemonte;001309;10048 +M069;Virle Piemonte;TO;Piemonte;001310;10060 +M071;Vische;TO;Piemonte;001311;10030 +M080;Vistrorio;TO;Piemonte;001312;10080 +M094;Viù;TO;Piemonte;001313;10070 +M122;Volpiano;TO;Piemonte;001314;10088 +M133;Volvera;TO;Piemonte;001315;10040 +M316;Mappano;TO;Piemonte;001316;10072 +M405;Val di Chy;TO;Piemonte;001317; +M415;Valchiusa;TO;Piemonte;001318; +A119;Alagna Valsesia;VC;Piemonte;002002;13021 +A130;Albano Vercellese;VC;Piemonte;002003;13030 +A198;Alice Castello;VC;Piemonte;002004;13040 +A358;Arborio;VC;Piemonte;002006;13031 +A466;Asigliano Vercellese;VC;Piemonte;002007;13032 +A600;Balmuccia;VC;Piemonte;002008;13020 +A601;Balocco;VC;Piemonte;002009;13040 +A847;Bianzè;VC;Piemonte;002011;13041 +A914;Boccioleto;VC;Piemonte;002014;13022 +B009;Borgo d'Ale;VC;Piemonte;002015;13040 +B041;Borgosesia;VC;Piemonte;002016;13011 +B046;Borgo Vercelli;VC;Piemonte;002017;13012 +B280;Buronzo;VC;Piemonte;002021;13040 +B505;Campertogno;VC;Piemonte;002025;13023 +B752;Carcoforo;VC;Piemonte;002029;13026 +B767;Caresana;VC;Piemonte;002030;13010 +B768;Caresanablot;VC;Piemonte;002031;13030 +B782;Carisio;VC;Piemonte;002032;13040 +B928;Casanova Elvo;VC;Piemonte;002033;13030 +B952;San Giacomo Vercellese;VC;Piemonte;002035;13030 +C548;Cervatto;VC;Piemonte;002041;13025 +C680;Cigliano;VC;Piemonte;002042;13043 +C757;Civiasco;VC;Piemonte;002043;13010 +C884;Collobiano;VC;Piemonte;002045;13030 +D113;Costanzana;VC;Piemonte;002047;13033 +D132;Cravagliana;VC;Piemonte;002048;13020 +D154;Crescentino;VC;Piemonte;002049;13044 +D187;Crova;VC;Piemonte;002052;13040 +D281;Desana;VC;Piemonte;002054;13034 +D641;Fobello;VC;Piemonte;002057;13025 +D676;Fontanetto Po;VC;Piemonte;002058;13040 +D712;Formigliana;VC;Piemonte;002059;13030 +D938;Gattinara;VC;Piemonte;002061;13045 +E007;Ghislarengo;VC;Piemonte;002062;13030 +E163;Greggio;VC;Piemonte;002065;13030 +E237;Guardabosone;VC;Piemonte;002066;13010 +E433;Lamporo;VC;Piemonte;002067;13046 +E528;Lenta;VC;Piemonte;002068;13035 +E583;Lignana;VC;Piemonte;002070;13034,13100 +E626;Livorno Ferraris;VC;Piemonte;002071;13046 +E711;Lozzolo;VC;Piemonte;002072;13045 +F297;Mollia;VC;Piemonte;002078;13020 +F342;Moncrivello;VC;Piemonte;002079;13040 +F774;Motta de' Conti;VC;Piemonte;002082;13010 +G016;Olcenengo;VC;Piemonte;002088;13047 +G018;Oldenico;VC;Piemonte;002089;13030 +G266;Palazzolo Vercellese;VC;Piemonte;002090;13040 +G471;Pertengo;VC;Piemonte;002091;13030 +G528;Pezzana;VC;Piemonte;002093;13010 +G666;Pila;VC;Piemonte;002096;13020 +G685;Piode;VC;Piemonte;002097;13020 +G940;Postua;VC;Piemonte;002102;13010 +G985;Prarolo;VC;Piemonte;002104;13012,13100 +H108;Quarona;VC;Piemonte;002107;13017 +H132;Quinto Vercellese;VC;Piemonte;002108;13030 +H188;Rassa;VC;Piemonte;002110;13020 +H293;Rimella;VC;Piemonte;002113;13020 +H346;Rive;VC;Piemonte;002115;13030 +H365;Roasio;VC;Piemonte;002116;13060 +H549;Ronsecco;VC;Piemonte;002118;13036 +H577;Rossa;VC;Piemonte;002121;13020 +H364;Rovasenda;VC;Piemonte;002122;13040 +H690;Salasco;VC;Piemonte;002126;13040 +H707;Sali Vercellese;VC;Piemonte;002127;13040 +H725;Saluggia;VC;Piemonte;002128;13040 +H861;San Germano Vercellese;VC;Piemonte;002131;13047 +I337;Santhià;VC;Piemonte;002133;13048 +I544;Scopa;VC;Piemonte;002134;13027 +I545;Scopello;VC;Piemonte;002135;13028 +I663;Serravalle Sesia;VC;Piemonte;002137;13037 +I984;Stroppiana;VC;Piemonte;002142;13010 +L420;Tricerro;VC;Piemonte;002147;13038 +L429;Trino;VC;Piemonte;002148;13039 +L451;Tronzano Vercellese;VC;Piemonte;002150;13049 +L566;Valduggia;VC;Piemonte;002152;13018 +L669;Varallo;VC;Piemonte;002156;13019 +L750;Vercelli;VC;Piemonte;002158;13100 +M003;Villarboit;VC;Piemonte;002163;13030 +M028;Villata;VC;Piemonte;002164;13010 +M106;Vocca;VC;Piemonte;002166;13020 +M389;Alto Sermenza;VC;Piemonte;002170; +M398;Cellio con Breia;VC;Piemonte;002171; +A088;Agrate Conturbia;NO;Piemonte;003001;28010 +A264;Ameno;NO;Piemonte;003002;28010 +A414;Armeno;NO;Piemonte;003006;28011 +A429;Arona;NO;Piemonte;003008;28041 +A653;Barengo;NO;Piemonte;003012;28010 +A752;Bellinzago Novarese;NO;Piemonte;003016;28043 +A844;Biandrate;NO;Piemonte;003018;28061 +A911;Boca;NO;Piemonte;003019;28010 +A929;Bogogno;NO;Piemonte;003021;28010 +A953;Bolzano Novarese;NO;Piemonte;003022;28010 +B016;Borgolavezzaro;NO;Piemonte;003023;28071 +B019;Borgomanero;NO;Piemonte;003024;28021 +B043;Borgo Ticino;NO;Piemonte;003025;28040 +B176;Briga Novarese;NO;Piemonte;003026;28010 +B183;Briona;NO;Piemonte;003027;28072 +B431;Caltignaga;NO;Piemonte;003030;28010 +B473;Cameri;NO;Piemonte;003032;28062 +B823;Carpignano Sesia;NO;Piemonte;003036;28064 +B864;Casalbeltrame;NO;Piemonte;003037;28060 +B883;Casaleggio Novara;NO;Piemonte;003039;28060 +B897;Casalino;NO;Piemonte;003040;28060 +B920;Casalvolone;NO;Piemonte;003041;28060 +C149;Castellazzo Novarese;NO;Piemonte;003042;28060 +C166;Castelletto sopra Ticino;NO;Piemonte;003043;28053 +C364;Cavaglietto;NO;Piemonte;003044;28010 +C365;Cavaglio d'Agogna;NO;Piemonte;003045;28010 +C378;Cavallirio;NO;Piemonte;003047;28010 +C483;Cerano;NO;Piemonte;003049;28065 +C829;Colazza;NO;Piemonte;003051;28010 +C926;Comignago;NO;Piemonte;003052;28060 +D162;Cressa;NO;Piemonte;003055;28012 +D216;Cureggio;NO;Piemonte;003058;28060 +D309;Divignano;NO;Piemonte;003060;28010 +D347;Dormelletto;NO;Piemonte;003062;28040 +D492;Fara Novarese;NO;Piemonte;003065;28073 +D675;Fontaneto d'Agogna;NO;Piemonte;003066;28010 +D872;Galliate;NO;Piemonte;003068;28066 +D911;Garbagna Novarese;NO;Piemonte;003069;28070 +D921;Gargallo;NO;Piemonte;003070;28010 +E001;Ghemme;NO;Piemonte;003073;28074 +E120;Gozzano;NO;Piemonte;003076;28024 +E143;Granozzo con Monticello;NO;Piemonte;003077;28060 +E177;Grignasco;NO;Piemonte;003079;28075 +E314;Invorio;NO;Piemonte;003082;28045 +E436;Landiona;NO;Piemonte;003083;28064 +E544;Lesa;NO;Piemonte;003084;28040 +E803;Maggiora;NO;Piemonte;003088;28014 +E880;Mandello Vitta;NO;Piemonte;003090;28060 +E907;Marano Ticino;NO;Piemonte;003091;28040 +F047;Massino Visconti;NO;Piemonte;003093;28040 +F093;Meina;NO;Piemonte;003095;28046 +F188;Mezzomerico;NO;Piemonte;003097;28040 +F191;Miasino;NO;Piemonte;003098;28010 +F317;Momo;NO;Piemonte;003100;28015 +F859;Nebbiuno;NO;Piemonte;003103;28010 +F886;Nibbiola;NO;Piemonte;003104;28070 +F952;Novara;NO;Piemonte;003106;28100 +G019;Oleggio;NO;Piemonte;003108;28047 +G020;Oleggio Castello;NO;Piemonte;003109;28040 +G134;Orta San Giulio;NO;Piemonte;003112;28016 +G349;Paruzzaro;NO;Piemonte;003114;28040 +G421;Pella;NO;Piemonte;003115;28010 +G520;Pettenasco;NO;Piemonte;003116;28028 +G703;Pisano;NO;Piemonte;003119;28010 +G775;Pogno;NO;Piemonte;003120;28076 +G809;Pombia;NO;Piemonte;003121;28050 +H001;Prato Sesia;NO;Piemonte;003122;28077 +H213;Recetto;NO;Piemonte;003129;28060 +H502;Romagnano Sesia;NO;Piemonte;003130;28078 +H518;Romentino;NO;Piemonte;003131;28068 +I025;San Maurizio d'Opaglio;NO;Piemonte;003133;28017 +I052;San Nazzaro Sesia;NO;Piemonte;003134;28060 +I116;San Pietro Mosezzo;NO;Piemonte;003135;28060 +I736;Sillavengo;NO;Piemonte;003138;28064 +I767;Sizzano;NO;Piemonte;003139;28070 +I857;Soriso;NO;Piemonte;003140;28010 +I880;Sozzago;NO;Piemonte;003141;28060 +L007;Suno;NO;Piemonte;003143;28019 +L104;Terdobbiate;NO;Piemonte;003144;28070 +L223;Tornaco;NO;Piemonte;003146;28070 +L356;Trecate;NO;Piemonte;003149;28069 +L668;Vaprio d'Agogna;NO;Piemonte;003153;28010 +L670;Varallo Pombia;NO;Piemonte;003154;28040 +L808;Vespolate;NO;Piemonte;003158;28079 +L847;Vicolungo;NO;Piemonte;003159;28060 +M062;Vinzaglio;NO;Piemonte;003164;28060 +M416;Gattico-Veruno;NO;Piemonte;003166; +A016;Acceglio;CN;Piemonte;004001;12021 +A113;Aisone;CN;Piemonte;004002;12010 +A124;Alba;CN;Piemonte;004003;12051 +A139;Albaretto della Torre;CN;Piemonte;004004;12050 +A238;Alto;CN;Piemonte;004005;12070 +A394;Argentera;CN;Piemonte;004006;12010 +A396;Arguello;CN;Piemonte;004007;12050 +A555;Bagnasco;CN;Piemonte;004008;12071 +A571;Bagnolo Piemonte;CN;Piemonte;004009;12031 +A589;Baldissero d'Alba;CN;Piemonte;004010;12040 +A629;Barbaresco;CN;Piemonte;004011;12050 +A660;Barge;CN;Piemonte;004012;12032 +A671;Barolo;CN;Piemonte;004013;12060 +A709;Bastia Mondovì;CN;Piemonte;004014;12060 +A716;Battifollo;CN;Piemonte;004015;12070 +A735;Beinette;CN;Piemonte;004016;12081 +A750;Bellino;CN;Piemonte;004017;12020 +A774;Belvedere Langhe;CN;Piemonte;004018;12060 +A779;Bene Vagienna;CN;Piemonte;004019;12041 +A782;Benevello;CN;Piemonte;004020;12050 +A798;Bergolo;CN;Piemonte;004021;12074 +A805;Bernezzo;CN;Piemonte;004022;12010 +A979;Bonvicino;CN;Piemonte;004023;12060 +B018;Borgomale;CN;Piemonte;004024;12050 +B033;Borgo San Dalmazzo;CN;Piemonte;004025;12011 +B079;Bosia;CN;Piemonte;004026;12050 +B084;Bossolasco;CN;Piemonte;004027;12060 +B101;Boves;CN;Piemonte;004028;12012 +B111;Bra;CN;Piemonte;004029;12042 +B167;Briaglia;CN;Piemonte;004030;12080 +B175;Briga Alta;CN;Piemonte;004031;18025 +B200;Brondello;CN;Piemonte;004032;12030 +B204;Brossasco;CN;Piemonte;004033;12020 +B285;Busca;CN;Piemonte;004034;12022 +B467;Camerana;CN;Piemonte;004035;12072 +B573;Canale;CN;Piemonte;004037;12043 +B621;Canosio;CN;Piemonte;004038;12020 +B692;Caprauna;CN;Piemonte;004039;12070 +B719;Caraglio;CN;Piemonte;004040;12023 +B720;Caramagna Piemonte;CN;Piemonte;004041;12030 +B755;Cardè;CN;Piemonte;004042;12030 +B841;Carrù;CN;Piemonte;004043;12061 +B845;Cartignano;CN;Piemonte;004044;12020 +B894;Casalgrasso;CN;Piemonte;004045;12030 +C046;Castagnito;CN;Piemonte;004046;12050 +C081;Casteldelfino;CN;Piemonte;004047;12020 +C165;Castelletto Stura;CN;Piemonte;004049;12040 +C167;Castelletto Uzzone;CN;Piemonte;004050;12070 +C173;Castellinaldo d'Alba;CN;Piemonte;004051; +C176;Castellino Tanaro;CN;Piemonte;004052;12060 +C205;Castelmagno;CN;Piemonte;004053;12020 +C214;Castelnuovo di Ceva;CN;Piemonte;004054;12070 +C314;Castiglione Falletto;CN;Piemonte;004055;12060 +C317;Castiglione Tinella;CN;Piemonte;004056;12053 +C323;Castino;CN;Piemonte;004057;12050 +C375;Cavallerleone;CN;Piemonte;004058;12030 +C376;Cavallermaggiore;CN;Piemonte;004059;12030 +C441;Celle di Macra;CN;Piemonte;004060;12020 +C466;Centallo;CN;Piemonte;004061;12044 +C504;Ceresole Alba;CN;Piemonte;004062;12040 +C530;Cerretto Langhe;CN;Piemonte;004063; +C547;Cervasca;CN;Piemonte;004064;12010 +C550;Cervere;CN;Piemonte;004065;12040 +C589;Ceva;CN;Piemonte;004066;12073 +C599;Cherasco;CN;Piemonte;004067;12062 +C653;Chiusa di Pesio;CN;Piemonte;004068;12013 +C681;Cigliè;CN;Piemonte;004069;12060 +C738;Cissone;CN;Piemonte;004070;12050 +C792;Clavesana;CN;Piemonte;004071;12060 +D022;Corneliano d'Alba;CN;Piemonte;004072;12040 +D062;Cortemilia;CN;Piemonte;004073;12074 +D093;Cossano Belbo;CN;Piemonte;004074;12054 +D120;Costigliole Saluzzo;CN;Piemonte;004075;12024 +D133;Cravanzana;CN;Piemonte;004076;12050 +D172;Crissolo;CN;Piemonte;004077;12030 +D205;Cuneo;CN;Piemonte;004078;12100 +D271;Demonte;CN;Piemonte;004079;12014 +D291;Diano d'Alba;CN;Piemonte;004080;12055 +D314;Dogliani;CN;Piemonte;004081;12063 +D372;Dronero;CN;Piemonte;004082;12025 +D401;Elva;CN;Piemonte;004083;12020 +D410;Entracque;CN;Piemonte;004084;12010 +D412;Envie;CN;Piemonte;004085;12030 +D499;Farigliano;CN;Piemonte;004086;12060 +D511;Faule;CN;Piemonte;004087;12030 +D523;Feisoglio;CN;Piemonte;004088;12050 +D742;Fossano;CN;Piemonte;004089;12045 +D751;Frabosa Soprana;CN;Piemonte;004090;12082 +D752;Frabosa Sottana;CN;Piemonte;004091;12083 +D782;Frassino;CN;Piemonte;004092;12020 +D856;Gaiola;CN;Piemonte;004093;12010 +D894;Gambasca;CN;Piemonte;004094;12030 +D920;Garessio;CN;Piemonte;004095;12075 +D967;Genola;CN;Piemonte;004096;12040 +E111;Gorzegno;CN;Piemonte;004097;12070 +E115;Gottasecca;CN;Piemonte;004098;12070 +E118;Govone;CN;Piemonte;004099;12040 +E182;Grinzane Cavour;CN;Piemonte;004100;12060 +E251;Guarene;CN;Piemonte;004101;12050 +E282;Igliano;CN;Piemonte;004102;12060 +E327;Isasca;CN;Piemonte;004103;12020 +E406;Lagnasco;CN;Piemonte;004104;12030 +E430;La Morra;CN;Piemonte;004105;12064 +E540;Lequio Berria;CN;Piemonte;004106;12050 +E539;Lequio Tanaro;CN;Piemonte;004107;12060 +E546;Lesegno;CN;Piemonte;004108;12076 +E564;Levice;CN;Piemonte;004109;12070 +E597;Limone Piemonte;CN;Piemonte;004110;12015 +E615;Lisio;CN;Piemonte;004111;12070 +E789;Macra;CN;Piemonte;004112;12020 +E809;Magliano Alfieri;CN;Piemonte;004113;12050 +E808;Magliano Alpi;CN;Piemonte;004114;12060 +E887;Mango;CN;Piemonte;004115;12056 +E894;Manta;CN;Piemonte;004116;12030 +E939;Marene;CN;Piemonte;004117;12030 +E945;Margarita;CN;Piemonte;004118;12040 +E963;Marmora;CN;Piemonte;004119;12020 +E973;Marsaglia;CN;Piemonte;004120;12060 +E988;Martiniana Po;CN;Piemonte;004121;12030 +F114;Melle;CN;Piemonte;004122;12020 +F279;Moiola;CN;Piemonte;004123;12010 +F309;Mombarcaro;CN;Piemonte;004124;12070 +F312;Mombasiglio;CN;Piemonte;004125;12070 +F326;Monastero di Vasco;CN;Piemonte;004126;12080 +F329;Monasterolo Casotto;CN;Piemonte;004127;12080 +F330;Monasterolo di Savigliano;CN;Piemonte;004128;12030 +F338;Monchiero;CN;Piemonte;004129;12060 +F351;Mondovì;CN;Piemonte;004130;12084 +F355;Monesiglio;CN;Piemonte;004131;12077 +F358;Monforte d'Alba;CN;Piemonte;004132;12065 +F385;Montà;CN;Piemonte;004133;12046 +F405;Montaldo di Mondovì;CN;Piemonte;004134;12080 +F408;Montaldo Roero;CN;Piemonte;004135;12040 +F424;Montanera;CN;Piemonte;004136;12040 +F550;Montelupo Albese;CN;Piemonte;004137;12050 +F558;Montemale di Cuneo;CN;Piemonte;004138;12025 +F608;Monterosso Grana;CN;Piemonte;004139;12020 +F654;Monteu Roero;CN;Piemonte;004140;12040 +F666;Montezemolo;CN;Piemonte;004141;12070 +F669;Monticello d'Alba;CN;Piemonte;004142;12066 +F723;Moretta;CN;Piemonte;004143;12033 +F743;Morozzo;CN;Piemonte;004144;12040 +F809;Murazzano;CN;Piemonte;004145;12060 +F811;Murello;CN;Piemonte;004146;12030 +F846;Narzole;CN;Piemonte;004147;12068 +F863;Neive;CN;Piemonte;004148;12052 +F883;Neviglie;CN;Piemonte;004149;12050 +F894;Niella Belbo;CN;Piemonte;004150;12050 +F895;Niella Tanaro;CN;Piemonte;004151;12060 +F961;Novello;CN;Piemonte;004152;12060 +F972;Nucetto;CN;Piemonte;004153;12070 +G066;Oncino;CN;Piemonte;004154;12030 +G114;Ormea;CN;Piemonte;004155;12078 +G183;Ostana;CN;Piemonte;004156;12030 +G228;Paesana;CN;Piemonte;004157;12034 +G240;Pagno;CN;Piemonte;004158;12030 +G302;Pamparato;CN;Piemonte;004159;12087 +G339;Paroldo;CN;Piemonte;004160;12070 +G457;Perletto;CN;Piemonte;004161;12070 +G458;Perlo;CN;Piemonte;004162;12070 +G526;Peveragno;CN;Piemonte;004163;12016 +G532;Pezzolo Valle Uzzone;CN;Piemonte;004164;12070 +G561;Pianfei;CN;Piemonte;004165;12080 +G575;Piasco;CN;Piemonte;004166;12026 +G625;Pietraporzio;CN;Piemonte;004167;12010 +G683;Piobesi d'Alba;CN;Piemonte;004168;12040 +G697;Piozzo;CN;Piemonte;004169;12060 +G742;Pocapaglia;CN;Piemonte;004170;12060 +G800;Polonghera;CN;Piemonte;004171;12030 +G837;Pontechianale;CN;Piemonte;004172;12020 +G970;Pradleves;CN;Piemonte;004173;12027 +H011;Prazzo;CN;Piemonte;004174;12028 +H059;Priero;CN;Piemonte;004175;12070 +H068;Priocca;CN;Piemonte;004176;12040 +H069;Priola;CN;Piemonte;004177;12070 +H085;Prunetto;CN;Piemonte;004178;12077 +H150;Racconigi;CN;Piemonte;004179;12035 +H247;Revello;CN;Piemonte;004180;12036 +H285;Rifreddo;CN;Piemonte;004181;12030 +H326;Rittana;CN;Piemonte;004182;12010 +H362;Roaschia;CN;Piemonte;004183;12010 +H363;Roascio;CN;Piemonte;004184;12073 +H377;Robilante;CN;Piemonte;004185;12017 +H378;Roburent;CN;Piemonte;004186;12080 +H385;Roccabruna;CN;Piemonte;004187;12020 +H391;Rocca Cigliè;CN;Piemonte;004188;12060 +H395;Rocca de' Baldi;CN;Piemonte;004189;12047 +H407;Roccaforte Mondovì;CN;Piemonte;004190;12088 +H447;Roccasparvera;CN;Piemonte;004191;12010 +H453;Roccavione;CN;Piemonte;004192;12018 +H462;Rocchetta Belbo;CN;Piemonte;004193;12050 +H472;Roddi;CN;Piemonte;004194;12060 +H473;Roddino;CN;Piemonte;004195;12050 +H474;Rodello;CN;Piemonte;004196;12050 +H578;Rossana;CN;Piemonte;004197;12020 +H633;Ruffia;CN;Piemonte;004198;12030 +H695;Sale delle Langhe;CN;Piemonte;004199;12070 +H704;Sale San Giovanni;CN;Piemonte;004200;12070 +H710;Saliceto;CN;Piemonte;004201;12079 +H716;Salmour;CN;Piemonte;004202;12040 +H727;Saluzzo;CN;Piemonte;004203;12037 +H746;Sambuco;CN;Piemonte;004204;12010 +H755;Sampeyre;CN;Piemonte;004205;12020 +H770;San Benedetto Belbo;CN;Piemonte;004206;12050 +H812;San Damiano Macra;CN;Piemonte;004207;12029 +H851;Sanfrè;CN;Piemonte;004208;12040 +H852;Sanfront;CN;Piemonte;004209;12030 +I037;San Michele Mondovì;CN;Piemonte;004210;12080 +I210;Sant'Albano Stura;CN;Piemonte;004211;12040 +I316;Santa Vittoria d'Alba;CN;Piemonte;004212;12069 +I367;Santo Stefano Belbo;CN;Piemonte;004213;12058 +I372;Santo Stefano Roero;CN;Piemonte;004214;12040 +I470;Savigliano;CN;Piemonte;004215;12038 +I484;Scagnello;CN;Piemonte;004216;12070 +I512;Scarnafigi;CN;Piemonte;004217;12030 +I646;Serralunga d'Alba;CN;Piemonte;004218;12050 +I659;Serravalle Langhe;CN;Piemonte;004219;12050 +I750;Sinio;CN;Piemonte;004220;12050 +I817;Somano;CN;Piemonte;004221;12060 +I822;Sommariva del Bosco;CN;Piemonte;004222;12048 +I823;Sommariva Perno;CN;Piemonte;004223;12040 +I985;Stroppo;CN;Piemonte;004224;12020 +L048;Tarantasca;CN;Piemonte;004225;12020 +L252;Torre Bormida;CN;Piemonte;004226;12050 +L241;Torre Mondovì;CN;Piemonte;004227;12080 +L278;Torre San Giorgio;CN;Piemonte;004228;12030 +L281;Torresina;CN;Piemonte;004229;12070 +L367;Treiso;CN;Piemonte;004230;12050 +L410;Trezzo Tinella;CN;Piemonte;004231;12050 +L427;Trinità;CN;Piemonte;004232;12049 +L558;Valdieri;CN;Piemonte;004233;12010 +L580;Valgrana;CN;Piemonte;004234;12020 +L631;Valloriate;CN;Piemonte;004235;12010 +L729;Venasca;CN;Piemonte;004237;12020 +L758;Verduno;CN;Piemonte;004238;12060 +L771;Vernante;CN;Piemonte;004239;12019 +L804;Verzuolo;CN;Piemonte;004240;12039 +L817;Vezza d'Alba;CN;Piemonte;004241;12040 +L841;Vicoforte;CN;Piemonte;004242;12080 +L888;Vignolo;CN;Piemonte;004243;12010 +L942;Villafalletto;CN;Piemonte;004244;12020 +L974;Villanova Mondovì;CN;Piemonte;004245;12089 +L990;Villanova Solaro;CN;Piemonte;004246;12030 +M015;Villar San Costanzo;CN;Piemonte;004247;12020 +M055;Vinadio;CN;Piemonte;004248;12010 +M063;Viola;CN;Piemonte;004249;12070 +M136;Vottignasco;CN;Piemonte;004250;12020 +A072;Agliano Terme;AT;Piemonte;005001;14041 +A173;Albugnano;AT;Piemonte;005002;14022 +A312;Antignano;AT;Piemonte;005003;14010 +A352;Aramengo;AT;Piemonte;005004;14020 +A479;Asti;AT;Piemonte;005005;14100 +A527;Azzano d'Asti;AT;Piemonte;005006;14030 +A588;Baldichieri d'Asti;AT;Piemonte;005007;14011 +A770;Belveglio;AT;Piemonte;005008;14040 +A812;Berzano di San Pietro;AT;Piemonte;005009;14020 +B221;Bruno;AT;Piemonte;005010;14046 +B236;Bubbio;AT;Piemonte;005011;14051 +B306;Buttigliera d'Asti;AT;Piemonte;005012;14021 +B376;Calamandrana;AT;Piemonte;005013;14042 +B418;Calliano Monferrato;AT;Piemonte;005014; +B425;Calosso;AT;Piemonte;005015;14052 +B469;Camerano Casasco;AT;Piemonte;005016;14020 +B594;Canelli;AT;Piemonte;005017;14053 +B633;Cantarana;AT;Piemonte;005018;14010 +B707;Capriglio;AT;Piemonte;005019;14014 +B991;Casorzo Monferrato;AT;Piemonte;005020; +C022;Cassinasco;AT;Piemonte;005021;14050 +C049;Castagnole delle Lanze;AT;Piemonte;005022;14054 +C047;Castagnole Monferrato;AT;Piemonte;005023;14030 +C064;Castel Boglione;AT;Piemonte;005024;14040 +C127;Castell'Alfero;AT;Piemonte;005025;14033 +C154;Castellero;AT;Piemonte;005026;14013 +C161;Castelletto Molina;AT;Piemonte;005027;14040 +A300;Castello di Annone;AT;Piemonte;005028;14034 +C226;Castelnuovo Belbo;AT;Piemonte;005029;14043 +C230;Castelnuovo Calcea;AT;Piemonte;005030;14040 +C232;Castelnuovo Don Bosco;AT;Piemonte;005031;14022 +C253;Castel Rocchero;AT;Piemonte;005032;14044 +C438;Cellarengo;AT;Piemonte;005033;14010 +C440;Celle Enomondo;AT;Piemonte;005034;14010 +C528;Cerreto d'Asti;AT;Piemonte;005035;14020 +C533;Cerro Tanaro;AT;Piemonte;005036;14030 +C583;Cessole;AT;Piemonte;005037;14050 +C658;Chiusano d'Asti;AT;Piemonte;005038;14025 +C701;Cinaglio;AT;Piemonte;005039;14020 +C739;Cisterna d'Asti;AT;Piemonte;005040;14010 +C804;Coazzolo;AT;Piemonte;005041;14054 +C807;Cocconato;AT;Piemonte;005042;14023 +D046;Corsione;AT;Piemonte;005044;14020 +D050;Cortandone;AT;Piemonte;005045;14013 +D051;Cortanze;AT;Piemonte;005046;14020 +D052;Cortazzone;AT;Piemonte;005047;14010 +D072;Cortiglione;AT;Piemonte;005048;14040 +D101;Cossombrato;AT;Piemonte;005049;14020 +D119;Costigliole d'Asti;AT;Piemonte;005050;14055 +D207;Cunico;AT;Piemonte;005051;14026 +D388;Dusino San Michele;AT;Piemonte;005052;14010 +D554;Ferrere;AT;Piemonte;005053;14012 +D678;Fontanile;AT;Piemonte;005054;14044 +D802;Frinco;AT;Piemonte;005055;14030 +E134;Grana Monferrato;AT;Piemonte;005056; +E159;Grazzano Badoglio;AT;Piemonte;005057;14035 +E295;Incisa Scapaccino;AT;Piemonte;005058;14045 +E338;Isola d'Asti;AT;Piemonte;005059;14057 +E633;Loazzolo;AT;Piemonte;005060;14051 +E917;Maranzana;AT;Piemonte;005061;14040 +E944;Maretto;AT;Piemonte;005062;14018 +F254;Moasca;AT;Piemonte;005063;14050 +F308;Mombaldone;AT;Piemonte;005064;14050 +F311;Mombaruzzo;AT;Piemonte;005065;14046 +F316;Mombercelli;AT;Piemonte;005066;14047 +F323;Monale;AT;Piemonte;005067;14013 +F325;Monastero Bormida;AT;Piemonte;005068;14058 +F336;Moncalvo;AT;Piemonte;005069;14036 +F343;Moncucco Torinese;AT;Piemonte;005070;14024 +F361;Mongardino;AT;Piemonte;005071;14040 +F386;Montabone;AT;Piemonte;005072;14040 +F390;Montafia;AT;Piemonte;005073;14014 +F409;Montaldo Scarampi;AT;Piemonte;005074;14048 +F468;Montechiaro d'Asti;AT;Piemonte;005075;14025 +F527;Montegrosso d'Asti;AT;Piemonte;005076;14048 +F556;Montemagno Monferrato;AT;Piemonte;005077; +F902;Nizza Monferrato;AT;Piemonte;005080;14049 +G048;Olmo Gentile;AT;Piemonte;005081;14050 +G358;Passerano Marmorito;AT;Piemonte;005082;14020 +G430;Penango;AT;Piemonte;005083;14030 +G593;Piea;AT;Piemonte;005084;14020 +G676;Pino d'Asti;AT;Piemonte;005085;14020 +G692;Piovà Massaia;AT;Piemonte;005086;14026 +G894;Portacomaro;AT;Piemonte;005087;14037 +H102;Quaranti;AT;Piemonte;005088;14040 +H219;Refrancore;AT;Piemonte;005089;14030 +H250;Revigliasco d'Asti;AT;Piemonte;005090;14010 +H366;Roatto;AT;Piemonte;005091;14018 +H376;Robella;AT;Piemonte;005092;14020 +H392;Rocca d'Arazzo;AT;Piemonte;005093;14030 +H451;Roccaverano;AT;Piemonte;005094;14050 +H466;Rocchetta Palafea;AT;Piemonte;005095;14042 +H468;Rocchetta Tanaro;AT;Piemonte;005096;14030 +H811;San Damiano d'Asti;AT;Piemonte;005097;14015 +H899;San Giorgio Scarampi;AT;Piemonte;005098;14059 +H987;San Martino Alfieri;AT;Piemonte;005099;14010 +I017;San Marzano Oliveto;AT;Piemonte;005100;14050 +I076;San Paolo Solbrito;AT;Piemonte;005101;14010 +I555;Scurzolengo;AT;Piemonte;005103;14030 +I637;Serole;AT;Piemonte;005104;14050 +I678;Sessame;AT;Piemonte;005105;14058 +I698;Settime;AT;Piemonte;005106;14020 +I781;Soglio;AT;Piemonte;005107;14020 +L168;Tigliole;AT;Piemonte;005108;14016 +L203;Tonco;AT;Piemonte;005109;14039 +L531;Vaglio Serra;AT;Piemonte;005111;14049 +L574;Valfenera;AT;Piemonte;005112;14017 +L807;Vesime;AT;Piemonte;005113;14059 +L829;Viale;AT;Piemonte;005114;14010 +L834;Viarigi;AT;Piemonte;005115;14030 +L879;Vigliano d'Asti;AT;Piemonte;005116;14040 +L945;Villafranca d'Asti;AT;Piemonte;005117;14018 +L984;Villanova d'Asti;AT;Piemonte;005118;14019 +M019;Villa San Secondo;AT;Piemonte;005119;14020 +M058;Vinchio;AT;Piemonte;005120;14040 +M302;Montiglio Monferrato;AT;Piemonte;005121;14026 +M434;Moransengo-Tonengo;AT;Piemonte;005122; +A052;Acqui Terme;AL;Piemonte;006001;15011 +A146;Albera Ligure;AL;Piemonte;006002;15060 +A182;Alessandria;AL;Piemonte;006003;15100,15121 +A189;Alfiano Natta;AL;Piemonte;006004;15021 +A197;Alice Bel Colle;AL;Piemonte;006005;15010 +A227;Altavilla Monferrato;AL;Piemonte;006007;15041 +A245;Alzano Scrivia;AL;Piemonte;006008;15050 +A436;Arquata Scrivia;AL;Piemonte;006009;15061 +A523;Avolasca;AL;Piemonte;006010;15050 +A605;Balzola;AL;Piemonte;006011;15031 +A689;Basaluzzo;AL;Piemonte;006012;15060 +A708;Bassignana;AL;Piemonte;006013;15042 +A738;Belforte Monferrato;AL;Piemonte;006014;15070 +A793;Bergamasco;AL;Piemonte;006015;15022 +A813;Berzano di Tortona;AL;Piemonte;006016;15050 +A889;Bistagno;AL;Piemonte;006017;15012 +A998;Borghetto di Borbera;AL;Piemonte;006018;15060 +B029;Borgoratto Alessandrino;AL;Piemonte;006019;15013 +B037;Borgo San Martino;AL;Piemonte;006020;15032 +B071;Bosco Marengo;AL;Piemonte;006021;15062 +B080;Bosio;AL;Piemonte;006022;15060 +B109;Bozzole;AL;Piemonte;006023;15040 +B179;Brignano-Frascata;AL;Piemonte;006024;15050 +B311;Cabella Ligure;AL;Piemonte;006025;15060 +B453;Camagna Monferrato;AL;Piemonte;006026;15030 +B482;Camino;AL;Piemonte;006027;15020 +B629;Cantalupo Ligure;AL;Piemonte;006028;15060 +B701;Capriata d'Orba;AL;Piemonte;006029;15060 +B736;Carbonara Scrivia;AL;Piemonte;006030;15050 +B765;Carentino;AL;Piemonte;006031;15026 +B769;Carezzano;AL;Piemonte;006032;15051 +B818;Carpeneto;AL;Piemonte;006033;15071 +B836;Carrega Ligure;AL;Piemonte;006034;15060 +B840;Carrosio;AL;Piemonte;006035;15060 +B847;Cartosio;AL;Piemonte;006036;15015 +B870;Casal Cermelli;AL;Piemonte;006037;15072 +B882;Casaleggio Boiro;AL;Piemonte;006038;15070 +B885;Casale Monferrato;AL;Piemonte;006039;15033 +B902;Casalnoceto;AL;Piemonte;006040;15052 +B941;Casasco;AL;Piemonte;006041;15050 +C027;Cassine;AL;Piemonte;006043;15016 +C030;Cassinelle;AL;Piemonte;006044;15070 +C137;Castellania Coppi;AL;Piemonte;006045; +C142;Castellar Guidobono;AL;Piemonte;006046;15050 +C148;Castellazzo Bormida;AL;Piemonte;006047;15073 +C156;Castelletto d'Erro;AL;Piemonte;006048;15010 +C158;Castelletto d'Orba;AL;Piemonte;006049;15060 +C160;Castelletto Merli;AL;Piemonte;006050;15020 +C162;Castelletto Monferrato;AL;Piemonte;006051;15040 +C229;Castelnuovo Bormida;AL;Piemonte;006052;15017 +C243;Castelnuovo Scrivia;AL;Piemonte;006053;15053 +C274;Castelspina;AL;Piemonte;006054;15070 +C387;Cavatore;AL;Piemonte;006055;15010 +C432;Cella Monte;AL;Piemonte;006056;15034 +C503;Cereseto;AL;Piemonte;006057;15020 +C507;Cerreto Grue;AL;Piemonte;006058;15050 +C531;Cerrina Monferrato;AL;Piemonte;006059;15020 +C962;Coniolo;AL;Piemonte;006060;15030 +C977;Conzano;AL;Piemonte;006061;15030 +D102;Costa Vescovato;AL;Piemonte;006062;15050 +D149;Cremolino;AL;Piemonte;006063;15010 +D272;Denice;AL;Piemonte;006065;15010 +D277;Dernice;AL;Piemonte;006066;15056 +D447;Fabbrica Curone;AL;Piemonte;006067;15054 +D528;Felizzano;AL;Piemonte;006068;15023 +D559;Fraconalto;AL;Piemonte;006069;15060 +D759;Francavilla Bisio;AL;Piemonte;006070;15060 +D770;Frascaro;AL;Piemonte;006071;15010 +D777;Frassinello Monferrato;AL;Piemonte;006072;15035 +D780;Frassineto Po;AL;Piemonte;006073;15040 +D797;Fresonara;AL;Piemonte;006074;15064 +D813;Frugarolo;AL;Piemonte;006075;15065 +D814;Fubine Monferrato;AL;Piemonte;006076; +D835;Gabiano;AL;Piemonte;006077;15020 +D890;Gamalero;AL;Piemonte;006078;15010 +D910;Garbagna;AL;Piemonte;006079;15050 +D944;Gavi;AL;Piemonte;006081;15066 +E015;Giarole;AL;Piemonte;006082;15036 +E164;Gremiasco;AL;Piemonte;006083;15056 +E188;Grognardo;AL;Piemonte;006084;15010 +E191;Grondona;AL;Piemonte;006085;15060 +E255;Guazzora;AL;Piemonte;006086;15050 +E360;Isola Sant'Antonio;AL;Piemonte;006087;15050 +E543;Lerma;AL;Piemonte;006088;15070 +E870;Malvicino;AL;Piemonte;006090;15015 +F015;Masio;AL;Piemonte;006091;15024 +F096;Melazzo;AL;Piemonte;006092;15010 +F131;Merana;AL;Piemonte;006093;15010 +F232;Mirabello Monferrato;AL;Piemonte;006094;15040 +F281;Molare;AL;Piemonte;006095;15074 +F293;Molino dei Torti;AL;Piemonte;006096;15050 +F313;Mombello Monferrato;AL;Piemonte;006097;15020 +F320;Momperone;AL;Piemonte;006098;15050 +F337;Moncestino;AL;Piemonte;006099;15020 +F365;Mongiardino Ligure;AL;Piemonte;006100;15060 +F374;Monleale;AL;Piemonte;006101;15059 +F387;Montacuto;AL;Piemonte;006102;15050 +F403;Montaldeo;AL;Piemonte;006103;15060 +F404;Montaldo Bormida;AL;Piemonte;006104;15010 +F455;Montecastello;AL;Piemonte;006105;15040 +F469;Montechiaro d'Acqui;AL;Piemonte;006106;15010 +F518;Montegioco;AL;Piemonte;006107;15050 +F562;Montemarzino;AL;Piemonte;006108;15050 +F707;Morano sul Po;AL;Piemonte;006109;15025 +F713;Morbello;AL;Piemonte;006110;15010 +F737;Mornese;AL;Piemonte;006111;15075 +F751;Morsasco;AL;Piemonte;006112;15010 +F814;Murisengo Monferrato;AL;Piemonte;006113; +F965;Novi Ligure;AL;Piemonte;006114;15067 +F995;Occimiano;AL;Piemonte;006115;15040 +F997;Odalengo Grande;AL;Piemonte;006116;15020 +F998;Odalengo Piccolo;AL;Piemonte;006117;15020 +G042;Olivola;AL;Piemonte;006118;15030 +G124;Orsara Bormida;AL;Piemonte;006119;15010 +G193;Ottiglio;AL;Piemonte;006120;15038 +G197;Ovada;AL;Piemonte;006121;15076 +G199;Oviglio;AL;Piemonte;006122;15026 +G204;Ozzano Monferrato;AL;Piemonte;006123;15039 +G215;Paderna;AL;Piemonte;006124;15050 +G334;Pareto;AL;Piemonte;006125;15010 +G338;Parodi Ligure;AL;Piemonte;006126;15060 +G367;Pasturana;AL;Piemonte;006127;15060 +G397;Pecetto di Valenza;AL;Piemonte;006128;15040 +G619;Pietra Marazzi;AL;Piemonte;006129;15040 +G807;Pomaro Monferrato;AL;Piemonte;006131;15040 +G839;Pontecurone;AL;Piemonte;006132;15055 +G858;Pontestura;AL;Piemonte;006133;15027 +G861;Ponti;AL;Piemonte;006134;15010 +G872;Ponzano Monferrato;AL;Piemonte;006135;15020 +G877;Ponzone;AL;Piemonte;006136;15010 +G960;Pozzol Groppo;AL;Piemonte;006137;15050 +G961;Pozzolo Formigaro;AL;Piemonte;006138;15068 +G987;Prasco;AL;Piemonte;006139;15010 +H021;Predosa;AL;Piemonte;006140;15077 +H104;Quargnento;AL;Piemonte;006141;15044 +H121;Quattordio;AL;Piemonte;006142;15028 +H272;Ricaldone;AL;Piemonte;006143;15010 +H334;Rivalta Bormida;AL;Piemonte;006144;15010 +H343;Rivarone;AL;Piemonte;006145;15040 +H406;Roccaforte Ligure;AL;Piemonte;006146;15060 +H414;Rocca Grimalda;AL;Piemonte;006147;15078 +H465;Rocchetta Ligure;AL;Piemonte;006148;15060 +H569;Rosignano Monferrato;AL;Piemonte;006149;15030 +H677;Sala Monferrato;AL;Piemonte;006150;15030 +H694;Sale;AL;Piemonte;006151;15045 +H810;San Cristoforo;AL;Piemonte;006152;15060 +H878;San Giorgio Monferrato;AL;Piemonte;006153;15020 +I144;San Salvatore Monferrato;AL;Piemonte;006154;15046 +I150;San Sebastiano Curone;AL;Piemonte;006155;15056 +I190;Sant'Agata Fossili;AL;Piemonte;006156;15050 +I429;Sardigliano;AL;Piemonte;006157;15060 +I432;Sarezzano;AL;Piemonte;006158;15050 +I645;Serralunga di Crea;AL;Piemonte;006159;15020 +I657;Serravalle Scrivia;AL;Piemonte;006160;15069 +I711;Sezzadio;AL;Piemonte;006161;15079 +I738;Silvano d'Orba;AL;Piemonte;006162;15060 +I798;Solero;AL;Piemonte;006163;15029 +I808;Solonghello;AL;Piemonte;006164;15020 +I901;Spigno Monferrato;AL;Piemonte;006165;15018 +I911;Spineto Scrivia;AL;Piemonte;006166;15050 +I941;Stazzano;AL;Piemonte;006167;15060 +I977;Strevi;AL;Piemonte;006168;15019 +L027;Tagliolo Monferrato;AL;Piemonte;006169;15070 +L059;Tassarolo;AL;Piemonte;006170;15060 +L139;Terruggia;AL;Piemonte;006171;15030 +L143;Terzo;AL;Piemonte;006172;15010 +L165;Ticineto;AL;Piemonte;006173;15040 +L304;Tortona;AL;Piemonte;006174;15057 +L403;Treville;AL;Piemonte;006175;15030 +L432;Trisobbio;AL;Piemonte;006176;15070 +L570;Valenza;AL;Piemonte;006177;15048 +L633;Valmacca;AL;Piemonte;006178;15040 +L881;Vignale Monferrato;AL;Piemonte;006179;15049 +L887;Vignole Borbera;AL;Piemonte;006180;15060 +L904;Viguzzolo;AL;Piemonte;006181;15058 +L931;Villadeati;AL;Piemonte;006182;15020 +L963;Villalvernia;AL;Piemonte;006183;15050 +L970;Villamiroglio;AL;Piemonte;006184;15020 +L972;Villanova Monferrato;AL;Piemonte;006185;15030 +M009;Villaromagnano;AL;Piemonte;006186;15050 +M077;Visone;AL;Piemonte;006187;15010 +M120;Volpedo;AL;Piemonte;006188;15059 +M121;Volpeglino;AL;Piemonte;006189;15050 +M123;Voltaggio;AL;Piemonte;006190;15060 +M388;Cassano Spinola;AL;Piemonte;006191;15063 +M397;Alluvioni Piovera;AL;Piemonte;006192; +M420;Lu e Cuccaro Monferrato;AL;Piemonte;006193; +A205;Allein;AO;Valle d'Aosta/Vallée d'Aoste;007001;11010 +A305;Antey-Saint-André;AO;Valle d'Aosta/Vallée d'Aoste;007002;11020 +A326;Aosta;AO;Valle d'Aosta/Vallée d'Aoste;007003;11100 +A424;Arnad;AO;Valle d'Aosta/Vallée d'Aoste;007004;11020 +A452;Arvier;AO;Valle d'Aosta/Vallée d'Aoste;007005;11011 +A521;Avise;AO;Valle d'Aosta/Vallée d'Aoste;007006;11010 +A094;Ayas;AO;Valle d'Aosta/Vallée d'Aoste;007007;11020 +A108;Aymavilles;AO;Valle d'Aosta/Vallée d'Aoste;007008;11010 +A643;Bard;AO;Valle d'Aosta/Vallée d'Aoste;007009;11020 +A877;Bionaz;AO;Valle d'Aosta/Vallée d'Aoste;007010;11010 +B192;Brissogne;AO;Valle d'Aosta/Vallée d'Aoste;007011;11020 +B230;Brusson;AO;Valle d'Aosta/Vallée d'Aoste;007012;11022 +C593;Challand-Saint-Anselme;AO;Valle d'Aosta/Vallée d'Aoste;007013;11020 +C594;Challand-Saint-Victor;AO;Valle d'Aosta/Vallée d'Aoste;007014;11020 +C595;Chambave;AO;Valle d'Aosta/Vallée d'Aoste;007015;11023 +B491;Chamois;AO;Valle d'Aosta/Vallée d'Aoste;007016;11020 +C596;Champdepraz;AO;Valle d'Aosta/Vallée d'Aoste;007017;11020 +B540;Champorcher;AO;Valle d'Aosta/Vallée d'Aoste;007018;11020 +C598;Charvensod;AO;Valle d'Aosta/Vallée d'Aoste;007019;11020 +C294;Châtillon;AO;Valle d'Aosta/Vallée d'Aoste;007020;11024 +C821;Cogne;AO;Valle d'Aosta/Vallée d'Aoste;007021;11012 +D012;Courmayeur;AO;Valle d'Aosta/Vallée d'Aoste;007022;11013 +D338;Donnas;AO;Valle d'Aosta/Vallée d'Aoste;007023;11020 +D356;Doues;AO;Valle d'Aosta/Vallée d'Aoste;007024;11010 +D402;Emarèse;AO;Valle d'Aosta/Vallée d'Aoste;007025;11020 +D444;Etroubles;AO;Valle d'Aosta/Vallée d'Aoste;007026;11014 +D537;Fénis;AO;Valle d'Aosta/Vallée d'Aoste;007027;11020 +D666;Fontainemore;AO;Valle d'Aosta/Vallée d'Aoste;007028;11020 +D839;Gaby;AO;Valle d'Aosta/Vallée d'Aoste;007029;11020 +E029;Gignod;AO;Valle d'Aosta/Vallée d'Aoste;007030;11010 +E165;Gressan;AO;Valle d'Aosta/Vallée d'Aoste;007031;11020 +E167;Gressoney-La-Trinité;AO;Valle d'Aosta/Vallée d'Aoste;007032;11020 +E168;Gressoney-Saint-Jean;AO;Valle d'Aosta/Vallée d'Aoste;007033;11025 +E273;Hône;AO;Valle d'Aosta/Vallée d'Aoste;007034;11020 +E306;Introd;AO;Valle d'Aosta/Vallée d'Aoste;007035;11010 +E369;Issime;AO;Valle d'Aosta/Vallée d'Aoste;007036;11020 +E371;Issogne;AO;Valle d'Aosta/Vallée d'Aoste;007037;11020 +E391;Jovençan;AO;Valle d'Aosta/Vallée d'Aoste;007038;11020 +A308;La Magdeleine;AO;Valle d'Aosta/Vallée d'Aoste;007039;11020 +E458;La Salle;AO;Valle d'Aosta/Vallée d'Aoste;007040;11015 +E470;La Thuile;AO;Valle d'Aosta/Vallée d'Aoste;007041;11016 +E587;Lillianes;AO;Valle d'Aosta/Vallée d'Aoste;007042;11020 +F367;Montjovet;AO;Valle d'Aosta/Vallée d'Aoste;007043;11020 +F726;Morgex;AO;Valle d'Aosta/Vallée d'Aoste;007044;11017 +F987;Nus;AO;Valle d'Aosta/Vallée d'Aoste;007045;11020 +G045;Ollomont;AO;Valle d'Aosta/Vallée d'Aoste;007046;11010 +G012;Oyace;AO;Valle d'Aosta/Vallée d'Aoste;007047;11010 +G459;Perloz;AO;Valle d'Aosta/Vallée d'Aoste;007048;11020 +G794;Pollein;AO;Valle d'Aosta/Vallée d'Aoste;007049;11020 +G545;Pontboset;AO;Valle d'Aosta/Vallée d'Aoste;007050;11020 +G860;Pontey;AO;Valle d'Aosta/Vallée d'Aoste;007051;11024 +G854;Pont-Saint-Martin;AO;Valle d'Aosta/Vallée d'Aoste;007052;11026 +H042;Pré-Saint-Didier;AO;Valle d'Aosta/Vallée d'Aoste;007053;11010 +H110;Quart;AO;Valle d'Aosta/Vallée d'Aoste;007054;11020 +H262;Rhêmes-Notre-Dame;AO;Valle d'Aosta/Vallée d'Aoste;007055;11010 +H263;Rhêmes-Saint-Georges;AO;Valle d'Aosta/Vallée d'Aoste;007056;11010 +H497;Roisan;AO;Valle d'Aosta/Vallée d'Aoste;007057;11010,11100 +H669;Saint-Christophe;AO;Valle d'Aosta/Vallée d'Aoste;007058;11020 +H670;Saint-Denis;AO;Valle d'Aosta/Vallée d'Aoste;007059;11023 +H671;Saint-Marcel;AO;Valle d'Aosta/Vallée d'Aoste;007060;11020 +H672;Saint-Nicolas;AO;Valle d'Aosta/Vallée d'Aoste;007061;11010 +H673;Saint-Oyen;AO;Valle d'Aosta/Vallée d'Aoste;007062;11014 +H674;Saint-Pierre;AO;Valle d'Aosta/Vallée d'Aoste;007063;11010 +H675;Saint-Rhémy-en-Bosses;AO;Valle d'Aosta/Vallée d'Aoste;007064;11010 +H676;Saint-Vincent;AO;Valle d'Aosta/Vallée d'Aoste;007065;11027 +I442;Sarre;AO;Valle d'Aosta/Vallée d'Aoste;007066;11010 +L217;Torgnon;AO;Valle d'Aosta/Vallée d'Aoste;007067;11020 +L582;Valgrisenche;AO;Valle d'Aosta/Vallée d'Aoste;007068;11010 +L643;Valpelline;AO;Valle d'Aosta/Vallée d'Aoste;007069;11010 +L647;Valsavarenche;AO;Valle d'Aosta/Vallée d'Aoste;007070;11010 +L654;Valtournenche;AO;Valle d'Aosta/Vallée d'Aoste;007071;11028 +L783;Verrayes;AO;Valle d'Aosta/Vallée d'Aoste;007072;11020 +C282;Verrès;AO;Valle d'Aosta/Vallée d'Aoste;007073;11029 +L981;Villeneuve;AO;Valle d'Aosta/Vallée d'Aoste;007074;11018 +A111;Airole;IM;Liguria;008001;18030 +A338;Apricale;IM;Liguria;008002;18035 +A344;Aquila d'Arroscia;IM;Liguria;008003; +A418;Armo;IM;Liguria;008004;18026 +A499;Aurigo;IM;Liguria;008005;18020 +A536;Badalucco;IM;Liguria;008006;18010 +A581;Bajardo;IM;Liguria;008007;18031 +A984;Bordighera;IM;Liguria;008008;18012 +A993;Borghetto d'Arroscia;IM;Liguria;008009;18020 +B020;Borgomaro;IM;Liguria;008010;18021 +B559;Camporosso;IM;Liguria;008011;18033 +B734;Caravonica;IM;Liguria;008012;18020 +C143;Castellaro;IM;Liguria;008014;18011 +C110;Castel Vittorio;IM;Liguria;008015;18030 +C511;Ceriana;IM;Liguria;008016;18034 +C559;Cervo;IM;Liguria;008017;18010 +C578;Cesio;IM;Liguria;008018;18022 +C657;Chiusanico;IM;Liguria;008019;18027 +C660;Chiusavecchia;IM;Liguria;008020;18027 +C718;Cipressa;IM;Liguria;008021;18017 +C755;Civezza;IM;Liguria;008022;18017 +D087;Cosio d'Arroscia;IM;Liguria;008023; +D114;Costarainera;IM;Liguria;008024;18017 +D293;Diano Arentino;IM;Liguria;008025;18013 +D296;Diano Castello;IM;Liguria;008026;18013 +D297;Diano Marina;IM;Liguria;008027;18013 +D298;Diano San Pietro;IM;Liguria;008028;18013 +D318;Dolceacqua;IM;Liguria;008029;18035 +D319;Dolcedo;IM;Liguria;008030;18020,18100 +E290;Imperia;IM;Liguria;008031;18100 +E346;Isolabona;IM;Liguria;008032;18035 +E719;Lucinasco;IM;Liguria;008033;18020 +F123;Mendatica;IM;Liguria;008034;18025 +F290;Molini di Triora;IM;Liguria;008035;18010 +F528;Montegrosso Pian Latte;IM;Liguria;008037;18025 +G041;Olivetta San Michele;IM;Liguria;008038;18030 +G164;Ospedaletti;IM;Liguria;008039;18014 +G454;Perinaldo;IM;Liguria;008040;18032 +G607;Pietrabruna;IM;Liguria;008041;18010 +G632;Pieve di Teco;IM;Liguria;008042;18026 +G660;Pigna;IM;Liguria;008043;18037 +G814;Pompeiana;IM;Liguria;008044;18015 +G840;Pontedassio;IM;Liguria;008045;18027 +G890;Pornassio;IM;Liguria;008046;18024 +H027;Prelà;IM;Liguria;008047;18020,18100 +H180;Ranzo;IM;Liguria;008048;18020 +H257;Rezzo;IM;Liguria;008049;18026 +H328;Riva Ligure;IM;Liguria;008050;18015 +H460;Rocchetta Nervina;IM;Liguria;008051;18030 +H763;San Bartolomeo al Mare;IM;Liguria;008052;18016 +H780;San Biagio della Cima;IM;Liguria;008053;18036 +H957;San Lorenzo al Mare;IM;Liguria;008054;18017 +I138;Sanremo;IM;Liguria;008055; +I365;Santo Stefano al Mare;IM;Liguria;008056;18010 +I556;Seborga;IM;Liguria;008057;18012 +I796;Soldano;IM;Liguria;008058;18036 +L024;Taggia;IM;Liguria;008059;18018 +L146;Terzorio;IM;Liguria;008060;18010 +L430;Triora;IM;Liguria;008061;18010 +L596;Vallebona;IM;Liguria;008062;18012 +L599;Vallecrosia;IM;Liguria;008063;18019 +L693;Vasia;IM;Liguria;008064;18020,18100 +L741;Ventimiglia;IM;Liguria;008065;18039 +L809;Vessalico;IM;Liguria;008066;18026 +L943;Villa Faraldi;IM;Liguria;008067;18010 +M387;Montalto Carpasio;IM;Liguria;008068; +A122;Alassio;SV;Liguria;009001;17021 +A145;Albenga;SV;Liguria;009002;17031 +A165;Albissola Marina;SV;Liguria;009003;17012 +A166;Albisola Superiore;SV;Liguria;009004;17011 +A226;Altare;SV;Liguria;009005;17041 +A278;Andora;SV;Liguria;009006;17051 +A422;Arnasco;SV;Liguria;009007;17032 +A593;Balestrino;SV;Liguria;009008;17020 +A647;Bardineto;SV;Liguria;009009;17057 +A796;Bergeggi;SV;Liguria;009010;17028 +A931;Boissano;SV;Liguria;009011;17054 +A999;Borghetto Santo Spirito;SV;Liguria;009012;17052 +B005;Borgio Verezzi;SV;Liguria;009013;17022 +B048;Bormida;SV;Liguria;009014;17045 +B369;Cairo Montenotte;SV;Liguria;009015;17014 +B409;Calice Ligure;SV;Liguria;009016;17020 +B416;Calizzano;SV;Liguria;009017;17057 +B748;Carcare;SV;Liguria;009018;17043 +B927;Casanova Lerrone;SV;Liguria;009019;17033 +C063;Castelbianco;SV;Liguria;009020;17030 +C276;Castelvecchio di Rocca Barbena;SV;Liguria;009021;17034 +C443;Celle Ligure;SV;Liguria;009022;17015 +C463;Cengio;SV;Liguria;009023;17056 +C510;Ceriale;SV;Liguria;009024;17023 +C729;Cisano sul Neva;SV;Liguria;009025;17035 +D095;Cosseria;SV;Liguria;009026;17017 +D264;Dego;SV;Liguria;009027;17058 +D424;Erli;SV;Liguria;009028;17030 +D600;Finale Ligure;SV;Liguria;009029;17024 +D927;Garlenda;SV;Liguria;009030;17033 +E064;Giustenice;SV;Liguria;009031;17027 +E066;Giusvalla;SV;Liguria;009032;17010 +E414;Laigueglia;SV;Liguria;009033;17053 +E632;Loano;SV;Liguria;009034;17025 +E816;Magliolo;SV;Liguria;009035;17020 +E860;Mallare;SV;Liguria;009036;17045 +F046;Massimino;SV;Liguria;009037;12071 +F213;Millesimo;SV;Liguria;009038;17017 +F226;Mioglia;SV;Liguria;009039;17040 +F813;Murialdo;SV;Liguria;009040;17013 +F847;Nasino;SV;Liguria;009041;17030 +F926;Noli;SV;Liguria;009042;17026 +G076;Onzo;SV;Liguria;009043;17037 +D522;Orco Feglino;SV;Liguria;009044;17024 +G144;Ortovero;SV;Liguria;009045;17037 +G155;Osiglia;SV;Liguria;009046;17010 +G281;Pallare;SV;Liguria;009047;17043 +G542;Piana Crixia;SV;Liguria;009048;17058 +G605;Pietra Ligure;SV;Liguria;009049;17027 +G741;Plodio;SV;Liguria;009050;17043 +G866;Pontinvrea;SV;Liguria;009051;17042 +H126;Quiliano;SV;Liguria;009052;17047 +H266;Rialto;SV;Liguria;009053;17020 +H452;Roccavignale;SV;Liguria;009054;17017 +I453;Sassello;SV;Liguria;009055;17046 +I480;Savona;SV;Liguria;009056;17100 +I926;Spotorno;SV;Liguria;009057;17028 +I946;Stella;SV;Liguria;009058;17044 +I947;Stellanello;SV;Liguria;009059;17020 +L152;Testico;SV;Liguria;009060;17020 +L190;Toirano;SV;Liguria;009061;17055 +L315;Tovo San Giacomo;SV;Liguria;009062;17020 +L499;Urbe;SV;Liguria;009063;17048 +L528;Vado Ligure;SV;Liguria;009064;17047 +L675;Varazze;SV;Liguria;009065;17019 +L730;Vendone;SV;Liguria;009066;17032 +L823;Vezzi Portio;SV;Liguria;009067;17028 +L975;Villanova d'Albenga;SV;Liguria;009068;17038 +M197;Zuccarello;SV;Liguria;009069;17039 +A388;Arenzano;GE;Liguria;010001;16011 +A506;Avegno;GE;Liguria;010002;16030 +A658;Bargagli;GE;Liguria;010003;16021 +A922;Bogliasco;GE;Liguria;010004;16031 +B067;Borzonasca;GE;Liguria;010005;16041 +B282;Busalla;GE;Liguria;010006;16012 +B490;Camogli;GE;Liguria;010007;16032 +B538;Campo Ligure;GE;Liguria;010008;16013 +B551;Campomorone;GE;Liguria;010009;16014 +B726;Carasco;GE;Liguria;010010;16042 +B939;Casarza Ligure;GE;Liguria;010011;16030 +B956;Casella;GE;Liguria;010012;16015 +C302;Castiglione Chiavarese;GE;Liguria;010013;16030 +C481;Ceranesi;GE;Liguria;010014;16014 +C621;Chiavari;GE;Liguria;010015;16043 +C673;Cicagna;GE;Liguria;010016;16044 +C823;Cogoleto;GE;Liguria;010017;16016 +C826;Cogorno;GE;Liguria;010018;16030 +C995;Coreglia Ligure;GE;Liguria;010019;16040 +D175;Crocefieschi;GE;Liguria;010020;16010 +D255;Davagna;GE;Liguria;010021;16022 +D509;Fascia;GE;Liguria;010022;16020 +D512;Favale di Malvaro;GE;Liguria;010023;16040 +D677;Fontanigorda;GE;Liguria;010024;16023 +D969;Genova;GE;Liguria;010025;16100,16121-16167 +E109;Gorreto;GE;Liguria;010026;16020 +E341;Isola del Cantone;GE;Liguria;010027;16017 +E488;Lavagna;GE;Liguria;010028;16033 +E519;Leivi;GE;Liguria;010029;16040 +E695;Lorsica;GE;Liguria;010030;16045 +E737;Lumarzo;GE;Liguria;010031;16024 +F020;Masone;GE;Liguria;010032;16010 +F098;Mele;GE;Liguria;010033;16010 +F173;Mezzanego;GE;Liguria;010034;16046 +F202;Mignanego;GE;Liguria;010035;16018 +F256;Moconesi;GE;Liguria;010036;16047 +F354;Moneglia;GE;Liguria;010037;16030 +F445;Montebruno;GE;Liguria;010038;16025 +F682;Montoggio;GE;Liguria;010039;16026 +F858;Ne;GE;Liguria;010040;16040 +F862;Neirone;GE;Liguria;010041;16040 +G093;Orero;GE;Liguria;010042;16015,16040 +G646;Pieve Ligure;GE;Liguria;010043;16030 +G913;Portofino;GE;Liguria;010044;16034 +H073;Propata;GE;Liguria;010045;16027 +H183;Rapallo;GE;Liguria;010046;16035 +H212;Recco;GE;Liguria;010047;16036 +H258;Rezzoaglio;GE;Liguria;010048;16048 +H536;Ronco Scrivia;GE;Liguria;010049;16019 +H546;Rondanina;GE;Liguria;010050;16025 +H581;Rossiglione;GE;Liguria;010051;16010 +H599;Rovegno;GE;Liguria;010052;16028 +H802;San Colombano Certenoli;GE;Liguria;010053;16040 +I225;Santa Margherita Ligure;GE;Liguria;010054;16038 +I346;Sant'Olcese;GE;Liguria;010055;16010 +I368;Santo Stefano d'Aveto;GE;Liguria;010056;16049 +I475;Savignone;GE;Liguria;010057;16010 +I640;Serra Riccò;GE;Liguria;010058;16010 +I693;Sestri Levante;GE;Liguria;010059;16039 +I852;Sori;GE;Liguria;010060;16030 +L167;Tiglieto;GE;Liguria;010061;16010 +L298;Torriglia;GE;Liguria;010062;16029 +L416;Tribogna;GE;Liguria;010063;16030 +L507;Uscio;GE;Liguria;010064;16030 +L546;Valbrevenna;GE;Liguria;010065;16010 +M105;Vobbia;GE;Liguria;010066;16010 +M182;Zoagli;GE;Liguria;010067;16030 +A261;Ameglia;SP;Liguria;011001;19031 +A373;Arcola;SP;Liguria;011002;19021 +A836;Beverino;SP;Liguria;011003;19020 +A932;Bolano;SP;Liguria;011004;19020 +A961;Bonassola;SP;Liguria;011005;19011 +A992;Borghetto di Vara;SP;Liguria;011006;19020 +B214;Brugnato;SP;Liguria;011007;19020 +B410;Calice al Cornoviglio;SP;Liguria;011008;19020 +B838;Carro;SP;Liguria;011009;19012 +B839;Carrodano;SP;Liguria;011010;19020 +C240;Castelnuovo Magra;SP;Liguria;011011;19033 +D265;Deiva Marina;SP;Liguria;011012;19013 +D655;Follo;SP;Liguria;011013;19020 +D758;Framura;SP;Liguria;011014;19014 +E463;La Spezia;SP;Liguria;011015;19100,19124 +E542;Lerici;SP;Liguria;011016;19032 +E560;Levanto;SP;Liguria;011017;19015 +E842;Maissana;SP;Liguria;011018;19010 +F609;Monterosso al Mare;SP;Liguria;011019;19016 +G143;Luni;SP;Liguria;011020;19034 +G664;Pignone;SP;Liguria;011021;19020 +G925;Portovenere;SP;Liguria;011022;19025 +H275;Riccò del Golfo di Spezia;SP;Liguria;011023;19020 +H304;Riomaggiore;SP;Liguria;011024;19017 +H461;Rocchetta di Vara;SP;Liguria;011025;19020 +I363;Santo Stefano di Magra;SP;Liguria;011026;19037 +I449;Sarzana;SP;Liguria;011027;19038 +E070;Sesta Godano;SP;Liguria;011028;19020 +L681;Varese Ligure;SP;Liguria;011029;19028 +L774;Vernazza;SP;Liguria;011030;19018 +L819;Vezzano Ligure;SP;Liguria;011031;19020 +M177;Zignago;SP;Liguria;011032;19020 +A085;Agra;VA;Lombardia;012001;21010 +A167;Albizzate;VA;Lombardia;012002;21041 +A290;Angera;VA;Lombardia;012003;21021 +A371;Arcisate;VA;Lombardia;012004;21051 +A441;Arsago Seprio;VA;Lombardia;012005;21010 +A531;Azzate;VA;Lombardia;012006;21022 +A532;Azzio;VA;Lombardia;012007;21030 +A619;Barasso;VA;Lombardia;012008;21020 +A728;Bedero Valcuvia;VA;Lombardia;012010;21039 +A819;Besano;VA;Lombardia;012011;21050 +A825;Besnate;VA;Lombardia;012012;21010 +A826;Besozzo;VA;Lombardia;012013;21023 +A845;Biandronno;VA;Lombardia;012014;21024 +A891;Bisuschio;VA;Lombardia;012015;21050 +A918;Bodio Lomnago;VA;Lombardia;012016;21020 +B126;Brebbia;VA;Lombardia;012017;21020 +B150;Brenta;VA;Lombardia;012019;21030 +B166;Brezzo di Bedero;VA;Lombardia;012020;21010 +B182;Brinzio;VA;Lombardia;012021;21030 +B191;Brissago-Valtravaglia;VA;Lombardia;012022;21030 +B219;Brunello;VA;Lombardia;012023;21020 +B228;Brusimpiano;VA;Lombardia;012024;21050 +B258;Buguggiate;VA;Lombardia;012025;21020 +B300;Busto Arsizio;VA;Lombardia;012026;21052 +B326;Cadegliano-Viconago;VA;Lombardia;012027;21031 +B368;Cairate;VA;Lombardia;012029;21050 +B634;Cantello;VA;Lombardia;012030;21050 +B732;Caravate;VA;Lombardia;012031;21032 +B754;Cardano al Campo;VA;Lombardia;012032;21010 +B796;Carnago;VA;Lombardia;012033;21040 +B805;Caronno Pertusella;VA;Lombardia;012034;21042 +B807;Caronno Varesino;VA;Lombardia;012035;21040 +B875;Casale Litta;VA;Lombardia;012036;21020 +B921;Casalzuigno;VA;Lombardia;012037;21030 +B949;Casciago;VA;Lombardia;012038;21020 +B987;Casorate Sempione;VA;Lombardia;012039;21011 +C004;Cassano Magnago;VA;Lombardia;012040;21012 +B999;Cassano Valcuvia;VA;Lombardia;012041;21030 +C139;Castellanza;VA;Lombardia;012042;21053 +B312;Castello Cabiaglio;VA;Lombardia;012043;21030 +C273;Castelseprio;VA;Lombardia;012044;21050 +C181;Castelveccana;VA;Lombardia;012045;21010 +C300;Castiglione Olona;VA;Lombardia;012046;21043 +C343;Castronno;VA;Lombardia;012047;21040 +C382;Cavaria con Premezzo;VA;Lombardia;012048;21044 +C409;Cazzago Brabbia;VA;Lombardia;012049;21020 +C732;Cislago;VA;Lombardia;012050;21040 +C751;Cittiglio;VA;Lombardia;012051;21033 +C796;Clivio;VA;Lombardia;012052;21050 +C810;Cocquio-Trevisago;VA;Lombardia;012053;21034 +C911;Comabbio;VA;Lombardia;012054;21020 +C922;Comerio;VA;Lombardia;012055;21025 +D144;Cremenaga;VA;Lombardia;012056;21030 +D185;Crosio della Valle;VA;Lombardia;012057;21020 +D192;Cuasso al Monte;VA;Lombardia;012058;21050 +D199;Cugliate-Fabiasco;VA;Lombardia;012059;21030 +D204;Cunardo;VA;Lombardia;012060;21035 +D217;Curiglia con Monteviasco;VA;Lombardia;012061;21010 +D238;Cuveglio;VA;Lombardia;012062;21030 +D239;Cuvio;VA;Lombardia;012063;21030 +D256;Daverio;VA;Lombardia;012064;21020 +D384;Dumenza;VA;Lombardia;012065;21010 +D385;Duno;VA;Lombardia;012066;21030 +D467;Fagnano Olona;VA;Lombardia;012067;21054 +D543;Ferno;VA;Lombardia;012068;21010 +D551;Ferrera di Varese;VA;Lombardia;012069;21030 +D869;Gallarate;VA;Lombardia;012070;21013 +D871;Galliate Lombardo;VA;Lombardia;012071;21020 +D946;Gavirate;VA;Lombardia;012072;21026 +D951;Gazzada Schianno;VA;Lombardia;012073;21045 +D963;Gemonio;VA;Lombardia;012074;21036 +D981;Gerenzano;VA;Lombardia;012075;21040 +D987;Germignaga;VA;Lombardia;012076;21010 +E079;Golasecca;VA;Lombardia;012077;21010 +E101;Gorla Maggiore;VA;Lombardia;012078;21050 +E102;Gorla Minore;VA;Lombardia;012079;21055 +E104;Gornate Olona;VA;Lombardia;012080;21040 +E144;Grantola;VA;Lombardia;012081;21030 +E292;Inarzo;VA;Lombardia;012082;21020 +E299;Induno Olona;VA;Lombardia;012083;21056 +E367;Ispra;VA;Lombardia;012084;21027 +E386;Jerago con Orago;VA;Lombardia;012085;21040 +E494;Lavena Ponte Tresa;VA;Lombardia;012086;21037 +E496;Laveno-Mombello;VA;Lombardia;012087;21014 +E510;Leggiuno;VA;Lombardia;012088;21038 +E665;Lonate Ceppino;VA;Lombardia;012089;21050 +E666;Lonate Pozzolo;VA;Lombardia;012090;21015 +E707;Lozza;VA;Lombardia;012091;21040 +E734;Luino;VA;Lombardia;012092;21016 +E769;Luvinate;VA;Lombardia;012093;21020 +E863;Malnate;VA;Lombardia;012096;21046 +E929;Marchirolo;VA;Lombardia;012097;21030 +E965;Marnate;VA;Lombardia;012098;21050 +F002;Marzio;VA;Lombardia;012099;21030 +F007;Masciago Primo;VA;Lombardia;012100;21030 +F134;Mercallo;VA;Lombardia;012101;21020 +F154;Mesenzana;VA;Lombardia;012102;21030 +F526;Montegrino Valtravaglia;VA;Lombardia;012103;21010 +F703;Monvalle;VA;Lombardia;012104;21020 +F711;Morazzone;VA;Lombardia;012105;21040 +F736;Mornago;VA;Lombardia;012106;21020 +G008;Oggiona con Santo Stefano;VA;Lombardia;012107;21040 +G028;Olgiate Olona;VA;Lombardia;012108;21057 +G103;Origgio;VA;Lombardia;012109;21040 +G105;Orino;VA;Lombardia;012110;21030 +G906;Porto Ceresio;VA;Lombardia;012113;21050 +G907;Porto Valtravaglia;VA;Lombardia;012114;21010 +H173;Rancio Valcuvia;VA;Lombardia;012115;21030 +H174;Ranco;VA;Lombardia;012116;21020 +H723;Saltrio;VA;Lombardia;012117;21050 +H736;Samarate;VA;Lombardia;012118;21017 +I441;Saronno;VA;Lombardia;012119;21047 +I688;Sesto Calende;VA;Lombardia;012120;21018 +I793;Solbiate Arno;VA;Lombardia;012121;21048 +I794;Solbiate Olona;VA;Lombardia;012122;21058 +I819;Somma Lombardo;VA;Lombardia;012123;21019 +L003;Sumirago;VA;Lombardia;012124;21040 +L032;Taino;VA;Lombardia;012125;21020 +L115;Ternate;VA;Lombardia;012126;21020 +L319;Tradate;VA;Lombardia;012127;21049 +L342;Travedona-Monate;VA;Lombardia;012128;21028 +A705;Tronzano Lago Maggiore;VA;Lombardia;012129;21010 +L480;Uboldo;VA;Lombardia;012130;21040 +L577;Valganna;VA;Lombardia;012131;21039 +L671;Varano Borghi;VA;Lombardia;012132;21020 +L682;Varese;VA;Lombardia;012133;21100 +L703;Vedano Olona;VA;Lombardia;012134;21040 +L733;Venegono Inferiore;VA;Lombardia;012136;21040 +L734;Venegono Superiore;VA;Lombardia;012137;21040 +L765;Vergiate;VA;Lombardia;012138;21029 +L876;Viggiù;VA;Lombardia;012139;21059 +M101;Vizzola Ticino;VA;Lombardia;012140;21010 +H872;Sangiano;VA;Lombardia;012141;21038 +M339;Maccagno con Pino e Veddasca;VA;Lombardia;012142;21061 +M425;Cadrezzate con Osmate;VA;Lombardia;012143; +M433;Bardello con Malgesso e Bregano;VA;Lombardia;012144; +A143;Albavilla;CO;Lombardia;013003;22031 +A153;Albese con Cassano;CO;Lombardia;013004;22032 +A164;Albiolo;CO;Lombardia;013005;22070 +A224;Alserio;CO;Lombardia;013006;22040 +A249;Alzate Brianza;CO;Lombardia;013007;22040 +A319;Anzano del Parco;CO;Lombardia;013009;22040 +A333;Appiano Gentile;CO;Lombardia;013010;22070 +A391;Argegno;CO;Lombardia;013011;22010 +A430;Arosio;CO;Lombardia;013012;22060 +A476;Asso;CO;Lombardia;013013;22033 +A670;Barni;CO;Lombardia;013015;22030 +A778;Bene Lario;CO;Lombardia;013021;22010 +A791;Beregazzo con Figliaro;CO;Lombardia;013022;22070 +A870;Binago;CO;Lombardia;013023;22070 +A898;Bizzarone;CO;Lombardia;013024;22020 +A904;Blessagno;CO;Lombardia;013025;22028 +A905;Blevio;CO;Lombardia;013026;22020 +B134;Bregnano;CO;Lombardia;013028;22070 +B144;Brenna;CO;Lombardia;013029;22040 +B172;Brienno;CO;Lombardia;013030;22010 +B218;Brunate;CO;Lombardia;013032;22034 +B262;Bulgarograsso;CO;Lombardia;013034;22070 +B313;Cabiate;CO;Lombardia;013035;22060 +B346;Cadorago;CO;Lombardia;013036;22071 +B355;Caglio;CO;Lombardia;013037;22030 +B513;Campione d'Italia;CO;Lombardia;013040;22060 +B639;Cantù;CO;Lombardia;013041;22063 +B641;Canzo;CO;Lombardia;013042;22035 +B653;Capiago Intimiano;CO;Lombardia;013043;22070 +B730;Carate Urio;CO;Lombardia;013044;22010 +B742;Carbonate;CO;Lombardia;013045;22070 +B778;Carimate;CO;Lombardia;013046;22060 +B785;Carlazzo;CO;Lombardia;013047;22010 +B851;Carugo;CO;Lombardia;013048;22060 +B974;Caslino d'Erba;CO;Lombardia;013052;22030 +B977;Casnate con Bernate;CO;Lombardia;013053;22070 +C020;Cassina Rizzardi;CO;Lombardia;013055;22070 +C206;Castelmarte;CO;Lombardia;013058;22030 +C220;Castelnuovo Bozzente;CO;Lombardia;013059;22070 +C381;Cavargna;CO;Lombardia;013062;22010 +C482;Cerano d'Intelvi;CO;Lombardia;013063;22020 +C516;Cermenate;CO;Lombardia;013064;22072 +C520;Cernobbio;CO;Lombardia;013065;22012 +C724;Cirimido;CO;Lombardia;013068;22070 +C787;Claino con Osteno;CO;Lombardia;013071;22010 +C902;Colonno;CO;Lombardia;013074;22010 +C933;Como;CO;Lombardia;013075;22100 +D041;Corrido;CO;Lombardia;013077;22010 +D147;Cremia;CO;Lombardia;013083;22010 +D196;Cucciago;CO;Lombardia;013084;22060 +D232;Cusino;CO;Lombardia;013085;22010 +D310;Dizzasco;CO;Lombardia;013087;22020 +D329;Domaso;CO;Lombardia;013089;22013 +D341;Dongo;CO;Lombardia;013090;22014 +D355;Dosso del Liro;CO;Lombardia;013092;22010 +D416;Erba;CO;Lombardia;013095;22036 +D445;Eupilio;CO;Lombardia;013097;22030 +D462;Faggeto Lario;CO;Lombardia;013098;22020 +D482;Faloppio;CO;Lombardia;013099;22020 +D531;Fenegrò;CO;Lombardia;013100;22070 +D579;Figino Serenza;CO;Lombardia;013101;22060 +D605;Fino Mornasco;CO;Lombardia;013102;22073 +D930;Garzeno;CO;Lombardia;013106;22010 +D974;Gera Lario;CO;Lombardia;013107;22010 +E139;Grandate;CO;Lombardia;013110;22070 +E141;Grandola ed Uniti;CO;Lombardia;013111;22010 +E172;Griante;CO;Lombardia;013113;22011 +E235;Guanzate;CO;Lombardia;013114;22070 +E309;Inverigo;CO;Lombardia;013118;22044 +E405;Laglio;CO;Lombardia;013119;22010 +E416;Laino;CO;Lombardia;013120;22020 +E428;Lambrugo;CO;Lombardia;013121;22045 +E462;Lasnigo;CO;Lombardia;013123;22030 +E569;Lezzeno;CO;Lombardia;013126;22025 +E593;Limido Comasco;CO;Lombardia;013128;22070 +E607;Lipomo;CO;Lombardia;013129;22030 +E623;Livo;CO;Lombardia;013130;22010 +E638;Locate Varesino;CO;Lombardia;013131;22070 +E659;Lomazzo;CO;Lombardia;013133;22074 +E679;Longone al Segrino;CO;Lombardia;013134;22030 +E735;Luisago;CO;Lombardia;013135;22070 +E749;Lurago d'Erba;CO;Lombardia;013136;22040 +E750;Lurago Marinone;CO;Lombardia;013137;22070 +E753;Lurate Caccivio;CO;Lombardia;013138;22075 +E830;Magreglio;CO;Lombardia;013139;22030 +E951;Mariano Comense;CO;Lombardia;013143;22066 +F017;Maslianico;CO;Lombardia;013144;22026 +F120;Menaggio;CO;Lombardia;013145;22017 +F151;Merone;CO;Lombardia;013147;22046 +F305;Moltrasio;CO;Lombardia;013152;22010 +F372;Monguzzo;CO;Lombardia;013153;22040 +F427;Montano Lucino;CO;Lombardia;013154;22070 +F564;Montemezzo;CO;Lombardia;013155;22010 +F688;Montorfano;CO;Lombardia;013157;22030 +F788;Mozzate;CO;Lombardia;013159;22076 +F828;Musso;CO;Lombardia;013160;22010 +F877;Nesso;CO;Lombardia;013161;22020 +F958;Novedrate;CO;Lombardia;013163;22060 +G025;Olgiate Comasco;CO;Lombardia;013165;22077 +G056;Oltrona di San Mamette;CO;Lombardia;013169;22070 +G126;Orsenigo;CO;Lombardia;013170;22030 +G415;Peglio;CO;Lombardia;013178;22010 +G556;Pianello del Lario;CO;Lombardia;013183;22010 +G665;Pigra;CO;Lombardia;013184;22020 +G737;Plesio;CO;Lombardia;013185;22010 +G773;Pognana Lario;CO;Lombardia;013186;22020 +G821;Ponna;CO;Lombardia;013187;22020 +G847;Ponte Lambro;CO;Lombardia;013188;22037 +G889;Porlezza;CO;Lombardia;013189;22018 +H074;Proserpio;CO;Lombardia;013192;22030 +H094;Pusiano;CO;Lombardia;013193;22030 +H255;Rezzago;CO;Lombardia;013195;22030 +H478;Rodero;CO;Lombardia;013197;22070 +H601;Rovellasca;CO;Lombardia;013201;22069 +H602;Rovello Porro;CO;Lombardia;013202;22070 +H679;Sala Comacina;CO;Lombardia;013203;22010 +H760;San Bartolomeo Val Cavargna;CO;Lombardia;013204;22010 +H840;San Fermo della Battaglia;CO;Lombardia;013206;22020 +I051;San Nazzaro Val Cavargna;CO;Lombardia;013207;22010 +I529;Schignano;CO;Lombardia;013211;22020 +I611;Senna Comasco;CO;Lombardia;013212;22070 +I856;Sorico;CO;Lombardia;013216;22010 +I860;Sormano;CO;Lombardia;013217;22030 +I943;Stazzona;CO;Lombardia;013218;22010 +L071;Tavernerio;CO;Lombardia;013222;22038 +L228;Torno;CO;Lombardia;013223;22020 +L413;Trezzone;CO;Lombardia;013226;22010 +L470;Turate;CO;Lombardia;013227;22078 +L547;Valbrona;CO;Lombardia;013229;22039 +L640;Valmorea;CO;Lombardia;013232;22070 +H259;Val Rezzo;CO;Lombardia;013233;22010 +C936;Valsolda;CO;Lombardia;013234;22010 +L715;Veleso;CO;Lombardia;013236;22020 +L737;Veniano;CO;Lombardia;013238;22070 +L748;Vercana;CO;Lombardia;013239;22013 +L792;Vertemate con Minoprio;CO;Lombardia;013242;22070 +L956;Villa Guardia;CO;Lombardia;013245;22079 +M156;Zelbio;CO;Lombardia;013246;22020 +I162;San Siro;CO;Lombardia;013248;22010 +M315;Gravedona ed Uniti;CO;Lombardia;013249; +M335;Bellagio;CO;Lombardia;013250;22021 +M336;Colverde;CO;Lombardia;013251;22041 +M341;Tremezzina;CO;Lombardia;013252;22016 +M383;Alta Valle Intelvi;CO;Lombardia;013253; +M394;Centro Valle Intelvi;CO;Lombardia;013254; +M412;Solbiate con Cagno;CO;Lombardia;013255; +M435;Uggiate con Ronago;CO;Lombardia;013256; +A135;Albaredo per San Marco;SO;Lombardia;014001;23010 +A172;Albosaggia;SO;Lombardia;014002;23010,23100 +A273;Andalo Valtellino;SO;Lombardia;014003;23014 +A337;Aprica;SO;Lombardia;014004;23031 +A382;Ardenno;SO;Lombardia;014005;23011 +A777;Bema;SO;Lombardia;014006;23010 +A787;Berbenno di Valtellina;SO;Lombardia;014007;23010 +A848;Bianzone;SO;Lombardia;014008;23030 +B049;Bormio;SO;Lombardia;014009;23032 +B255;Buglio in Monte;SO;Lombardia;014010;23010 +B366;Caiolo;SO;Lombardia;014011;23010 +B530;Campodolcino;SO;Lombardia;014012;23021 +B993;Caspoggio;SO;Lombardia;014013;23020 +C186;Castello dell'Acqua;SO;Lombardia;014014;23030 +C325;Castione Andevenno;SO;Lombardia;014015;23012 +C418;Cedrasco;SO;Lombardia;014016;23010 +C493;Cercino;SO;Lombardia;014017;23016 +C623;Chiavenna;SO;Lombardia;014018;23022 +C628;Chiesa in Valmalenco;SO;Lombardia;014019;23023 +C651;Chiuro;SO;Lombardia;014020;23030 +C709;Cino;SO;Lombardia;014021;23010 +C785;Civo;SO;Lombardia;014022;23010 +C903;Colorina;SO;Lombardia;014023;23010 +D088;Cosio Valtellino;SO;Lombardia;014024;23013 +D258;Dazio;SO;Lombardia;014025;23010 +D266;Delebio;SO;Lombardia;014026;23014 +D377;Dubino;SO;Lombardia;014027;23015 +D456;Faedo Valtellino;SO;Lombardia;014028;23020 +D694;Forcola;SO;Lombardia;014029;23010 +D830;Fusine;SO;Lombardia;014030;23010 +D990;Gerola Alta;SO;Lombardia;014031;23010 +E090;Gordona;SO;Lombardia;014032;23020 +E200;Grosio;SO;Lombardia;014033;23033 +E201;Grosotto;SO;Lombardia;014034;23034 +E342;Madesimo;SO;Lombardia;014035;23024 +E443;Lanzada;SO;Lombardia;014036;23020 +E621;Livigno;SO;Lombardia;014037;23030 +E705;Lovero;SO;Lombardia;014038;23030 +E896;Mantello;SO;Lombardia;014039;23016 +F070;Mazzo di Valtellina;SO;Lombardia;014040;23030 +F115;Mello;SO;Lombardia;014041;23010 +F153;Mese;SO;Lombardia;014043;23020 +F393;Montagna in Valtellina;SO;Lombardia;014044;23020 +F712;Morbegno;SO;Lombardia;014045;23017 +F956;Novate Mezzola;SO;Lombardia;014046;23025 +G410;Pedesina;SO;Lombardia;014047;23010 +G572;Piantedo;SO;Lombardia;014048;23010 +G576;Piateda;SO;Lombardia;014049;23020 +G718;Piuro;SO;Lombardia;014050;23020 +G431;Poggiridenti;SO;Lombardia;014051;23020 +G829;Ponte in Valtellina;SO;Lombardia;014052;23026 +G937;Postalesio;SO;Lombardia;014053;23010 +G993;Prata Camportaccio;SO;Lombardia;014054;23020 +H192;Rasura;SO;Lombardia;014055;23010 +H493;Rogolo;SO;Lombardia;014056;23010 +H752;Samolaco;SO;Lombardia;014057;23027 +H868;San Giacomo Filippo;SO;Lombardia;014058;23020 +I636;Sernio;SO;Lombardia;014059;23030 +I828;Sondalo;SO;Lombardia;014060;23035 +I829;Sondrio;SO;Lombardia;014061;23100 +I928;Spriana;SO;Lombardia;014062;23020 +L035;Talamona;SO;Lombardia;014063;23018 +L056;Tartano;SO;Lombardia;014064;23010 +L084;Teglio;SO;Lombardia;014065;23036 +L175;Tirano;SO;Lombardia;014066;23037 +L244;Torre di Santa Maria;SO;Lombardia;014067;23020 +L316;Tovo di Sant'Agata;SO;Lombardia;014068;23030 +L330;Traona;SO;Lombardia;014069;23019 +L392;Tresivio;SO;Lombardia;014070;23020 +L557;Valdidentro;SO;Lombardia;014071;23038 +L563;Valdisotto;SO;Lombardia;014072;23030 +L576;Valfurva;SO;Lombardia;014073;23030 +L638;Val Masino;SO;Lombardia;014074;23010 +L749;Verceia;SO;Lombardia;014075;23020 +L799;Vervio;SO;Lombardia;014076;23030 +L907;Villa di Chiavenna;SO;Lombardia;014077;23029 +L908;Villa di Tirano;SO;Lombardia;014078;23030 +A010;Abbiategrasso;MI;Lombardia;015002;20081 +A127;Albairate;MI;Lombardia;015005;20080 +A375;Arconate;MI;Lombardia;015007;20020 +A389;Arese;MI;Lombardia;015009;20044 +A413;Arluno;MI;Lombardia;015010;20004 +A473;Assago;MI;Lombardia;015011;20057 +A652;Bareggio;MI;Lombardia;015012;20008 +A697;Basiano;MI;Lombardia;015014;20060 +A699;Basiglio;MI;Lombardia;015015;20079 +A751;Bellinzago Lombardo;MI;Lombardia;015016;20060 +A804;Bernate Ticino;MI;Lombardia;015019;20010 +A820;Besate;MI;Lombardia;015022;20080 +A872;Binasco;MI;Lombardia;015024;20082 +A920;Boffalora sopra Ticino;MI;Lombardia;015026;20010 +A940;Bollate;MI;Lombardia;015027;20021 +B162;Bresso;MI;Lombardia;015032;20091 +B235;Bubbiano;MI;Lombardia;015035;20080 +B240;Buccinasco;MI;Lombardia;015036;20090 +B286;Buscate;MI;Lombardia;015038;20010 +B292;Bussero;MI;Lombardia;015040;20041 +B301;Busto Garolfo;MI;Lombardia;015041;20038 +B448;Calvignasco;MI;Lombardia;015042;20080 +B461;Cambiago;MI;Lombardia;015044;20040 +B593;Canegrate;MI;Lombardia;015046;20039 +B820;Carpiano;MI;Lombardia;015050;20074 +B850;Carugate;MI;Lombardia;015051;20061 +B938;Casarile;MI;Lombardia;015055;20059 +B989;Casorezzo;MI;Lombardia;015058;20003 +C003;Cassano d'Adda;MI;Lombardia;015059;20062 +C014;Cassina de' Pecchi;MI;Lombardia;015060;20051 +C033;Cassinetta di Lugagnano;MI;Lombardia;015061;20081 +C052;Castano Primo;MI;Lombardia;015062;20022 +C523;Cernusco sul Naviglio;MI;Lombardia;015070;20063 +C536;Cerro al Lambro;MI;Lombardia;015071;20070 +C537;Cerro Maggiore;MI;Lombardia;015072;20023 +C565;Cesano Boscone;MI;Lombardia;015074;20090 +C569;Cesate;MI;Lombardia;015076;20031 +C707;Cinisello Balsamo;MI;Lombardia;015077;20092 +C733;Cisliano;MI;Lombardia;015078;20046 +C895;Cologno Monzese;MI;Lombardia;015081;20093 +C908;Colturano;MI;Lombardia;015082;20075 +C986;Corbetta;MI;Lombardia;015085;20011 +D013;Cormano;MI;Lombardia;015086;20032 +D018;Cornaredo;MI;Lombardia;015087;20007 +D045;Corsico;MI;Lombardia;015093;20094 +D198;Cuggiono;MI;Lombardia;015096;20012 +D229;Cusago;MI;Lombardia;015097;20047 +D231;Cusano Milanino;MI;Lombardia;015098;20095 +D244;Dairago;MI;Lombardia;015099;20036 +D367;Dresano;MI;Lombardia;015101;20070 +D845;Gaggiano;MI;Lombardia;015103;20083 +D912;Garbagnate Milanese;MI;Lombardia;015105;20024 +D995;Gessate;MI;Lombardia;015106;20060 +E094;Gorgonzola;MI;Lombardia;015108;20064 +E170;Grezzago;MI;Lombardia;015110;20056 +E258;Gudo Visconti;MI;Lombardia;015112;20088 +E313;Inveruno;MI;Lombardia;015113;20001 +E317;Inzago;MI;Lombardia;015114;20065 +E395;Lacchiarella;MI;Lombardia;015115;20084 +E415;Lainate;MI;Lombardia;015116;20045 +E514;Legnano;MI;Lombardia;015118;20025 +E610;Liscate;MI;Lombardia;015122;20050 +E639;Locate di Triulzi;MI;Lombardia;015125;20085 +E801;Magenta;MI;Lombardia;015130;20013 +E819;Magnago;MI;Lombardia;015131;20020 +E921;Marcallo con Casone;MI;Lombardia;015134;20010 +F003;Masate;MI;Lombardia;015136;20060 +F084;Mediglia;MI;Lombardia;015139;20076 +F100;Melegnano;MI;Lombardia;015140;20077 +F119;Melzo;MI;Lombardia;015142;20066 +F155;Mesero;MI;Lombardia;015144;20010 +F205;Milano;MI;Lombardia;015146;20121-20129,20131-20139,20141-20149,20151-20159,20161-20162 +D033;Morimondo;MI;Lombardia;015150;20081 +F783;Motta Visconti;MI;Lombardia;015151;20086 +F874;Nerviano;MI;Lombardia;015154;20014 +F939;Nosate;MI;Lombardia;015155;20020 +F955;Novate Milanese;MI;Lombardia;015157;20026 +F968;Noviglio;MI;Lombardia;015158;20082 +G078;Opera;MI;Lombardia;015159;20073 +G181;Ossona;MI;Lombardia;015164;20002 +G206;Ozzero;MI;Lombardia;015165;20080 +G220;Paderno Dugnano;MI;Lombardia;015166;20037 +G316;Pantigliate;MI;Lombardia;015167;20048 +G324;Parabiago;MI;Lombardia;015168;20015 +G385;Paullo;MI;Lombardia;015169;20067 +C013;Pero;MI;Lombardia;015170;20016 +G488;Peschiera Borromeo;MI;Lombardia;015171;20068 +G502;Pessano con Bornago;MI;Lombardia;015172;20042 +G634;Pieve Emanuele;MI;Lombardia;015173;20072 +G686;Pioltello;MI;Lombardia;015175;20096 +G772;Pogliano Milanese;MI;Lombardia;015176;20005 +G955;Pozzo d'Adda;MI;Lombardia;015177;20060 +G965;Pozzuolo Martesana;MI;Lombardia;015178;20060 +H026;Pregnana Milanese;MI;Lombardia;015179;20006 +H240;Rescaldina;MI;Lombardia;015181;20027 +H264;Rho;MI;Lombardia;015182;20017 +H371;Robecchetto con Induno;MI;Lombardia;015183;20020 +H373;Robecco sul Naviglio;MI;Lombardia;015184;20087 +H470;Rodano;MI;Lombardia;015185;20053 +H560;Rosate;MI;Lombardia;015188;20088 +H623;Rozzano;MI;Lombardia;015189;20089 +H803;San Colombano al Lambro;MI;Lombardia;015191;20078 +H827;San Donato Milanese;MI;Lombardia;015192;20097 +H884;San Giorgio su Legnano;MI;Lombardia;015194;20034 +H930;San Giuliano Milanese;MI;Lombardia;015195;20098 +I361;Santo Stefano Ticino;MI;Lombardia;015200;20010 +I409;San Vittore Olona;MI;Lombardia;015201;20028 +I415;San Zenone al Lambro;MI;Lombardia;015202;20070 +I566;Sedriano;MI;Lombardia;015204;20018 +I577;Segrate;MI;Lombardia;015205;20054 +I602;Senago;MI;Lombardia;015206;20030 +I690;Sesto San Giovanni;MI;Lombardia;015209;20099 +I696;Settala;MI;Lombardia;015210;20049 +I700;Settimo Milanese;MI;Lombardia;015211;20019 +I786;Solaro;MI;Lombardia;015213;20033 +L408;Trezzano Rosa;MI;Lombardia;015219;20060 +L409;Trezzano sul Naviglio;MI;Lombardia;015220;20090 +L411;Trezzo sull'Adda;MI;Lombardia;015221;20056 +L415;Tribiano;MI;Lombardia;015222;20067 +L454;Truccazzano;MI;Lombardia;015224;20060 +L471;Turbigo;MI;Lombardia;015226;20029 +L665;Vanzago;MI;Lombardia;015229;20043 +L667;Vaprio d'Adda;MI;Lombardia;015230;20069 +L773;Vernate;MI;Lombardia;015236;20080 +L883;Vignate;MI;Lombardia;015237;20052 +M053;Vimodrone;MI;Lombardia;015242;20055 +M091;Vittuone;MI;Lombardia;015243;20009 +M102;Vizzolo Predabissi;MI;Lombardia;015244;20070 +M176;Zibido San Giacomo;MI;Lombardia;015247;20058 +L928;Villa Cortese;MI;Lombardia;015248;20035 +L664;Vanzaghello;MI;Lombardia;015249;20020 +A618;Baranzate;MI;Lombardia;015250;20021 +M424;Vermezzo con Zelo;MI;Lombardia;015251; +A057;Adrara San Martino;BG;Lombardia;016001;24060 +A058;Adrara San Rocco;BG;Lombardia;016002;24060 +A129;Albano Sant'Alessandro;BG;Lombardia;016003;24061 +A163;Albino;BG;Lombardia;016004;24021 +A214;Almè;BG;Lombardia;016005;24011 +A216;Almenno San Bartolomeo;BG;Lombardia;016006;24030 +A217;Almenno San Salvatore;BG;Lombardia;016007;24031 +A246;Alzano Lombardo;BG;Lombardia;016008;24022 +A259;Ambivere;BG;Lombardia;016009;24030 +A304;Antegnate;BG;Lombardia;016010;24051 +A365;Arcene;BG;Lombardia;016011;24040 +A383;Ardesio;BG;Lombardia;016012;24020 +A440;Arzago d'Adda;BG;Lombardia;016013;24040 +A511;Averara;BG;Lombardia;016014;24010 +A517;Aviatico;BG;Lombardia;016015;24020 +A528;Azzano San Paolo;BG;Lombardia;016016;24052 +A533;Azzone;BG;Lombardia;016017;24020 +A557;Bagnatica;BG;Lombardia;016018;24060 +A631;Barbata;BG;Lombardia;016019;24040 +A664;Bariano;BG;Lombardia;016020;24050 +A684;Barzana;BG;Lombardia;016021;24030 +A732;Bedulita;BG;Lombardia;016022;24030 +A786;Berbenno;BG;Lombardia;016023;24030 +A794;Bergamo;BG;Lombardia;016024;24100,24121-24129 +A815;Berzo San Fermo;BG;Lombardia;016025;24060 +A846;Bianzano;BG;Lombardia;016026;24060 +A903;Blello;BG;Lombardia;016027;24010 +A937;Bolgare;BG;Lombardia;016028;24060 +A950;Boltiere;BG;Lombardia;016029;24040 +A963;Bonate Sopra;BG;Lombardia;016030;24040 +A962;Bonate Sotto;BG;Lombardia;016031;24040 +B010;Borgo di Terzo;BG;Lombardia;016032;24060 +B083;Bossico;BG;Lombardia;016033;24060 +B088;Bottanuco;BG;Lombardia;016034;24040 +B112;Bracca;BG;Lombardia;016035;24010 +B123;Branzi;BG;Lombardia;016036;24010 +B137;Brembate;BG;Lombardia;016037;24041 +B138;Brembate di Sopra;BG;Lombardia;016038;24030 +B178;Brignano Gera d'Adda;BG;Lombardia;016040;24053 +B217;Brumano;BG;Lombardia;016041;24037 +B223;Brusaporto;BG;Lombardia;016042;24060 +B393;Calcinate;BG;Lombardia;016043;24050 +B395;Calcio;BG;Lombardia;016044;24054 +B434;Calusco d'Adda;BG;Lombardia;016046;24033 +B442;Calvenzano;BG;Lombardia;016047;24040 +B471;Camerata Cornello;BG;Lombardia;016048;24010 +B618;Canonica d'Adda;BG;Lombardia;016049;24040 +B661;Capizzone;BG;Lombardia;016050;24030 +B703;Capriate San Gervasio;BG;Lombardia;016051;24042 +B710;Caprino Bergamasco;BG;Lombardia;016052;24030 +B731;Caravaggio;BG;Lombardia;016053;24043 +B801;Carobbio degli Angeli;BG;Lombardia;016055;24060 +B803;Carona;BG;Lombardia;016056;24010 +B854;Carvico;BG;Lombardia;016057;24030 +B947;Casazza;BG;Lombardia;016058;24060 +B971;Casirate d'Adda;BG;Lombardia;016059;24040 +B978;Casnigo;BG;Lombardia;016060;24020 +C007;Cassiglio;BG;Lombardia;016061;24010 +C079;Castelli Calepio;BG;Lombardia;016062;24060 +C255;Castel Rozzone;BG;Lombardia;016063;24040 +C324;Castione della Presolana;BG;Lombardia;016064;24020 +C337;Castro;BG;Lombardia;016065;24063 +C396;Cavernago;BG;Lombardia;016066;24050 +C410;Cazzano Sant'Andrea;BG;Lombardia;016067;24026 +C456;Cenate Sopra;BG;Lombardia;016068;24060 +C457;Cenate Sotto;BG;Lombardia;016069;24069 +C459;Cene;BG;Lombardia;016070;24020 +C506;Cerete;BG;Lombardia;016071;24020 +C635;Chignolo d'Isola;BG;Lombardia;016072;24040 +C649;Chiuduno;BG;Lombardia;016073;24060 +C728;Cisano Bergamasco;BG;Lombardia;016074;24034 +C730;Ciserano;BG;Lombardia;016075;24040 +C759;Cividate al Piano;BG;Lombardia;016076;24050 +C800;Clusone;BG;Lombardia;016077;24023 +C835;Colere;BG;Lombardia;016078;24020 +C894;Cologno al Serio;BG;Lombardia;016079;24055 +C910;Colzate;BG;Lombardia;016080;24020 +C937;Comun Nuovo;BG;Lombardia;016081;24040 +D015;Corna Imagna;BG;Lombardia;016082;24030 +D066;Cortenuova;BG;Lombardia;016083;24050 +D110;Costa di Mezzate;BG;Lombardia;016084;24060 +D103;Costa Valle Imagna;BG;Lombardia;016085;24030 +D117;Costa Volpino;BG;Lombardia;016086;24062 +D126;Covo;BG;Lombardia;016087;24050 +D139;Credaro;BG;Lombardia;016088;24060 +D221;Curno;BG;Lombardia;016089;24035 +D233;Cusio;BG;Lombardia;016090;24010 +D245;Dalmine;BG;Lombardia;016091;24044 +D352;Dossena;BG;Lombardia;016092;24010 +D406;Endine Gaiano;BG;Lombardia;016093;24060 +D411;Entratico;BG;Lombardia;016094;24060 +D490;Fara Gera d'Adda;BG;Lombardia;016096;24045 +D491;Fara Olivana con Sola;BG;Lombardia;016097;24058 +D588;Filago;BG;Lombardia;016098;24040 +D604;Fino del Monte;BG;Lombardia;016099;24020 +D606;Fiorano al Serio;BG;Lombardia;016100;24020 +D672;Fontanella;BG;Lombardia;016101;24056 +D684;Fonteno;BG;Lombardia;016102;24060 +D688;Foppolo;BG;Lombardia;016103;24010 +D697;Foresto Sparso;BG;Lombardia;016104;24060 +D727;Fornovo San Giovanni;BG;Lombardia;016105;24040 +D817;Fuipiano Valle Imagna;BG;Lombardia;016106;24030 +D903;Gandellino;BG;Lombardia;016107;24020 +D905;Gandino;BG;Lombardia;016108;24024 +D906;Gandosso;BG;Lombardia;016109;24060 +D943;Gaverina Terme;BG;Lombardia;016110;24060 +D952;Gazzaniga;BG;Lombardia;016111;24025 +E006;Ghisalba;BG;Lombardia;016113;24050 +E100;Gorlago;BG;Lombardia;016114;24060 +E103;Gorle;BG;Lombardia;016115;24020 +E106;Gorno;BG;Lombardia;016116;24020 +E148;Grassobbio;BG;Lombardia;016117;24050 +E189;Gromo;BG;Lombardia;016118;24020 +E192;Grone;BG;Lombardia;016119;24060 +E219;Grumello del Monte;BG;Lombardia;016120;24064 +E353;Isola di Fondra;BG;Lombardia;016121;24010 +E370;Isso;BG;Lombardia;016122;24040 +E422;Lallio;BG;Lombardia;016123;24040 +E509;Leffe;BG;Lombardia;016124;24026 +E524;Lenna;BG;Lombardia;016125;24010 +E562;Levate;BG;Lombardia;016126;24040 +E640;Locatello;BG;Lombardia;016127;24030 +E704;Lovere;BG;Lombardia;016128;24065 +E751;Lurano;BG;Lombardia;016129;24050 +E770;Luzzana;BG;Lombardia;016130;24069 +E794;Madone;BG;Lombardia;016131;24040 +E901;Mapello;BG;Lombardia;016132;24030 +E987;Martinengo;BG;Lombardia;016133;24057 +F186;Mezzoldo;BG;Lombardia;016134;24010 +F243;Misano di Gera d'Adda;BG;Lombardia;016135;24040 +F276;Moio de' Calvi;BG;Lombardia;016136;24010 +F328;Monasterolo del Castello;BG;Lombardia;016137;24060 +F547;Montello;BG;Lombardia;016139;24060 +F720;Morengo;BG;Lombardia;016140;24050 +F738;Mornico al Serio;BG;Lombardia;016141;24050 +F786;Mozzanica;BG;Lombardia;016142;24050 +F791;Mozzo;BG;Lombardia;016143;24030 +F864;Nembro;BG;Lombardia;016144;24027 +G049;Olmo al Brembo;BG;Lombardia;016145;24010 +G050;Oltre il Colle;BG;Lombardia;016146;24013 +G054;Oltressenda Alta;BG;Lombardia;016147;24020 +G068;Oneta;BG;Lombardia;016148;24020 +G075;Onore;BG;Lombardia;016149;24020 +G108;Orio al Serio;BG;Lombardia;016150;24050 +G118;Ornica;BG;Lombardia;016151;24010 +G159;Osio Sopra;BG;Lombardia;016152;24040 +G160;Osio Sotto;BG;Lombardia;016153;24046 +G233;Pagazzano;BG;Lombardia;016154;24040 +G249;Paladina;BG;Lombardia;016155;24030 +G259;Palazzago;BG;Lombardia;016156;24030 +G295;Palosco;BG;Lombardia;016157;24050 +G346;Parre;BG;Lombardia;016158;24020 +G350;Parzanica;BG;Lombardia;016159;24060 +G412;Pedrengo;BG;Lombardia;016160;24066 +G418;Peia;BG;Lombardia;016161;24020 +G564;Pianico;BG;Lombardia;016162;24060 +G574;Piario;BG;Lombardia;016163;24020 +G579;Piazza Brembana;BG;Lombardia;016164;24014 +G583;Piazzatorre;BG;Lombardia;016165;24010 +G588;Piazzolo;BG;Lombardia;016166;24010 +G774;Pognano;BG;Lombardia;016167;24040 +F941;Ponte Nossa;BG;Lombardia;016168;24028 +G853;Ponteranica;BG;Lombardia;016169;24010 +G856;Ponte San Pietro;BG;Lombardia;016170;24036 +G864;Pontida;BG;Lombardia;016171;24030 +G867;Pontirolo Nuovo;BG;Lombardia;016172;24040 +G968;Pradalunga;BG;Lombardia;016173;24020 +H020;Predore;BG;Lombardia;016174;24060 +H036;Premolo;BG;Lombardia;016175;24020 +H046;Presezzo;BG;Lombardia;016176;24030 +H091;Pumenengo;BG;Lombardia;016177;24050 +H176;Ranica;BG;Lombardia;016178;24020 +H177;Ranzanico;BG;Lombardia;016179;24060 +H331;Riva di Solto;BG;Lombardia;016180;24060 +H492;Rogno;BG;Lombardia;016182;24060 +H509;Romano di Lombardia;BG;Lombardia;016183;24058 +H535;Roncobello;BG;Lombardia;016184;24010 +H544;Roncola;BG;Lombardia;016185;24030 +H584;Rota d'Imagna;BG;Lombardia;016186;24037 +H615;Rovetta;BG;Lombardia;016187;24020 +H910;San Giovanni Bianco;BG;Lombardia;016188;24015 +B310;San Paolo d'Argon;BG;Lombardia;016189;24060 +I079;San Pellegrino Terme;BG;Lombardia;016190;24016 +I168;Santa Brigida;BG;Lombardia;016191;24010 +I437;Sarnico;BG;Lombardia;016193;24067 +I506;Scanzorosciate;BG;Lombardia;016194;24020 +I530;Schilpario;BG;Lombardia;016195;24020 +I567;Sedrina;BG;Lombardia;016196;24010 +I597;Selvino;BG;Lombardia;016197;24020 +I628;Seriate;BG;Lombardia;016198;24068 +I629;Serina;BG;Lombardia;016199;24017 +I812;Solto Collina;BG;Lombardia;016200;24060 +I830;Songavazzo;BG;Lombardia;016201;24020 +I858;Sorisole;BG;Lombardia;016202;24010 +I869;Sotto il Monte Giovanni XXIII;BG;Lombardia;016203;24039 +I873;Sovere;BG;Lombardia;016204;24060 +I916;Spinone al Lago;BG;Lombardia;016205;24060 +I919;Spirano;BG;Lombardia;016206;24050 +I951;Stezzano;BG;Lombardia;016207;24040 +I986;Strozza;BG;Lombardia;016208;24030 +I997;Suisio;BG;Lombardia;016209;24040 +L037;Taleggio;BG;Lombardia;016210;24010 +L073;Tavernola Bergamasca;BG;Lombardia;016211;24060 +L087;Telgate;BG;Lombardia;016212;24060 +L118;Terno d'Isola;BG;Lombardia;016213;24030 +L251;Torre Boldone;BG;Lombardia;016214;24020 +L257;Torre de' Busi;BG;Lombardia;016215; +L265;Torre de' Roveri;BG;Lombardia;016216;24060 +L276;Torre Pallavicina;BG;Lombardia;016217;24050 +L388;Trescore Balneario;BG;Lombardia;016218;24069 +L400;Treviglio;BG;Lombardia;016219;24047 +L404;Treviolo;BG;Lombardia;016220;24048 +C789;Ubiale Clanezzo;BG;Lombardia;016221;24010 +L502;Urgnano;BG;Lombardia;016222;24059 +L544;Valbondione;BG;Lombardia;016223;24020 +L545;Valbrembo;BG;Lombardia;016224;24030 +L579;Valgoglio;BG;Lombardia;016225;24020 +L623;Valleve;BG;Lombardia;016226;24010 +L642;Valnegra;BG;Lombardia;016227;24010 +L655;Valtorta;BG;Lombardia;016229;24010 +L707;Vedeseta;BG;Lombardia;016230;24010 +L752;Verdellino;BG;Lombardia;016232;24040 +L753;Verdello;BG;Lombardia;016233;24049 +L795;Vertova;BG;Lombardia;016234;24029 +L827;Viadanica;BG;Lombardia;016235;24060 +L865;Vigano San Martino;BG;Lombardia;016236;24060 +L894;Vigolo;BG;Lombardia;016237;24060 +L929;Villa d'Adda;BG;Lombardia;016238;24030 +A215;Villa d'Almè;BG;Lombardia;016239;24018 +L936;Villa di Serio;BG;Lombardia;016240;24020 +L938;Villa d'Ogna;BG;Lombardia;016241;24020 +M045;Villongo;BG;Lombardia;016242;24060 +M050;Vilminore di Scalve;BG;Lombardia;016243;24020 +M144;Zandobbio;BG;Lombardia;016244;24060 +M147;Zanica;BG;Lombardia;016245;24050 +M184;Zogno;BG;Lombardia;016246;24019 +D111;Costa Serina;BG;Lombardia;016247;24010 +A193;Algua;BG;Lombardia;016248;24010 +D016;Cornalba;BG;Lombardia;016249;24017 +F085;Medolago;BG;Lombardia;016250;24030 +I813;Solza;BG;Lombardia;016251;24030 +M333;Sant'Omobono Terme;BG;Lombardia;016252;24038 +M334;Val Brembilla;BG;Lombardia;016253;24012 +A034;Acquafredda;BS;Lombardia;017001;25010 +A060;Adro;BS;Lombardia;017002;25030 +A082;Agnosine;BS;Lombardia;017003;25071 +A188;Alfianello;BS;Lombardia;017004;25020 +A288;Anfo;BS;Lombardia;017005;25070 +A293;Angolo Terme;BS;Lombardia;017006;25040 +A451;Artogne;BS;Lombardia;017007;25040 +A529;Azzano Mella;BS;Lombardia;017008;25020 +A569;Bagnolo Mella;BS;Lombardia;017009;25021 +A578;Bagolino;BS;Lombardia;017010;25072 +A630;Barbariga;BS;Lombardia;017011;25030 +A661;Barghe;BS;Lombardia;017012;25070 +A702;Bassano Bresciano;BS;Lombardia;017013;25020 +A729;Bedizzole;BS;Lombardia;017014;25081 +A799;Berlingo;BS;Lombardia;017015;25030 +A816;Berzo Demo;BS;Lombardia;017016;25040 +A817;Berzo Inferiore;BS;Lombardia;017017;25040 +A861;Bienno;BS;Lombardia;017018;25040 +A878;Bione;BS;Lombardia;017019;25070 +B035;Borgo San Giacomo;BS;Lombardia;017020;25022 +B040;Borgosatollo;BS;Lombardia;017021;25010 +B054;Borno;BS;Lombardia;017022;25042 +B091;Botticino;BS;Lombardia;017023;25082 +B100;Bovegno;BS;Lombardia;017024;25061 +B102;Bovezzo;BS;Lombardia;017025;25073 +B120;Brandico;BS;Lombardia;017026;25030 +B124;Braone;BS;Lombardia;017027;25040 +B149;Breno;BS;Lombardia;017028;25043 +B157;Brescia;BS;Lombardia;017029;25100,25121-25136 +B184;Brione;BS;Lombardia;017030;25060 +B365;Caino;BS;Lombardia;017031;25070 +B394;Calcinato;BS;Lombardia;017032;25011 +B436;Calvagese della Riviera;BS;Lombardia;017033;25080 +B450;Calvisano;BS;Lombardia;017034;25012 +B664;Capo di Ponte;BS;Lombardia;017035;25044 +B676;Capovalle;BS;Lombardia;017036;25070 +B698;Capriano del Colle;BS;Lombardia;017037;25020 +B711;Capriolo;BS;Lombardia;017038;25031 +B817;Carpenedolo;BS;Lombardia;017039;25013 +C055;Castegnato;BS;Lombardia;017040;25045 +C072;Castelcovati;BS;Lombardia;017041;25030 +C208;Castel Mella;BS;Lombardia;017042;25030 +C293;Castenedolo;BS;Lombardia;017043;25014 +C330;Casto;BS;Lombardia;017044;25070 +C332;Castrezzato;BS;Lombardia;017045;25030 +C408;Cazzago San Martino;BS;Lombardia;017046;25046 +C417;Cedegolo;BS;Lombardia;017047;25051 +C439;Cellatica;BS;Lombardia;017048;25060 +C549;Cerveno;BS;Lombardia;017049;25040 +C585;Ceto;BS;Lombardia;017050;25040 +C591;Cevo;BS;Lombardia;017051;25040 +C618;Chiari;BS;Lombardia;017052;25032 +C685;Cigole;BS;Lombardia;017053;25020 +C691;Cimbergo;BS;Lombardia;017054;25050 +C760;Cividate Camuno;BS;Lombardia;017055;25040 +C806;Coccaglio;BS;Lombardia;017056;25030 +C850;Collebeato;BS;Lombardia;017057;25060 +C883;Collio;BS;Lombardia;017058;25060 +C893;Cologne;BS;Lombardia;017059;25033 +C925;Comezzano-Cizzago;BS;Lombardia;017060;25030 +C948;Concesio;BS;Lombardia;017061;25062 +D058;Corte Franca;BS;Lombardia;017062;25040 +D064;Corteno Golgi;BS;Lombardia;017063;25040 +D082;Corzano;BS;Lombardia;017064;25030 +D251;Darfo Boario Terme;BS;Lombardia;017065;25047 +D270;Dello;BS;Lombardia;017066;25020 +D284;Desenzano del Garda;BS;Lombardia;017067;25015 +D391;Edolo;BS;Lombardia;017068;25048 +D421;Erbusco;BS;Lombardia;017069;25030 +D434;Esine;BS;Lombardia;017070;25040 +D576;Fiesse;BS;Lombardia;017071;25020 +D634;Flero;BS;Lombardia;017072;25020 +D891;Gambara;BS;Lombardia;017073;25020 +D917;Gardone Riviera;BS;Lombardia;017074;25083 +D918;Gardone Val Trompia;BS;Lombardia;017075;25063 +D924;Gargnano;BS;Lombardia;017076;25084 +D940;Gavardo;BS;Lombardia;017077;25085 +D999;Ghedi;BS;Lombardia;017078;25016 +E010;Gianico;BS;Lombardia;017079;25040 +E116;Gottolengo;BS;Lombardia;017080;25023 +E271;Gussago;BS;Lombardia;017081;25064 +E280;Idro;BS;Lombardia;017082;25074 +E297;Incudine;BS;Lombardia;017083;25040 +E325;Irma;BS;Lombardia;017084;25061 +E333;Iseo;BS;Lombardia;017085;25049 +E364;Isorella;BS;Lombardia;017086;25010 +E497;Lavenone;BS;Lombardia;017087;25074 +E526;Leno;BS;Lombardia;017088;25024 +E596;Limone sul Garda;BS;Lombardia;017089;25010 +E652;Lodrino;BS;Lombardia;017090;25060 +E654;Lograto;BS;Lombardia;017091;25030 +M312;Lonato del Garda;BS;Lombardia;017092; +E673;Longhena;BS;Lombardia;017093;25030 +E698;Losine;BS;Lombardia;017094;25050 +E706;Lozio;BS;Lombardia;017095;25040 +E738;Lumezzane;BS;Lombardia;017096;25065 +E787;Maclodio;BS;Lombardia;017097;25030 +E800;Magasa;BS;Lombardia;017098;25080 +E841;Mairano;BS;Lombardia;017099;25030 +E851;Malegno;BS;Lombardia;017100;25053 +E865;Malonno;BS;Lombardia;017101;25040 +E883;Manerba del Garda;BS;Lombardia;017102;25080 +E884;Manerbio;BS;Lombardia;017103;25025 +E928;Marcheno;BS;Lombardia;017104;25060 +E961;Marmentino;BS;Lombardia;017105;25060 +E967;Marone;BS;Lombardia;017106;25054 +F063;Mazzano;BS;Lombardia;017107;25080 +F216;Milzano;BS;Lombardia;017108;25020 +F373;Moniga del Garda;BS;Lombardia;017109;25080 +F375;Monno;BS;Lombardia;017110;25040 +F532;Monte Isola;BS;Lombardia;017111;25050 +F672;Monticelli Brusati;BS;Lombardia;017112;25040 +F471;Montichiari;BS;Lombardia;017113;25018 +F680;Montirone;BS;Lombardia;017114;25010 +F806;Mura;BS;Lombardia;017115;25070 +F820;Muscoline;BS;Lombardia;017116;25080 +F851;Nave;BS;Lombardia;017117;25075 +F884;Niardo;BS;Lombardia;017118;25050 +F989;Nuvolento;BS;Lombardia;017119;25080 +F990;Nuvolera;BS;Lombardia;017120;25080 +G001;Odolo;BS;Lombardia;017121;25076 +G006;Offlaga;BS;Lombardia;017122;25020 +G061;Ome;BS;Lombardia;017123;25050 +G074;Ono San Pietro;BS;Lombardia;017124;25040 +G149;Orzinuovi;BS;Lombardia;017125;25034 +G150;Orzivecchi;BS;Lombardia;017126;25030 +G170;Ospitaletto;BS;Lombardia;017127;25035 +G179;Ossimo;BS;Lombardia;017128;25050 +G213;Padenghe sul Garda;BS;Lombardia;017129;25080 +G217;Paderno Franciacorta;BS;Lombardia;017130;25050 +G247;Paisco Loveno;BS;Lombardia;017131;25050 +G248;Paitone;BS;Lombardia;017132;25080 +G264;Palazzolo sull'Oglio;BS;Lombardia;017133;25036 +G327;Paratico;BS;Lombardia;017134;25030 +G354;Paspardo;BS;Lombardia;017135;25050 +G361;Passirano;BS;Lombardia;017136;25050 +G391;Pavone del Mella;BS;Lombardia;017137;25020 +G407;San Paolo;BS;Lombardia;017138;25020 +G474;Pertica Alta;BS;Lombardia;017139;25070 +G475;Pertica Bassa;BS;Lombardia;017140;25078 +G529;Pezzaze;BS;Lombardia;017141;25060 +G546;Pian Camuno;BS;Lombardia;017142;25050 +G710;Pisogne;BS;Lombardia;017143;25055 +G779;Polaveno;BS;Lombardia;017144;25060 +G801;Polpenazze del Garda;BS;Lombardia;017145;25080 +G815;Pompiano;BS;Lombardia;017146;25030 +G818;Poncarale;BS;Lombardia;017147;25020 +G844;Ponte di Legno;BS;Lombardia;017148;25056 +G859;Pontevico;BS;Lombardia;017149;25026 +G869;Pontoglio;BS;Lombardia;017150;25037 +G959;Pozzolengo;BS;Lombardia;017151;25010 +G977;Pralboino;BS;Lombardia;017152;25020 +H043;Preseglie;BS;Lombardia;017153;25070 +H055;Prevalle;BS;Lombardia;017155;25080 +H078;Provaglio d'Iseo;BS;Lombardia;017156;25050 +H077;Provaglio Val Sabbia;BS;Lombardia;017157;25070 +H086;Puegnago del Garda;BS;Lombardia;017158; +H140;Quinzano d'Oglio;BS;Lombardia;017159;25027 +H230;Remedello;BS;Lombardia;017160;25010 +H256;Rezzato;BS;Lombardia;017161;25086 +H410;Roccafranca;BS;Lombardia;017162;25030 +H477;Rodengo Saiano;BS;Lombardia;017163;25050 +H484;Roè Volciano;BS;Lombardia;017164;25077 +H525;Roncadelle;BS;Lombardia;017165;25030 +H598;Rovato;BS;Lombardia;017166;25038 +H630;Rudiano;BS;Lombardia;017167;25030 +H650;Sabbio Chiese;BS;Lombardia;017168;25070 +H699;Sale Marasino;BS;Lombardia;017169;25057 +H717;Salò;BS;Lombardia;017170;25087 +H838;San Felice del Benaco;BS;Lombardia;017171;25010 +H865;San Gervasio Bresciano;BS;Lombardia;017172;25020 +I412;San Zeno Naviglio;BS;Lombardia;017173;25010 +I433;Sarezzo;BS;Lombardia;017174;25068 +I476;Saviore dell'Adamello;BS;Lombardia;017175;25040 +I588;Sellero;BS;Lombardia;017176;25050 +I607;Seniga;BS;Lombardia;017177;25020 +I631;Serle;BS;Lombardia;017178;25080 +I633;Sirmione;BS;Lombardia;017179;25019 +I782;Soiano del Lago;BS;Lombardia;017180;25080 +I831;Sonico;BS;Lombardia;017181;25048 +L002;Sulzano;BS;Lombardia;017182;25058 +C698;Tavernole sul Mella;BS;Lombardia;017183;25060 +L094;Temù;BS;Lombardia;017184;25050 +L169;Tignale;BS;Lombardia;017185;25080 +L210;Torbole Casaglia;BS;Lombardia;017186;25030 +L312;Toscolano-Maderno;BS;Lombardia;017187;25088 +L339;Travagliato;BS;Lombardia;017188;25039 +L372;Tremosine sul Garda;BS;Lombardia;017189; +L380;Trenzano;BS;Lombardia;017190;25030 +L406;Treviso Bresciano;BS;Lombardia;017191;25070 +L494;Urago d'Oglio;BS;Lombardia;017192;25030 +L626;Vallio Terme;BS;Lombardia;017193;25080 +L468;Valvestino;BS;Lombardia;017194;25080 +L777;Verolanuova;BS;Lombardia;017195;25028 +L778;Verolavecchia;BS;Lombardia;017196;25029 +L812;Vestone;BS;Lombardia;017197;25078 +L816;Vezza d'Oglio;BS;Lombardia;017198;25059 +L919;Villa Carcina;BS;Lombardia;017199;25069 +L923;Villachiara;BS;Lombardia;017200;25030 +L995;Villanuova sul Clisi;BS;Lombardia;017201;25089 +M065;Vione;BS;Lombardia;017202;25050 +M070;Visano;BS;Lombardia;017203;25010 +M104;Vobarno;BS;Lombardia;017204;25079 +M188;Zone;BS;Lombardia;017205;25050 +G549;Piancogno;BS;Lombardia;017206;25052 +A118;Alagna;PV;Lombardia;018001;27020 +A171;Albonese;PV;Lombardia;018003;27020 +A175;Albuzzano;PV;Lombardia;018004;27010 +A387;Arena Po;PV;Lombardia;018005;27040 +A538;Badia Pavese;PV;Lombardia;018006;27010 +A550;Bagnaria;PV;Lombardia;018007;27050 +A634;Barbianello;PV;Lombardia;018008;27041 +A690;Bascapè;PV;Lombardia;018009;27010 +A712;Bastida Pancarana;PV;Lombardia;018011;27050 +A718;Battuda;PV;Lombardia;018012;27020 +A741;Belgioioso;PV;Lombardia;018013;27011 +A792;Bereguardo;PV;Lombardia;018014;27021 +A989;Borgarello;PV;Lombardia;018015;27010 +B028;Borgo Priolo;PV;Lombardia;018016;27040 +B030;Borgoratto Mormorolo;PV;Lombardia;018017;27040 +B038;Borgo San Siro;PV;Lombardia;018018;27020 +B051;Bornasco;PV;Lombardia;018019;27010 +B082;Bosnasco;PV;Lombardia;018020;27040 +B117;Brallo di Pregola;PV;Lombardia;018021;27050 +B142;Breme;PV;Lombardia;018022;27020 +B159;Bressana Bottarone;PV;Lombardia;018023;27042 +B201;Broni;PV;Lombardia;018024;27043 +B447;Calvignano;PV;Lombardia;018025;27040 +B567;Campospinoso Albaredo;PV;Lombardia;018026; +B587;Candia Lomellina;PV;Lombardia;018027;27031 +B613;Canneto Pavese;PV;Lombardia;018029;27044 +B741;Carbonara al Ticino;PV;Lombardia;018030;27020 +B929;Casanova Lonati;PV;Lombardia;018031;27041 +B945;Casatisma;PV;Lombardia;018032;27040 +B954;Casei Gerola;PV;Lombardia;018033;27050 +B988;Casorate Primo;PV;Lombardia;018034;27022 +C038;Cassolnovo;PV;Lombardia;018035;27023 +C050;Castana;PV;Lombardia;018036;27040 +C053;Casteggio;PV;Lombardia;018037;27045 +C157;Castelletto di Branduzzo;PV;Lombardia;018038;27040 +C184;Castello d'Agogna;PV;Lombardia;018039;27030 +C213;Castelnovetto;PV;Lombardia;018040;27030 +C360;Cava Manara;PV;Lombardia;018041;27051 +C414;Cecima;PV;Lombardia;018042;27050 +C484;Ceranova;PV;Lombardia;018043;27010 +C508;Ceretto Lomellina;PV;Lombardia;018044;27030 +C509;Cergnago;PV;Lombardia;018045;27020 +C541;Certosa di Pavia;PV;Lombardia;018046;27012 +C551;Cervesina;PV;Lombardia;018047;27050 +C637;Chignolo Po;PV;Lombardia;018048;27013 +C684;Cigognola;PV;Lombardia;018049;27040 +C686;Cilavegna;PV;Lombardia;018050;27024 +C813;Codevilla;PV;Lombardia;018051;27050 +C958;Confienza;PV;Lombardia;018052;27030 +C979;Copiano;PV;Lombardia;018053;27010 +C982;Corana;PV;Lombardia;018054;27050 +D081;Corvino San Quirico;PV;Lombardia;018057;27050 +D109;Costa de' Nobili;PV;Lombardia;018058;27010 +D127;Cozzo;PV;Lombardia;018059;27030 +B824;Cura Carpignano;PV;Lombardia;018060;27010 +D348;Dorno;PV;Lombardia;018061;27020 +D552;Ferrera Erbognone;PV;Lombardia;018062;27032 +D594;Filighera;PV;Lombardia;018063;27010 +D732;Fortunago;PV;Lombardia;018064;27040 +D771;Frascarolo;PV;Lombardia;018065;27030 +D873;Galliavola;PV;Lombardia;018066;27034 +D892;Gambarana;PV;Lombardia;018067;27030 +D901;Gambolò;PV;Lombardia;018068;27025 +D925;Garlasco;PV;Lombardia;018069;27026 +D980;Gerenzago;PV;Lombardia;018071;27010 +E062;Giussago;PV;Lombardia;018072;27010 +E072;Godiasco Salice Terme;PV;Lombardia;018073; +E081;Golferenzo;PV;Lombardia;018074;27047 +E152;Gravellona Lomellina;PV;Lombardia;018075;27020 +E195;Gropello Cairoli;PV;Lombardia;018076;27027 +E310;Inverno e Monteleone;PV;Lombardia;018077;27010 +E437;Landriano;PV;Lombardia;018078;27015 +E439;Langosco;PV;Lombardia;018079;27030 +E454;Lardirago;PV;Lombardia;018080;27016 +E600;Linarolo;PV;Lombardia;018081;27010 +E662;Lomello;PV;Lombardia;018083;27034 +B387;Lungavilla;PV;Lombardia;018084;27053 +E804;Magherno;PV;Lombardia;018085;27010 +E934;Marcignago;PV;Lombardia;018086;27020 +E999;Marzano;PV;Lombardia;018087;27010 +F080;Mede;PV;Lombardia;018088;27035 +F122;Menconico;PV;Lombardia;018089;27050 +F170;Mezzana Bigli;PV;Lombardia;018090;27030 +F171;Mezzana Rabattone;PV;Lombardia;018091;27030 +F175;Mezzanino;PV;Lombardia;018092;27040 +F238;Miradolo Terme;PV;Lombardia;018093;27010 +F417;Montalto Pavese;PV;Lombardia;018094;27040 +F440;Montebello della Battaglia;PV;Lombardia;018095;27054 +F449;Montecalvo Versiggia;PV;Lombardia;018096;27047 +F638;Montescano;PV;Lombardia;018097;27040 +F644;Montesegale;PV;Lombardia;018098;27052 +F670;Monticelli Pavese;PV;Lombardia;018099;27010 +F701;Montù Beccaria;PV;Lombardia;018100;27040 +F739;Mornico Losana;PV;Lombardia;018101;27040 +F754;Mortara;PV;Lombardia;018102;27036 +F891;Nicorvo;PV;Lombardia;018103;27020 +G021;Olevano di Lomellina;PV;Lombardia;018104;27020 +G032;Oliva Gessi;PV;Lombardia;018105;27050 +G194;Ottobiano;PV;Lombardia;018106;27030 +G275;Palestro;PV;Lombardia;018107;27030 +G304;Pancarana;PV;Lombardia;018108;27050 +G342;Parona;PV;Lombardia;018109;27020 +G388;Pavia;PV;Lombardia;018110;27100 +G612;Pietra de' Giorgi;PV;Lombardia;018111;27040 +G635;Pieve Albignola;PV;Lombardia;018112;27030 +G639;Pieve del Cairo;PV;Lombardia;018113;27037 +G650;Pieve Porto Morone;PV;Lombardia;018114;27017 +G671;Pinarolo Po;PV;Lombardia;018115;27040 +G720;Pizzale;PV;Lombardia;018116;27050 +G851;Ponte Nizza;PV;Lombardia;018117;27050 +G895;Portalbera;PV;Lombardia;018118;27040 +H204;Rea;PV;Lombardia;018119;27040 +H216;Redavalle;PV;Lombardia;018120;27050 +H246;Retorbido;PV;Lombardia;018121;27050 +H336;Rivanazzano Terme;PV;Lombardia;018122; +H369;Robbio;PV;Lombardia;018123;27038 +H375;Robecco Pavese;PV;Lombardia;018124;27042 +H396;Rocca de' Giorgi;PV;Lombardia;018125;27040 +H450;Rocca Susella;PV;Lombardia;018126;27052 +H491;Rognano;PV;Lombardia;018127;27010 +H505;Romagnese;PV;Lombardia;018128;27050 +H527;Roncaro;PV;Lombardia;018129;27010 +H559;Rosasco;PV;Lombardia;018130;27030 +H614;Rovescala;PV;Lombardia;018131;27040 +H799;San Cipriano Po;PV;Lombardia;018133;27043 +H814;San Damiano al Colle;PV;Lombardia;018134;27040 +H859;San Genesio ed Uniti;PV;Lombardia;018135;27010 +H885;San Giorgio di Lomellina;PV;Lombardia;018136;27020 +I014;San Martino Siccomario;PV;Lombardia;018137;27028 +I048;Sannazzaro de' Burgondi;PV;Lombardia;018138;27039 +I175;Santa Cristina e Bissone;PV;Lombardia;018139;27010 +I203;Santa Giuletta;PV;Lombardia;018140;27046 +I213;Sant'Alessio con Vialone;PV;Lombardia;018141;27016 +I230;Santa Margherita di Staffora;PV;Lombardia;018142;27050 +I237;Santa Maria della Versa;PV;Lombardia;018143;27047 +I276;Sant'Angelo Lomellina;PV;Lombardia;018144;27030 +I416;San Zenone al Po;PV;Lombardia;018145;27010 +I447;Sartirana Lomellina;PV;Lombardia;018146;27020 +I487;Scaldasole;PV;Lombardia;018147;27020 +I599;Semiana;PV;Lombardia;018148;27020 +I739;Silvano Pietra;PV;Lombardia;018149;27050 +E265;Siziano;PV;Lombardia;018150;27010 +I825;Sommo;PV;Lombardia;018151;27048 +I894;Spessa;PV;Lombardia;018152;27010 +I968;Stradella;PV;Lombardia;018153;27049 +B014;Suardi;PV;Lombardia;018154;27030 +L237;Torrazza Coste;PV;Lombardia;018155;27050 +L250;Torre Beretti e Castellaro;PV;Lombardia;018156;27030 +L256;Torre d'Arese;PV;Lombardia;018157;27010 +L262;Torre de' Negri;PV;Lombardia;018158;27011 +L269;Torre d'Isola;PV;Lombardia;018159;27020 +L285;Torrevecchia Pia;PV;Lombardia;018160;27010 +L292;Torricella Verzate;PV;Lombardia;018161;27050 +I236;Travacò Siccomario;PV;Lombardia;018162;27020 +L440;Trivolzio;PV;Lombardia;018163;27020 +L449;Tromello;PV;Lombardia;018164;27020 +L453;Trovo;PV;Lombardia;018165;27020 +L562;Val di Nizza;PV;Lombardia;018166;27050 +L568;Valeggio;PV;Lombardia;018167;27020 +L593;Valle Lomellina;PV;Lombardia;018168;27020 +L617;Valle Salimbene;PV;Lombardia;018169;27010 +L690;Varzi;PV;Lombardia;018171;27057 +L716;Velezzo Lomellina;PV;Lombardia;018172;27020 +L720;Vellezzo Bellini;PV;Lombardia;018173;27010 +L784;Verretto;PV;Lombardia;018174;27053 +L788;Verrua Po;PV;Lombardia;018175;27040 +L854;Vidigulfo;PV;Lombardia;018176;27018 +L872;Vigevano;PV;Lombardia;018177;27029 +L917;Villa Biscossi;PV;Lombardia;018178;27035 +L983;Villanova d'Ardenghi;PV;Lombardia;018179;27030 +L994;Villanterio;PV;Lombardia;018180;27019 +M079;Vistarino;PV;Lombardia;018181;27010 +M109;Voghera;PV;Lombardia;018182;27058 +M119;Volpara;PV;Lombardia;018183;27047 +M150;Zavattarello;PV;Lombardia;018184;27059 +M152;Zeccone;PV;Lombardia;018185;27010 +M161;Zeme;PV;Lombardia;018186;27030 +M162;Zenevredo;PV;Lombardia;018187;27049 +M166;Zerbo;PV;Lombardia;018188;27017 +M167;Zerbolò;PV;Lombardia;018189;27020 +M180;Zinasco;PV;Lombardia;018190;27030 +M338;Cornale e Bastida;PV;Lombardia;018191;27056 +M372;Corteolona e Genzone;PV;Lombardia;018192; +M419;Colli Verdi;PV;Lombardia;018193; +A039;Acquanegra Cremonese;CR;Lombardia;019001;26020 +A076;Agnadello;CR;Lombardia;019002;26020 +A299;Annicco;CR;Lombardia;019003;26021 +A526;Azzanello;CR;Lombardia;019004;26010 +A570;Bagnolo Cremasco;CR;Lombardia;019005;26010 +A972;Bonemerse;CR;Lombardia;019006;26040 +A986;Bordolano;CR;Lombardia;019007;26020 +B439;Calvatone;CR;Lombardia;019009;26030 +B484;Camisano;CR;Lombardia;019010;26010 +B498;Campagnola Cremasca;CR;Lombardia;019011;26010 +B650;Capergnanica;CR;Lombardia;019012;26010 +B679;Cappella Cantone;CR;Lombardia;019013;26020 +B680;Cappella de' Picenardi;CR;Lombardia;019014;26030 +B686;Capralba;CR;Lombardia;019015;26010 +B869;Casalbuttano ed Uniti;CR;Lombardia;019016;26011 +B881;Casale Cremasco-Vidolasco;CR;Lombardia;019017;26010 +B889;Casaletto Ceredano;CR;Lombardia;019018;26010 +B890;Casaletto di Sopra;CR;Lombardia;019019;26014 +B891;Casaletto Vaprio;CR;Lombardia;019020;26010 +B898;Casalmaggiore;CR;Lombardia;019021;26041 +B900;Casalmorano;CR;Lombardia;019022;26020 +C089;Casteldidone;CR;Lombardia;019023;26030 +C115;Castel Gabbiano;CR;Lombardia;019024;26010 +C153;Castelleone;CR;Lombardia;019025;26012 +B129;Castelverde;CR;Lombardia;019026;26022 +C290;Castelvisconti;CR;Lombardia;019027;26010 +C435;Cella Dati;CR;Lombardia;019028;26040 +C634;Chieve;CR;Lombardia;019029;26010 +C678;Cicognolo;CR;Lombardia;019030;26030 +C703;Cingia de' Botti;CR;Lombardia;019031;26042 +D056;Corte de' Cortesi con Cignone;CR;Lombardia;019032;26020 +D057;Corte de' Frati;CR;Lombardia;019033;26010 +D141;Credera Rubbiano;CR;Lombardia;019034;26010 +D142;Crema;CR;Lombardia;019035;26013 +D150;Cremona;CR;Lombardia;019036;26100 +D151;Cremosano;CR;Lombardia;019037;26010 +D186;Crotta d'Adda;CR;Lombardia;019038;26020 +D203;Cumignano sul Naviglio;CR;Lombardia;019039;26020 +D278;Derovere;CR;Lombardia;019040;26040 +D358;Dovera;CR;Lombardia;019041;26010 +D574;Fiesco;CR;Lombardia;019043;26010 +D710;Formigara;CR;Lombardia;019044;26020 +D834;Gabbioneta-Binanuova;CR;Lombardia;019045;26030 +D841;Gadesco-Pieve Delmona;CR;Lombardia;019046;26030 +D966;Genivolta;CR;Lombardia;019047;26020 +D993;Gerre de' Caprioli;CR;Lombardia;019048;26040 +E082;Gombito;CR;Lombardia;019049;26020 +E193;Grontardo;CR;Lombardia;019050;26044 +E217;Grumello Cremonese ed Uniti;CR;Lombardia;019051;26023 +E272;Gussola;CR;Lombardia;019052;26040 +E356;Isola Dovarese;CR;Lombardia;019053;26031 +E380;Izano;CR;Lombardia;019054;26010 +E793;Madignano;CR;Lombardia;019055;26020 +E843;Malagnino;CR;Lombardia;019056;26030 +E983;Martignana di Po;CR;Lombardia;019057;26040 +F434;Monte Cremasco;CR;Lombardia;019058;26010 +F681;Montodine;CR;Lombardia;019059;26010 +F761;Moscazzano;CR;Lombardia;019060;26010 +F771;Motta Baluffi;CR;Lombardia;019061;26045 +G004;Offanengo;CR;Lombardia;019062;26010 +G047;Olmeneta;CR;Lombardia;019063;26010 +G185;Ostiano;CR;Lombardia;019064;26032 +G222;Paderno Ponchielli;CR;Lombardia;019065;26024 +G260;Palazzo Pignano;CR;Lombardia;019066;26020 +G306;Pandino;CR;Lombardia;019067;26025 +G469;Persico Dosimo;CR;Lombardia;019068;26043 +G483;Pescarolo ed Uniti;CR;Lombardia;019069;26033 +G504;Pessina Cremonese;CR;Lombardia;019070;26030 +G558;Pianengo;CR;Lombardia;019072;26010 +G603;Pieranica;CR;Lombardia;019073;26017 +G647;Pieve d'Olmi;CR;Lombardia;019074;26040 +G651;Pieve San Giacomo;CR;Lombardia;019075;26035 +G721;Pizzighettone;CR;Lombardia;019076;26026 +B914;Pozzaglio ed Uniti;CR;Lombardia;019077;26010 +H130;Quintano;CR;Lombardia;019078;26017 +H276;Ricengo;CR;Lombardia;019079;26010 +H314;Ripalta Arpina;CR;Lombardia;019080;26010 +H315;Ripalta Cremasca;CR;Lombardia;019081;26010 +H316;Ripalta Guerina;CR;Lombardia;019082;26010 +H341;Rivarolo del Re ed Uniti;CR;Lombardia;019083;26036 +H357;Rivolta d'Adda;CR;Lombardia;019084;26027 +H372;Robecco d'Oglio;CR;Lombardia;019085;26010 +H508;Romanengo;CR;Lombardia;019086;26014 +H731;Salvirola;CR;Lombardia;019087;26010 +H767;San Bassano;CR;Lombardia;019088;26020 +H815;San Daniele Po;CR;Lombardia;019089;26046 +H918;San Giovanni in Croce;CR;Lombardia;019090;26037 +I007;San Martino del Lago;CR;Lombardia;019091;26040 +I497;Scandolara Ravara;CR;Lombardia;019092;26040 +I498;Scandolara Ripa d'Oglio;CR;Lombardia;019093;26047 +I627;Sergnano;CR;Lombardia;019094;26010 +I683;Sesto ed Uniti;CR;Lombardia;019095;26028 +I790;Solarolo Rainerio;CR;Lombardia;019096;26030 +I827;Soncino;CR;Lombardia;019097;26029 +I849;Soresina;CR;Lombardia;019098;26015 +I865;Sospiro;CR;Lombardia;019099;26048 +I906;Spinadesco;CR;Lombardia;019100;26020 +I909;Spineda;CR;Lombardia;019101;26030 +I914;Spino d'Adda;CR;Lombardia;019102;26016 +I935;Stagno Lombardo;CR;Lombardia;019103;26049 +L164;Ticengo;CR;Lombardia;019104;26020 +L221;Torlino Vimercati;CR;Lombardia;019105;26017 +L225;Tornata;CR;Lombardia;019106;26030 +L258;Torre de' Picenardi;CR;Lombardia;019107;26038 +L296;Torricella del Pizzo;CR;Lombardia;019108;26040 +L389;Trescore Cremasco;CR;Lombardia;019109;26017 +L426;Trigolo;CR;Lombardia;019110;26018 +L535;Vaiano Cremasco;CR;Lombardia;019111;26010 +L539;Vailate;CR;Lombardia;019112;26019 +L806;Vescovato;CR;Lombardia;019113;26039 +M116;Volongo;CR;Lombardia;019114;26030 +M127;Voltido;CR;Lombardia;019115;26030 +M418;Piadena Drizzona;CR;Lombardia;019116; +A038;Acquanegra sul Chiese;MN;Lombardia;020001;46011 +A470;Asola;MN;Lombardia;020002;46041 +A575;Bagnolo San Vito;MN;Lombardia;020003;46031 +B110;Bozzolo;MN;Lombardia;020007;46012 +B612;Canneto sull'Oglio;MN;Lombardia;020008;46013 +B901;Casalmoro;MN;Lombardia;020010;46040 +B907;Casaloldo;MN;Lombardia;020011;46040 +B911;Casalromano;MN;Lombardia;020012;46040 +C059;Castelbelforte;MN;Lombardia;020013;46032 +C076;Castel d'Ario;MN;Lombardia;020014;46033 +C118;Castel Goffredo;MN;Lombardia;020015;46042 +C195;Castellucchio;MN;Lombardia;020016;46014 +C312;Castiglione delle Stiviere;MN;Lombardia;020017;46043 +C406;Cavriana;MN;Lombardia;020018;46040 +C502;Ceresara;MN;Lombardia;020019;46040 +C930;Commessaggio;MN;Lombardia;020020;46010 +D227;Curtatone;MN;Lombardia;020021;46010 +D351;Dosolo;MN;Lombardia;020022;46030 +D949;Gazoldo degli Ippoliti;MN;Lombardia;020024;46040 +D959;Gazzuolo;MN;Lombardia;020025;46010 +E078;Goito;MN;Lombardia;020026;46044 +E089;Gonzaga;MN;Lombardia;020027;46023 +E261;Guidizzolo;MN;Lombardia;020028;46040 +E818;Magnacavallo;MN;Lombardia;020029;46020 +E897;Mantova;MN;Lombardia;020030;46100 +E922;Marcaria;MN;Lombardia;020031;46010 +E949;Mariana Mantovana;MN;Lombardia;020032;46010 +E962;Marmirolo;MN;Lombardia;020033;46045 +F086;Medole;MN;Lombardia;020034;46046 +F267;Moglia;MN;Lombardia;020035;46024 +F705;Monzambano;MN;Lombardia;020036;46040 +B012;Motteggiana;MN;Lombardia;020037;46020 +G186;Ostiglia;MN;Lombardia;020038;46035 +G417;Pegognaga;MN;Lombardia;020039;46020 +G717;Piubega;MN;Lombardia;020041;46040 +G753;Poggio Rusco;MN;Lombardia;020042;46025 +G816;Pomponesco;MN;Lombardia;020043;46030 +G862;Ponti sul Mincio;MN;Lombardia;020044;46040 +G917;Porto Mantovano;MN;Lombardia;020045;46047 +H129;Quingentole;MN;Lombardia;020046;46020 +H143;Quistello;MN;Lombardia;020047;46026 +H218;Redondesco;MN;Lombardia;020048;46010 +H342;Rivarolo Mantovano;MN;Lombardia;020050;46017 +H481;Rodigo;MN;Lombardia;020051;46040 +H541;Roncoferraro;MN;Lombardia;020052;46037 +H604;Roverbella;MN;Lombardia;020053;46048 +H652;Sabbioneta;MN;Lombardia;020054;46018 +H771;San Benedetto Po;MN;Lombardia;020055;46027 +H870;San Giacomo delle Segnate;MN;Lombardia;020056;46020 +H883;San Giorgio Bigarello;MN;Lombardia;020057; +H912;San Giovanni del Dosso;MN;Lombardia;020058;46020 +I005;San Martino dall'Argine;MN;Lombardia;020059;46010 +I532;Schivenoglia;MN;Lombardia;020060;46020 +I632;Sermide e Felonica;MN;Lombardia;020061; +I662;Serravalle a Po;MN;Lombardia;020062;46030 +I801;Solferino;MN;Lombardia;020063;46040 +L015;Sustinente;MN;Lombardia;020064;46030 +L020;Suzzara;MN;Lombardia;020065;46029 +L826;Viadana;MN;Lombardia;020066;46019 +M044;Villimpenta;MN;Lombardia;020068;46039 +M125;Volta Mantovana;MN;Lombardia;020070;46049 +M340;Borgo Virgilio;MN;Lombardia;020071;46034 +M396;Borgo Mantovano;MN;Lombardia;020072; +M406;Borgocarbonara;MN;Lombardia;020073; +A179;Aldino;BZ;Trentino-Alto Adige/Südtirol;021001;39040 +A286;Andriano;BZ;Trentino-Alto Adige/Südtirol;021002;39010 +A306;Anterivo;BZ;Trentino-Alto Adige/Südtirol;021003;39040 +A332;Appiano sulla strada del vino;BZ;Trentino-Alto Adige/Südtirol;021004;39057 +A507;Avelengo;BZ;Trentino-Alto Adige/Südtirol;021005;39010 +A537;Badia;BZ;Trentino-Alto Adige/Südtirol;021006;39036 +A635;Barbiano;BZ;Trentino-Alto Adige/Südtirol;021007;39040 +A952;Bolzano;BZ;Trentino-Alto Adige/Südtirol;021008;39100 +B116;Braies;BZ;Trentino-Alto Adige/Südtirol;021009;39030 +B145;Brennero;BZ;Trentino-Alto Adige/Südtirol;021010;39041 +B160;Bressanone;BZ;Trentino-Alto Adige/Südtirol;021011;39042 +B203;Bronzolo;BZ;Trentino-Alto Adige/Südtirol;021012;39051 +B220;Brunico;BZ;Trentino-Alto Adige/Südtirol;021013;39031 +B364;Caines;BZ;Trentino-Alto Adige/Südtirol;021014;39010 +B397;Caldaro sulla strada del vino;BZ;Trentino-Alto Adige/Südtirol;021015;39052 +B529;Campo di Trens;BZ;Trentino-Alto Adige/Südtirol;021016;39040 +B570;Campo Tures;BZ;Trentino-Alto Adige/Südtirol;021017;39032 +C062;Castelbello-Ciardes;BZ;Trentino-Alto Adige/Südtirol;021018;39020 +C254;Castelrotto;BZ;Trentino-Alto Adige/Südtirol;021019;39040 +A022;Cermes;BZ;Trentino-Alto Adige/Südtirol;021020;39010 +C625;Chienes;BZ;Trentino-Alto Adige/Südtirol;021021;39030 +C652;Chiusa;BZ;Trentino-Alto Adige/Südtirol;021022;39043 +B799;Cornedo all'Isarco;BZ;Trentino-Alto Adige/Südtirol;021023;39053 +D048;Cortaccia sulla strada del vino;BZ;Trentino-Alto Adige/Südtirol;021024;39040 +D075;Cortina sulla strada del vino;BZ;Trentino-Alto Adige/Südtirol;021025;39040 +D079;Corvara in Badia;BZ;Trentino-Alto Adige/Südtirol;021026;39033 +D222;Curon Venosta;BZ;Trentino-Alto Adige/Südtirol;021027;39027 +D311;Dobbiaco;BZ;Trentino-Alto Adige/Südtirol;021028;39034 +D392;Egna;BZ;Trentino-Alto Adige/Südtirol;021029;39044 +D484;Falzes;BZ;Trentino-Alto Adige/Südtirol;021030;39030 +D571;Fiè allo Sciliar;BZ;Trentino-Alto Adige/Südtirol;021031;39050 +D731;Fortezza;BZ;Trentino-Alto Adige/Südtirol;021032;39045 +D821;Funes;BZ;Trentino-Alto Adige/Südtirol;021033;39040 +D860;Gais;BZ;Trentino-Alto Adige/Südtirol;021034;39030 +D923;Gargazzone;BZ;Trentino-Alto Adige/Südtirol;021035;39010 +E069;Glorenza;BZ;Trentino-Alto Adige/Südtirol;021036;39020 +E398;Laces;BZ;Trentino-Alto Adige/Südtirol;021037;39021 +E412;Lagundo;BZ;Trentino-Alto Adige/Südtirol;021038;39022 +E420;Laion;BZ;Trentino-Alto Adige/Südtirol;021039;39040 +E421;Laives;BZ;Trentino-Alto Adige/Südtirol;021040;39055 +E434;Lana;BZ;Trentino-Alto Adige/Südtirol;021041;39011 +E457;Lasa;BZ;Trentino-Alto Adige/Südtirol;021042;39023 +E481;Lauregno;BZ;Trentino-Alto Adige/Südtirol;021043;39040 +E764;Luson;BZ;Trentino-Alto Adige/Südtirol;021044;39040 +E829;Magrè sulla strada del vino;BZ;Trentino-Alto Adige/Südtirol;021045;39040 +E862;Malles Venosta;BZ;Trentino-Alto Adige/Südtirol;021046;39024 +E938;Marebbe;BZ;Trentino-Alto Adige/Südtirol;021047;39030 +E959;Marlengo;BZ;Trentino-Alto Adige/Südtirol;021048;39020 +E981;Martello;BZ;Trentino-Alto Adige/Südtirol;021049;39020 +F118;Meltina;BZ;Trentino-Alto Adige/Südtirol;021050;39010 +F132;Merano;BZ;Trentino-Alto Adige/Südtirol;021051;39012 +F371;Monguelfo-Tesido;BZ;Trentino-Alto Adige/Südtirol;021052; +F392;Montagna sulla strada del vino;BZ;Trentino-Alto Adige/Südtirol;021053; +F766;Moso in Passiria;BZ;Trentino-Alto Adige/Südtirol;021054;39013 +F836;Nalles;BZ;Trentino-Alto Adige/Südtirol;021055;39010 +F849;Naturno;BZ;Trentino-Alto Adige/Südtirol;021056;39025 +F856;Naz-Sciaves;BZ;Trentino-Alto Adige/Südtirol;021057;39040 +F949;Nova Levante;BZ;Trentino-Alto Adige/Südtirol;021058;39056 +F950;Nova Ponente;BZ;Trentino-Alto Adige/Südtirol;021059;39050 +G083;Ora;BZ;Trentino-Alto Adige/Südtirol;021060;39040 +G140;Ortisei;BZ;Trentino-Alto Adige/Südtirol;021061;39046 +G328;Parcines;BZ;Trentino-Alto Adige/Südtirol;021062;39020 +G443;Perca;BZ;Trentino-Alto Adige/Südtirol;021063;39030 +G299;Plaus;BZ;Trentino-Alto Adige/Südtirol;021064;39025 +G830;Ponte Gardena;BZ;Trentino-Alto Adige/Südtirol;021065;39040 +G936;Postal;BZ;Trentino-Alto Adige/Südtirol;021066;39014 +H004;Prato allo Stelvio;BZ;Trentino-Alto Adige/Südtirol;021067;39026 +H019;Predoi;BZ;Trentino-Alto Adige/Südtirol;021068;39030 +H081;Proves;BZ;Trentino-Alto Adige/Südtirol;021069;39040 +H152;Racines;BZ;Trentino-Alto Adige/Südtirol;021070;39040 +H189;Rasun-Anterselva;BZ;Trentino-Alto Adige/Südtirol;021071;39030 +H236;Renon;BZ;Trentino-Alto Adige/Südtirol;021072;39054 +H284;Rifiano;BZ;Trentino-Alto Adige/Südtirol;021073;39010 +H299;Rio di Pusteria;BZ;Trentino-Alto Adige/Südtirol;021074;39037 +H475;Rodengo;BZ;Trentino-Alto Adige/Südtirol;021075;39037 +H719;Salorno sulla strada del vino;BZ;Trentino-Alto Adige/Südtirol;021076; +H786;San Candido;BZ;Trentino-Alto Adige/Südtirol;021077;39038 +H858;San Genesio Atesino;BZ;Trentino-Alto Adige/Südtirol;021079;39050 +H952;San Leonardo in Passiria;BZ;Trentino-Alto Adige/Südtirol;021080;39015 +H956;San Lorenzo di Sebato;BZ;Trentino-Alto Adige/Südtirol;021081;39030 +H988;San Martino in Badia;BZ;Trentino-Alto Adige/Südtirol;021082;39030 +H989;San Martino in Passiria;BZ;Trentino-Alto Adige/Südtirol;021083;39010 +I065;San Pancrazio;BZ;Trentino-Alto Adige/Südtirol;021084;39010 +I173;Santa Cristina Valgardena;BZ;Trentino-Alto Adige/Südtirol;021085; +I431;Sarentino;BZ;Trentino-Alto Adige/Südtirol;021086;39058 +I519;Scena;BZ;Trentino-Alto Adige/Südtirol;021087;39017 +I593;Selva dei Molini;BZ;Trentino-Alto Adige/Südtirol;021088;39030 +I591;Selva di Val Gardena;BZ;Trentino-Alto Adige/Südtirol;021089;39048 +I604;Senales;BZ;Trentino-Alto Adige/Südtirol;021091;39020 +I687;Sesto;BZ;Trentino-Alto Adige/Südtirol;021092;39030 +I729;Silandro;BZ;Trentino-Alto Adige/Südtirol;021093;39028 +I771;Sluderno;BZ;Trentino-Alto Adige/Südtirol;021094;39020 +I948;Stelvio;BZ;Trentino-Alto Adige/Südtirol;021095;39029 +L106;Terento;BZ;Trentino-Alto Adige/Südtirol;021096;39030 +L108;Terlano;BZ;Trentino-Alto Adige/Südtirol;021097;39018 +L111;Termeno sulla strada del vino;BZ;Trentino-Alto Adige/Südtirol;021098;39040 +L149;Tesimo;BZ;Trentino-Alto Adige/Südtirol;021099;39010 +L176;Tires;BZ;Trentino-Alto Adige/Südtirol;021100;39050 +L178;Tirolo;BZ;Trentino-Alto Adige/Südtirol;021101;39019 +L444;Trodena nel parco naturale;BZ;Trentino-Alto Adige/Südtirol;021102; +L455;Tubre;BZ;Trentino-Alto Adige/Südtirol;021103;39020 +L490;Ultimo;BZ;Trentino-Alto Adige/Südtirol;021104;39016 +L527;Vadena;BZ;Trentino-Alto Adige/Südtirol;021105;39051 +L552;Valdaora;BZ;Trentino-Alto Adige/Südtirol;021106;39030 +L564;Val di Vizze;BZ;Trentino-Alto Adige/Südtirol;021107;39049 +L595;Valle Aurina;BZ;Trentino-Alto Adige/Südtirol;021108;39030 +L601;Valle di Casies;BZ;Trentino-Alto Adige/Südtirol;021109;39030 +L660;Vandoies;BZ;Trentino-Alto Adige/Südtirol;021110;39030 +L687;Varna;BZ;Trentino-Alto Adige/Südtirol;021111;39040 +L745;Verano;BZ;Trentino-Alto Adige/Südtirol;021112;39010 +L915;Villabassa;BZ;Trentino-Alto Adige/Südtirol;021113;39039 +L971;Villandro;BZ;Trentino-Alto Adige/Südtirol;021114;39040 +M067;Vipiteno;BZ;Trentino-Alto Adige/Südtirol;021115;39049 +L724;Velturno;BZ;Trentino-Alto Adige/Südtirol;021116;39040 +E491;La Valle;BZ;Trentino-Alto Adige/Südtirol;021117;39030 +I603;Senale-San Felice;BZ;Trentino-Alto Adige/Südtirol;021118;39010 +A116;Ala;TN;Trentino-Alto Adige/Südtirol;022001;38061 +A158;Albiano;TN;Trentino-Alto Adige/Südtirol;022002;38041 +A178;Aldeno;TN;Trentino-Alto Adige/Südtirol;022003;38060 +A274;Andalo;TN;Trentino-Alto Adige/Südtirol;022005;38010 +A372;Arco;TN;Trentino-Alto Adige/Südtirol;022006;38062 +A520;Avio;TN;Trentino-Alto Adige/Südtirol;022007;38063 +A694;Baselga di Pinè;TN;Trentino-Alto Adige/Südtirol;022009;38042 +A730;Bedollo;TN;Trentino-Alto Adige/Südtirol;022011;38043 +A821;Besenello;TN;Trentino-Alto Adige/Südtirol;022013;38060 +A863;Bieno;TN;Trentino-Alto Adige/Südtirol;022015;38050 +A902;Bleggio Superiore;TN;Trentino-Alto Adige/Südtirol;022017;38071 +A916;Bocenago;TN;Trentino-Alto Adige/Südtirol;022018;38080 +A968;Bondone;TN;Trentino-Alto Adige/Südtirol;022021;38080 +B006;Borgo Valsugana;TN;Trentino-Alto Adige/Südtirol;022022;38051 +B153;Brentonico;TN;Trentino-Alto Adige/Südtirol;022025;38060 +B158;Bresimo;TN;Trentino-Alto Adige/Südtirol;022026;38020 +B335;Caderzone Terme;TN;Trentino-Alto Adige/Südtirol;022029; +B389;Calceranica al Lago;TN;Trentino-Alto Adige/Südtirol;022032;38050 +B400;Caldes;TN;Trentino-Alto Adige/Südtirol;022033;38022 +B404;Caldonazzo;TN;Trentino-Alto Adige/Südtirol;022034;38052 +B419;Calliano;TN;Trentino-Alto Adige/Südtirol;022035; +B514;Campitello di Fassa;TN;Trentino-Alto Adige/Südtirol;022036;38031 +B525;Campodenno;TN;Trentino-Alto Adige/Südtirol;022037;38010 +B577;Canal San Bovo;TN;Trentino-Alto Adige/Südtirol;022038;38050 +B579;Canazei;TN;Trentino-Alto Adige/Südtirol;022039;38032 +B697;Capriana;TN;Trentino-Alto Adige/Südtirol;022040;38030 +B783;Carisolo;TN;Trentino-Alto Adige/Südtirol;022042;38080 +B856;Carzano;TN;Trentino-Alto Adige/Südtirol;022043;38050 +C183;Castel Condino;TN;Trentino-Alto Adige/Südtirol;022045;38082 +C189;Castello-Molina di Fiemme;TN;Trentino-Alto Adige/Südtirol;022047;38030 +C194;Castello Tesino;TN;Trentino-Alto Adige/Südtirol;022048;38053 +C216;Castelnuovo;TN;Trentino-Alto Adige/Südtirol;022049;38050 +C372;Cavalese;TN;Trentino-Alto Adige/Südtirol;022050;38033 +C380;Cavareno;TN;Trentino-Alto Adige/Südtirol;022051;38011 +C392;Cavedago;TN;Trentino-Alto Adige/Südtirol;022052;38010 +C393;Cavedine;TN;Trentino-Alto Adige/Südtirol;022053;38073 +C400;Cavizzana;TN;Trentino-Alto Adige/Südtirol;022054;38022 +C700;Cimone;TN;Trentino-Alto Adige/Südtirol;022058;38060 +C712;Cinte Tesino;TN;Trentino-Alto Adige/Südtirol;022059;38050 +C727;Cis;TN;Trentino-Alto Adige/Südtirol;022060;38020 +C756;Civezzano;TN;Trentino-Alto Adige/Südtirol;022061;38045 +C794;Cles;TN;Trentino-Alto Adige/Südtirol;022062;38023 +C931;Commezzadura;TN;Trentino-Alto Adige/Südtirol;022064;38020 +D188;Croviana;TN;Trentino-Alto Adige/Südtirol;022068;38027 +D246;Dambel;TN;Trentino-Alto Adige/Südtirol;022071;38010 +D273;Denno;TN;Trentino-Alto Adige/Südtirol;022074;38010 +D365;Drena;TN;Trentino-Alto Adige/Südtirol;022078;38074 +D371;Dro;TN;Trentino-Alto Adige/Südtirol;022079;38074 +D468;Fai della Paganella;TN;Trentino-Alto Adige/Südtirol;022081;38010 +D565;Fiavè;TN;Trentino-Alto Adige/Südtirol;022083;38075 +D573;Fierozzo;TN;Trentino-Alto Adige/Südtirol;022085;38050 +D651;Folgaria;TN;Trentino-Alto Adige/Südtirol;022087;38064 +D714;Fornace;TN;Trentino-Alto Adige/Südtirol;022089;38040 +D775;Frassilongo;TN;Trentino-Alto Adige/Südtirol;022090;38050 +D928;Garniga Terme;TN;Trentino-Alto Adige/Südtirol;022091;38060 +E048;Giovo;TN;Trentino-Alto Adige/Südtirol;022092;38030 +E065;Giustino;TN;Trentino-Alto Adige/Südtirol;022093;38086 +E178;Grigno;TN;Trentino-Alto Adige/Südtirol;022095;38055 +E288;Imer;TN;Trentino-Alto Adige/Südtirol;022097;38050 +E334;Isera;TN;Trentino-Alto Adige/Südtirol;022098;38060 +E492;Lavarone;TN;Trentino-Alto Adige/Südtirol;022102;38046 +E500;Lavis;TN;Trentino-Alto Adige/Südtirol;022103;38015 +E565;Levico Terme;TN;Trentino-Alto Adige/Südtirol;022104;38056 +E624;Livo;TN;Trentino-Alto Adige/Südtirol;022106; +E664;Lona-Lases;TN;Trentino-Alto Adige/Südtirol;022108;38040 +E757;Luserna;TN;Trentino-Alto Adige/Südtirol;022109;38040 +E850;Malé;TN;Trentino-Alto Adige/Südtirol;022110;38027 +F045;Massimeno;TN;Trentino-Alto Adige/Südtirol;022112;38086 +F068;Mazzin;TN;Trentino-Alto Adige/Südtirol;022113;38030 +F168;Mezzana;TN;Trentino-Alto Adige/Südtirol;022114;38020 +F176;Mezzano;TN;Trentino-Alto Adige/Südtirol;022115;38050 +F183;Mezzocorona;TN;Trentino-Alto Adige/Südtirol;022116;38016 +F187;Mezzolombardo;TN;Trentino-Alto Adige/Südtirol;022117;38017 +F263;Moena;TN;Trentino-Alto Adige/Südtirol;022118;38035 +F307;Molveno;TN;Trentino-Alto Adige/Südtirol;022120;38018 +F728;Mori;TN;Trentino-Alto Adige/Südtirol;022123;38065 +F835;Nago-Torbole;TN;Trentino-Alto Adige/Südtirol;022124;38069 +F920;Nogaredo;TN;Trentino-Alto Adige/Südtirol;022127;38060 +F929;Nomi;TN;Trentino-Alto Adige/Südtirol;022128;38060 +F947;Novaledo;TN;Trentino-Alto Adige/Südtirol;022129;38050 +G168;Ospedaletto;TN;Trentino-Alto Adige/Südtirol;022130;38050 +G173;Ossana;TN;Trentino-Alto Adige/Südtirol;022131;38026 +G296;Palù del Fersina;TN;Trentino-Alto Adige/Südtirol;022133;38050 +G305;Panchià;TN;Trentino-Alto Adige/Südtirol;022134;38030 +M303;Ronzo-Chienis;TN;Trentino-Alto Adige/Südtirol;022135;38060 +G419;Peio;TN;Trentino-Alto Adige/Südtirol;022136;38024 +G428;Pellizzano;TN;Trentino-Alto Adige/Südtirol;022137;38020 +G429;Pelugo;TN;Trentino-Alto Adige/Südtirol;022138;38079 +G452;Pergine Valsugana;TN;Trentino-Alto Adige/Südtirol;022139;38057 +G656;Pieve Tesino;TN;Trentino-Alto Adige/Südtirol;022142;38050 +G681;Pinzolo;TN;Trentino-Alto Adige/Südtirol;022143;38086 +G808;Pomarolo;TN;Trentino-Alto Adige/Südtirol;022144;38060 +H018;Predazzo;TN;Trentino-Alto Adige/Südtirol;022147;38037 +H146;Rabbi;TN;Trentino-Alto Adige/Südtirol;022150;38020 +H330;Riva del Garda;TN;Trentino-Alto Adige/Südtirol;022153;38066 +H517;Romeno;TN;Trentino-Alto Adige/Südtirol;022155;38010 +H528;Roncegno Terme;TN;Trentino-Alto Adige/Südtirol;022156; +H532;Ronchi Valsugana;TN;Trentino-Alto Adige/Südtirol;022157;38050 +H552;Ronzone;TN;Trentino-Alto Adige/Südtirol;022159;38010 +H607;Roverè della Luna;TN;Trentino-Alto Adige/Südtirol;022160;38030 +H612;Rovereto;TN;Trentino-Alto Adige/Südtirol;022161;38068 +H634;Ruffrè-Mendola;TN;Trentino-Alto Adige/Südtirol;022162; +H639;Rumo;TN;Trentino-Alto Adige/Südtirol;022163;38020 +H666;Sagron Mis;TN;Trentino-Alto Adige/Südtirol;022164;38050 +H754;Samone;TN;Trentino-Alto Adige/Südtirol;022165;38059 +I042;San Michele all'Adige;TN;Trentino-Alto Adige/Südtirol;022167;38010 +I354;Sant'Orsola Terme;TN;Trentino-Alto Adige/Südtirol;022168;38050 +I411;Sanzeno;TN;Trentino-Alto Adige/Südtirol;022169;38010 +I439;Sarnonico;TN;Trentino-Alto Adige/Südtirol;022170;38011 +I554;Scurelle;TN;Trentino-Alto Adige/Südtirol;022171;38050 +I576;Segonzano;TN;Trentino-Alto Adige/Südtirol;022172;38047 +I714;Sfruz;TN;Trentino-Alto Adige/Südtirol;022173;38010 +I839;Soraga di Fassa;TN;Trentino-Alto Adige/Südtirol;022176; +I871;Sover;TN;Trentino-Alto Adige/Südtirol;022177;38048 +I899;Spiazzo;TN;Trentino-Alto Adige/Südtirol;022179;38088 +I924;Spormaggiore;TN;Trentino-Alto Adige/Südtirol;022180;38010 +I925;Sporminore;TN;Trentino-Alto Adige/Südtirol;022181;38010 +I949;Stenico;TN;Trentino-Alto Adige/Südtirol;022182;38070 +I964;Storo;TN;Trentino-Alto Adige/Südtirol;022183;38089 +I975;Strembo;TN;Trentino-Alto Adige/Südtirol;022184;38080 +L089;Telve;TN;Trentino-Alto Adige/Südtirol;022188;38050 +L090;Telve di Sopra;TN;Trentino-Alto Adige/Südtirol;022189;38050 +L096;Tenna;TN;Trentino-Alto Adige/Südtirol;022190;38050 +L097;Tenno;TN;Trentino-Alto Adige/Südtirol;022191;38060 +L121;Terragnolo;TN;Trentino-Alto Adige/Südtirol;022193;38060 +L145;Terzolas;TN;Trentino-Alto Adige/Südtirol;022195;38027 +L147;Tesero;TN;Trentino-Alto Adige/Südtirol;022196;38038 +L174;Tione di Trento;TN;Trentino-Alto Adige/Südtirol;022199;38079 +L200;Ton;TN;Trentino-Alto Adige/Südtirol;022200;38010 +L211;Torcegno;TN;Trentino-Alto Adige/Südtirol;022202;38050 +L322;Trambileno;TN;Trentino-Alto Adige/Südtirol;022203;38068 +L378;Trento;TN;Trentino-Alto Adige/Südtirol;022205;38100,38121-38123 +L575;Valfloriana;TN;Trentino-Alto Adige/Südtirol;022209;38040 +L588;Vallarsa;TN;Trentino-Alto Adige/Südtirol;022210;38060 +L769;Vermiglio;TN;Trentino-Alto Adige/Südtirol;022213;38029 +L886;Vignola-Falesina;TN;Trentino-Alto Adige/Südtirol;022216;38057 +L957;Villa Lagarina;TN;Trentino-Alto Adige/Südtirol;022222;38060 +M113;Volano;TN;Trentino-Alto Adige/Südtirol;022224;38060 +M173;Ziano di Fiemme;TN;Trentino-Alto Adige/Südtirol;022226;38030 +M314;Comano Terme;TN;Trentino-Alto Adige/Südtirol;022228;38077 +M313;Ledro;TN;Trentino-Alto Adige/Südtirol;022229;38067 +M344;Predaia;TN;Trentino-Alto Adige/Südtirol;022230;38012 +M345;San Lorenzo Dorsino;TN;Trentino-Alto Adige/Südtirol;022231;38078 +M343;Valdaone;TN;Trentino-Alto Adige/Südtirol;022232;38091 +M366;Dimaro Folgarida;TN;Trentino-Alto Adige/Südtirol;022233; +M365;Pieve di Bono-Prezzo;TN;Trentino-Alto Adige/Südtirol;022234; +M349;Altavalle;TN;Trentino-Alto Adige/Südtirol;022235; +M350;Altopiano della Vigolana;TN;Trentino-Alto Adige/Südtirol;022236; +M351;Amblar-Don;TN;Trentino-Alto Adige/Südtirol;022237; +M352;Borgo Chiese;TN;Trentino-Alto Adige/Südtirol;022238; +M353;Borgo Lares;TN;Trentino-Alto Adige/Südtirol;022239; +M354;Castel Ivano;TN;Trentino-Alto Adige/Südtirol;022240; +M355;Cembra Lisignago;TN;Trentino-Alto Adige/Südtirol;022241; +M356;Contà;TN;Trentino-Alto Adige/Südtirol;022242; +M357;Madruzzo;TN;Trentino-Alto Adige/Südtirol;022243;38076 +M358;Porte di Rendena;TN;Trentino-Alto Adige/Südtirol;022244; +M359;Primiero San Martino di Castrozza;TN;Trentino-Alto Adige/Südtirol;022245; +M360;Sella Giudicarie;TN;Trentino-Alto Adige/Südtirol;022246; +M361;Tre Ville;TN;Trentino-Alto Adige/Südtirol;022247; +M362;Vallelaghi;TN;Trentino-Alto Adige/Südtirol;022248; +M363;Ville d'Anaunia;TN;Trentino-Alto Adige/Südtirol;022249; +M390;San Giovanni di Fassa;TN;Trentino-Alto Adige/Südtirol;022250; +M407;Terre d'Adige;TN;Trentino-Alto Adige/Südtirol;022251; +M429;Borgo d'Anaunia;TN;Trentino-Alto Adige/Südtirol;022252; +M430;Novella;TN;Trentino-Alto Adige/Südtirol;022253; +M431;Ville di Fiemme;TN;Trentino-Alto Adige/Südtirol;022254; +A061;Affi;VR;Veneto;023001;37010 +A137;Albaredo d'Adige;VR;Veneto;023002;37041 +A292;Angiari;VR;Veneto;023003;37050 +A374;Arcole;VR;Veneto;023004;37040 +A540;Badia Calavena;VR;Veneto;023005;37030 +A650;Bardolino;VR;Veneto;023006;37011 +A737;Belfiore;VR;Veneto;023007;37050 +A837;Bevilacqua;VR;Veneto;023008;37040 +A964;Bonavigo;VR;Veneto;023009;37040 +B070;Boschi Sant'Anna;VR;Veneto;023010;37040 +B073;Bosco Chiesanuova;VR;Veneto;023011;37021 +B107;Bovolone;VR;Veneto;023012;37051 +B152;Brentino Belluno;VR;Veneto;023013;37020 +B154;Brenzone sul Garda;VR;Veneto;023014; +B296;Bussolengo;VR;Veneto;023015;37012 +B304;Buttapietra;VR;Veneto;023016;37060 +B402;Caldiero;VR;Veneto;023017;37042 +B709;Caprino Veronese;VR;Veneto;023018;37013 +B886;Casaleone;VR;Veneto;023019;37052 +C041;Castagnaro;VR;Veneto;023020;37043 +C078;Castel d'Azzano;VR;Veneto;023021;37060 +C225;Castelnuovo del Garda;VR;Veneto;023022;37014 +C370;Cavaion Veronese;VR;Veneto;023023;37010 +C412;Cazzano di Tramigna;VR;Veneto;023024;37030 +C498;Cerea;VR;Veneto;023025;37053 +C538;Cerro Veronese;VR;Veneto;023026;37020 +C890;Cologna Veneta;VR;Veneto;023027;37044 +C897;Colognola ai Colli;VR;Veneto;023028;37030 +C943;Concamarise;VR;Veneto;023029;37050 +D118;Costermano sul Garda;VR;Veneto;023030; +D317;Dolcè;VR;Veneto;023031;37020 +D419;Erbè;VR;Veneto;023032;37060 +D420;Erbezzo;VR;Veneto;023033;37020 +D549;Ferrara di Monte Baldo;VR;Veneto;023034;37020 +D818;Fumane;VR;Veneto;023035;37022 +D915;Garda;VR;Veneto;023036;37016 +D957;Gazzo Veronese;VR;Veneto;023037;37060 +E171;Grezzana;VR;Veneto;023038;37023 +E284;Illasi;VR;Veneto;023039;37031 +E349;Isola della Scala;VR;Veneto;023040;37063 +E358;Isola Rizza;VR;Veneto;023041;37050 +E489;Lavagno;VR;Veneto;023042;37030 +E502;Lazise;VR;Veneto;023043;37017 +E512;Legnago;VR;Veneto;023044;37045 +E848;Malcesine;VR;Veneto;023045;37018 +E911;Marano di Valpolicella;VR;Veneto;023046;37020 +F172;Mezzane di Sotto;VR;Veneto;023047;37030 +F218;Minerbe;VR;Veneto;023048;37046 +F461;Montecchia di Crosara;VR;Veneto;023049;37030 +F508;Monteforte d'Alpone;VR;Veneto;023050;37032 +F789;Mozzecane;VR;Veneto;023051;37060 +F861;Negrar di Valpolicella;VR;Veneto;023052; +F918;Nogara;VR;Veneto;023053;37054 +F921;Nogarole Rocca;VR;Veneto;023054;37060 +G080;Oppeano;VR;Veneto;023055;37050 +G297;Palù;VR;Veneto;023056;37050 +G365;Pastrengo;VR;Veneto;023057;37010 +G481;Pescantina;VR;Veneto;023058;37026 +G489;Peschiera del Garda;VR;Veneto;023059;37019 +G945;Povegliano Veronese;VR;Veneto;023060;37064 +H048;Pressana;VR;Veneto;023061;37040 +H356;Rivoli Veronese;VR;Veneto;023062;37010 +H522;Roncà;VR;Veneto;023063;37030 +H540;Ronco all'Adige;VR;Veneto;023064;37055 +H606;Roverchiara;VR;Veneto;023065;37050 +H610;Roveredo di Guà;VR;Veneto;023066;37040 +H608;Roverè Veronese;VR;Veneto;023067;37028 +H714;Salizzole;VR;Veneto;023068;37056 +H783;San Bonifacio;VR;Veneto;023069;37047 +H916;San Giovanni Ilarione;VR;Veneto;023070;37035 +H924;San Giovanni Lupatoto;VR;Veneto;023071;37057 +H944;Sanguinetto;VR;Veneto;023072;37058 +I003;San Martino Buon Albergo;VR;Veneto;023073;37036 +H712;San Mauro di Saline;VR;Veneto;023074;37030 +I105;San Pietro di Morubio;VR;Veneto;023075;37050 +I109;San Pietro in Cariano;VR;Veneto;023076;37029 +I259;Sant'Ambrogio di Valpolicella;VR;Veneto;023077;37015 +I292;Sant'Anna d'Alfaedo;VR;Veneto;023078;37020 +I414;San Zeno di Montagna;VR;Veneto;023079;37010 +I594;Selva di Progno;VR;Veneto;023080;37030 +I775;Soave;VR;Veneto;023081;37038 +I821;Sommacampagna;VR;Veneto;023082;37066 +I826;Sona;VR;Veneto;023083;37060 +I850;Sorgà;VR;Veneto;023084;37060 +L136;Terrazzo;VR;Veneto;023085;37040 +L287;Torri del Benaco;VR;Veneto;023086;37010 +L364;Tregnago;VR;Veneto;023087;37039 +L396;Trevenzuolo;VR;Veneto;023088;37060 +L567;Valeggio sul Mincio;VR;Veneto;023089;37067 +L722;Velo Veronese;VR;Veneto;023090;37030 +L781;Verona;VR;Veneto;023091;37100,37121-37142 +D193;Veronella;VR;Veneto;023092;37040 +L810;Vestenanova;VR;Veneto;023093;37030 +L869;Vigasio;VR;Veneto;023094;37068 +L912;Villa Bartolomea;VR;Veneto;023095;37049 +L949;Villafranca di Verona;VR;Veneto;023096;37069 +M172;Zevio;VR;Veneto;023097;37059 +M178;Zimella;VR;Veneto;023098;37040 +A093;Agugliaro;VI;Veneto;024001;36020 +A154;Albettone;VI;Veneto;024002;36020 +A220;Alonte;VI;Veneto;024003;36045 +A231;Altavilla Vicentina;VI;Veneto;024004;36077 +A236;Altissimo;VI;Veneto;024005;36070 +A377;Arcugnano;VI;Veneto;024006;36057 +A444;Arsiero;VI;Veneto;024007;36011 +A459;Arzignano;VI;Veneto;024008;36071 +A465;Asiago;VI;Veneto;024009;36012 +A467;Asigliano Veneto;VI;Veneto;024010;36020 +A703;Bassano del Grappa;VI;Veneto;024012;36061 +A954;Bolzano Vicentino;VI;Veneto;024013;36050 +B132;Breganze;VI;Veneto;024014;36042 +B143;Brendola;VI;Veneto;024015;36040 +B161;Bressanvido;VI;Veneto;024016;36050 +B196;Brogliano;VI;Veneto;024017;36070 +B403;Caldogno;VI;Veneto;024018;36030 +B433;Caltrano;VI;Veneto;024019;36030 +B441;Calvene;VI;Veneto;024020;36030 +B485;Camisano Vicentino;VI;Veneto;024021;36043 +B511;Campiglia dei Berici;VI;Veneto;024022;36020 +B835;Carrè;VI;Veneto;024024;36010 +B844;Cartigliano;VI;Veneto;024025;36050 +C037;Cassola;VI;Veneto;024026;36022 +C119;Castelgomberto;VI;Veneto;024028;36070 +C605;Chiampo;VI;Veneto;024029;36072 +C650;Chiuppano;VI;Veneto;024030;36010 +C824;Cogollo del Cengio;VI;Veneto;024032;36010 +D020;Cornedo Vicentino;VI;Veneto;024034;36073 +D107;Costabissara;VI;Veneto;024035;36030 +D136;Creazzo;VI;Veneto;024036;36051 +D156;Crespadoro;VI;Veneto;024037;36070 +D379;Dueville;VI;Veneto;024038;36031 +D407;Enego;VI;Veneto;024039;36052 +D496;Fara Vicentino;VI;Veneto;024040;36030 +D750;Foza;VI;Veneto;024041;36010 +D882;Gallio;VI;Veneto;024042;36032 +D897;Gambellara;VI;Veneto;024043;36053 +E184;Grisignano di Zocco;VI;Veneto;024046;36040 +E226;Grumolo delle Abbadesse;VI;Veneto;024047;36040 +E354;Isola Vicentina;VI;Veneto;024048;36033 +E403;Laghi;VI;Veneto;024049;36010 +E465;Lastebasse;VI;Veneto;024050;36040 +E671;Longare;VI;Veneto;024051;36023 +E682;Lonigo;VI;Veneto;024052;36045 +E731;Lugo di Vicenza;VI;Veneto;024053;36030 +E864;Malo;VI;Veneto;024055;36034 +E912;Marano Vicentino;VI;Veneto;024056;36035 +E970;Marostica;VI;Veneto;024057;36063 +F442;Montebello Vicentino;VI;Veneto;024060;36054 +F464;Montecchio Maggiore;VI;Veneto;024061;36075 +F465;Montecchio Precalcino;VI;Veneto;024062;36030 +F486;Monte di Malo;VI;Veneto;024063;36030 +F514;Montegalda;VI;Veneto;024064;36047 +F515;Montegaldella;VI;Veneto;024065;36047 +F662;Monteviale;VI;Veneto;024066;36050 +F675;Monticello Conte Otto;VI;Veneto;024067;36010 +F696;Montorso Vicentino;VI;Veneto;024068;36050 +F829;Mussolente;VI;Veneto;024070;36065 +F922;Nogarole Vicentino;VI;Veneto;024072;36070 +F957;Nove;VI;Veneto;024073;36055 +F964;Noventa Vicentina;VI;Veneto;024074;36025 +G095;Orgiano;VI;Veneto;024075;36040 +G406;Pedemonte;VI;Veneto;024076;36040 +G560;Pianezze;VI;Veneto;024077;36060 +G694;Piovene Rocchette;VI;Veneto;024078;36013 +G776;Pojana Maggiore;VI;Veneto;024079; +G931;Posina;VI;Veneto;024080;36010 +G943;Pove del Grappa;VI;Veneto;024081;36020 +G957;Pozzoleone;VI;Veneto;024082;36050 +H134;Quinto Vicentino;VI;Veneto;024083;36050 +H214;Recoaro Terme;VI;Veneto;024084;36076 +H361;Roana;VI;Veneto;024085;36010 +H512;Romano d'Ezzelino;VI;Veneto;024086;36060 +H556;Rosà;VI;Veneto;024087;36027 +H580;Rossano Veneto;VI;Veneto;024088;36028 +H594;Rotzo;VI;Veneto;024089;36010 +F810;Salcedo;VI;Veneto;024090;36040 +H829;Sandrigo;VI;Veneto;024091;36066 +I117;San Pietro Mussolino;VI;Veneto;024094;36070 +I353;Santorso;VI;Veneto;024095;36014 +I401;San Vito di Leguzzano;VI;Veneto;024096;36030 +I425;Sarcedo;VI;Veneto;024097;36030 +I430;Sarego;VI;Veneto;024098;36040 +I527;Schiavon;VI;Veneto;024099;36060 +I531;Schio;VI;Veneto;024100;36015 +I783;Solagna;VI;Veneto;024101;36020 +I867;Sossano;VI;Veneto;024102;36040 +L156;Tezze sul Brenta;VI;Veneto;024104;36056 +L157;Thiene;VI;Veneto;024105;36016 +D717;Tonezza del Cimone;VI;Veneto;024106;36040 +L248;Torrebelvicino;VI;Veneto;024107;36036 +L297;Torri di Quartesolo;VI;Veneto;024108;36040 +L433;Trissino;VI;Veneto;024110;36070 +L551;Valdagno;VI;Veneto;024111;36078 +L554;Valdastico;VI;Veneto;024112;36040 +L624;Valli del Pasubio;VI;Veneto;024113;36030 +L723;Velo d'Astico;VI;Veneto;024115;36010 +L840;Vicenza;VI;Veneto;024116;36100 +L952;Villaga;VI;Veneto;024117;36021 +M032;Villaverla;VI;Veneto;024118;36030 +M145;Zanè;VI;Veneto;024119;36010 +M170;Zermeghedo;VI;Veneto;024120;36050 +M194;Zovencedo;VI;Veneto;024121;36020 +M199;Zugliano;VI;Veneto;024122;36030 +M384;Val Liona;VI;Veneto;024123; +M401;Barbarano Mossano;VI;Veneto;024124; +M423;Valbrenta;VI;Veneto;024125; +M426;Colceresa;VI;Veneto;024126; +M427;Lusiana Conco;VI;Veneto;024127; +M436;Sovizzo;VI;Veneto;024128;36050 +M439;Castegnero Nanto;VI;Veneto;024129; +A083;Agordo;BL;Veneto;025001;32021 +A206;Alleghe;BL;Veneto;025003;32022 +A443;Arsiè;BL;Veneto;025004;32030 +A501;Auronzo di Cadore;BL;Veneto;025005;32041 +A757;Belluno;BL;Veneto;025006;32100 +A982;Borca di Cadore;BL;Veneto;025007;32040 +B375;Calalzo di Cadore;BL;Veneto;025008;32042 +C458;Cencenighe Agordino;BL;Veneto;025010;32020 +C577;Cesiomaggiore;BL;Veneto;025011;32030 +C630;Chies d'Alpago;BL;Veneto;025012;32010 +C672;Cibiana di Cadore;BL;Veneto;025013;32040 +C872;Colle Santa Lucia;BL;Veneto;025014;32020 +C920;Comelico Superiore;BL;Veneto;025015;32040 +A266;Cortina d'Ampezzo;BL;Veneto;025016;32043 +D247;Danta di Cadore;BL;Veneto;025017;32040 +D330;Domegge di Cadore;BL;Veneto;025018;32040 +D470;Falcade;BL;Veneto;025019;32020 +D530;Feltre;BL;Veneto;025021;32032 +D686;Fonzaso;BL;Veneto;025022;32030 +B574;Canale d'Agordo;BL;Veneto;025023;32020 +E113;Gosaldo;BL;Veneto;025025;32020 +E429;Lamon;BL;Veneto;025026;32033 +E490;La Valle Agordina;BL;Veneto;025027;32020 +E588;Limana;BL;Veneto;025029;32020 +E622;Livinallongo del Col di Lana;BL;Veneto;025030;32020 +E687;Lorenzago di Cadore;BL;Veneto;025032;32040 +E708;Lozzo di Cadore;BL;Veneto;025033;32040 +G169;Ospitale di Cadore;BL;Veneto;025035;32010 +G404;Pedavena;BL;Veneto;025036;32034 +G442;Perarolo di Cadore;BL;Veneto;025037;32010 +G642;Pieve di Cadore;BL;Veneto;025039;32044 +B662;Ponte nelle Alpi;BL;Veneto;025040;32014 +H327;Rivamonte Agordino;BL;Veneto;025043;32020 +H379;Rocca Pietore;BL;Veneto;025044;32023 +H938;San Gregorio nelle Alpi;BL;Veneto;025045;32030 +I063;San Nicolò di Comelico;BL;Veneto;025046;32040 +I088;San Pietro di Cadore;BL;Veneto;025047;32040 +I206;Santa Giustina;BL;Veneto;025048;32035 +I347;San Tomaso Agordino;BL;Veneto;025049;32020 +C919;Santo Stefano di Cadore;BL;Veneto;025050;32045 +I392;San Vito di Cadore;BL;Veneto;025051;32046 +I563;Sedico;BL;Veneto;025053;32036 +I592;Selva di Cadore;BL;Veneto;025054;32020 +I626;Seren del Grappa;BL;Veneto;025055;32030 +I866;Sospirolo;BL;Veneto;025056;32037 +I876;Soverzene;BL;Veneto;025057;32010 +I673;Sovramonte;BL;Veneto;025058;32030 +L030;Taibon Agordino;BL;Veneto;025059;32027 +L040;Tambre;BL;Veneto;025060;32010 +L584;Vallada Agordina;BL;Veneto;025062;32020 +L590;Valle di Cadore;BL;Veneto;025063;32040 +L890;Vigo di Cadore;BL;Veneto;025065;32040 +M108;Vodo Cadore;BL;Veneto;025066;32040 +M124;Voltago Agordino;BL;Veneto;025067;32020 +M189;Zoppè di Cadore;BL;Veneto;025069;32010 +M342;Longarone;BL;Veneto;025071;32013 +M375;Alpago;BL;Veneto;025072; +M374;Val di Zoldo;BL;Veneto;025073; +M421;Borgo Valbelluna;BL;Veneto;025074; +M437;Setteville;BL;Veneto;025075; +A237;Altivole;TV;Veneto;026001;31030 +A360;Arcade;TV;Veneto;026002;31030 +A471;Asolo;TV;Veneto;026003;31011 +B061;Borso del Grappa;TV;Veneto;026004;31030 +B128;Breda di Piave;TV;Veneto;026005;31030 +B349;Caerano di San Marco;TV;Veneto;026006;31031 +B678;Cappella Maggiore;TV;Veneto;026007;31012 +B744;Carbonera;TV;Veneto;026008;31030 +B879;Casale sul Sile;TV;Veneto;026009;31032 +B965;Casier;TV;Veneto;026010;31030 +C073;Castelcucco;TV;Veneto;026011;31030 +C111;Castelfranco Veneto;TV;Veneto;026012;31033 +C190;Castello di Godego;TV;Veneto;026013;31030 +C384;Cavaso del Tomba;TV;Veneto;026014;31034 +C580;Cessalto;TV;Veneto;026015;31040 +C614;Chiarano;TV;Veneto;026016;31040 +C689;Cimadolmo;TV;Veneto;026017;31010 +C735;Cison di Valmarino;TV;Veneto;026018;31030 +C815;Codognè;TV;Veneto;026019;31013 +C848;Colle Umberto;TV;Veneto;026020;31014 +C957;Conegliano;TV;Veneto;026021;31015 +C992;Cordignano;TV;Veneto;026022;31016 +D030;Cornuda;TV;Veneto;026023;31041 +C670;Crocetta del Montello;TV;Veneto;026025;31035 +D505;Farra di Soligo;TV;Veneto;026026;31010 +D654;Follina;TV;Veneto;026027;31051 +D674;Fontanelle;TV;Veneto;026028;31043 +D680;Fonte;TV;Veneto;026029;31010 +D794;Fregona;TV;Veneto;026030;31010 +D854;Gaiarine;TV;Veneto;026031;31018 +E021;Giavera del Montello;TV;Veneto;026032;31040 +E071;Godega di Sant'Urbano;TV;Veneto;026033;31010 +E092;Gorgo al Monticano;TV;Veneto;026034;31040 +E373;Istrana;TV;Veneto;026035;31036 +E692;Loria;TV;Veneto;026036;31037 +E893;Mansuè;TV;Veneto;026037;31040 +E940;Mareno di Piave;TV;Veneto;026038;31010 +F009;Maser;TV;Veneto;026039;31010 +F012;Maserada sul Piave;TV;Veneto;026040;31052 +F088;Meduna di Livenza;TV;Veneto;026041;31040 +F190;Miane;TV;Veneto;026042;31050 +F269;Mogliano Veneto;TV;Veneto;026043;31021 +F332;Monastier di Treviso;TV;Veneto;026044;31050 +F360;Monfumo;TV;Veneto;026045;31010 +F443;Montebelluna;TV;Veneto;026046;31044 +F725;Morgano;TV;Veneto;026047;31050 +F729;Moriago della Battaglia;TV;Veneto;026048;31010 +F770;Motta di Livenza;TV;Veneto;026049;31045 +F872;Nervesa della Battaglia;TV;Veneto;026050;31040 +F999;Oderzo;TV;Veneto;026051;31046 +G115;Ormelle;TV;Veneto;026052;31024 +G123;Orsago;TV;Veneto;026053;31010 +G229;Paese;TV;Veneto;026055;31038 +G408;Pederobba;TV;Veneto;026056;31040 +G645;Pieve di Soligo;TV;Veneto;026057;31053 +G846;Ponte di Piave;TV;Veneto;026058;31047 +G875;Ponzano Veneto;TV;Veneto;026059;31050 +G909;Portobuffolè;TV;Veneto;026060;31040 +G933;Possagno;TV;Veneto;026061;31054 +G944;Povegliano;TV;Veneto;026062;31050 +H022;Preganziol;TV;Veneto;026063;31022 +H131;Quinto di Treviso;TV;Veneto;026064;31055 +H220;Refrontolo;TV;Veneto;026065;31020 +H238;Resana;TV;Veneto;026066;31023 +H253;Revine Lago;TV;Veneto;026067;31020 +H280;Riese Pio X;TV;Veneto;026068;31039 +H523;Roncade;TV;Veneto;026069;31056 +H706;Salgareda;TV;Veneto;026070;31040 +H781;San Biagio di Callalta;TV;Veneto;026071;31048 +H843;San Fior;TV;Veneto;026072;31020 +I103;San Pietro di Feletto;TV;Veneto;026073;31020 +I124;San Polo di Piave;TV;Veneto;026074;31020 +I221;Santa Lucia di Piave;TV;Veneto;026075;31025 +I382;San Vendemiano;TV;Veneto;026076;31020 +I417;San Zenone degli Ezzelini;TV;Veneto;026077;31020 +I435;Sarmede;TV;Veneto;026078;31026 +I578;Segusino;TV;Veneto;026079;31040 +I635;Sernaglia della Battaglia;TV;Veneto;026080;31020 +F116;Silea;TV;Veneto;026081;31057 +I927;Spresiano;TV;Veneto;026082;31027 +L014;Susegana;TV;Veneto;026083;31058 +L058;Tarzo;TV;Veneto;026084;31020 +L402;Trevignano;TV;Veneto;026085;31040 +L407;Treviso;TV;Veneto;026086;31100 +L565;Valdobbiadene;TV;Veneto;026087;31049 +L700;Vazzola;TV;Veneto;026088;31028 +L706;Vedelago;TV;Veneto;026089;31050 +L856;Vidor;TV;Veneto;026090;31020 +M048;Villorba;TV;Veneto;026091;31020 +M089;Vittorio Veneto;TV;Veneto;026092;31029 +M118;Volpago del Montello;TV;Veneto;026093;31040 +M163;Zenson di Piave;TV;Veneto;026094;31050 +M171;Zero Branco;TV;Veneto;026095;31059 +M422;Pieve del Grappa;TV;Veneto;026096; +A302;Annone Veneto;VE;Veneto;027001;30020 +B493;Campagna Lupia;VE;Veneto;027002;30010 +B546;Campolongo Maggiore;VE;Veneto;027003;30010 +B554;Camponogara;VE;Veneto;027004;30010 +B642;Caorle;VE;Veneto;027005;30021 +C383;Cavarzere;VE;Veneto;027006;30014 +C422;Ceggia;VE;Veneto;027007;30022 +C638;Chioggia;VE;Veneto;027008;30015 +C714;Cinto Caomaggiore;VE;Veneto;027009;30020 +C938;Cona;VE;Veneto;027010;30010 +C950;Concordia Sagittaria;VE;Veneto;027011;30023 +D325;Dolo;VE;Veneto;027012;30031 +D415;Eraclea;VE;Veneto;027013;30020 +D578;Fiesso d'Artico;VE;Veneto;027014;30032 +D740;Fossalta di Piave;VE;Veneto;027015;30020 +D741;Fossalta di Portogruaro;VE;Veneto;027016;30025 +D748;Fossò;VE;Veneto;027017;30030 +E215;Gruaro;VE;Veneto;027018;30020 +C388;Jesolo;VE;Veneto;027019; +E936;Marcon;VE;Veneto;027020;30020 +E980;Martellago;VE;Veneto;027021;30030 +F130;Meolo;VE;Veneto;027022;30020 +F229;Mira;VE;Veneto;027023;30034 +F241;Mirano;VE;Veneto;027024;30035 +F826;Musile di Piave;VE;Veneto;027025;30024 +F904;Noale;VE;Veneto;027026;30033 +F963;Noventa di Piave;VE;Veneto;027027;30020 +G565;Pianiga;VE;Veneto;027028;30030 +G914;Portogruaro;VE;Veneto;027029;30026 +G981;Pramaggiore;VE;Veneto;027030;30020 +H117;Quarto d'Altino;VE;Veneto;027031;30020 +H735;Salzano;VE;Veneto;027032;30030 +H823;San Donà di Piave;VE;Veneto;027033;30027 +I040;San Michele al Tagliamento;VE;Veneto;027034;30028 +I242;Santa Maria di Sala;VE;Veneto;027035;30036 +I373;San Stino di Livenza;VE;Veneto;027036; +I551;Scorzè;VE;Veneto;027037;30037 +I908;Spinea;VE;Veneto;027038;30038 +I965;Stra;VE;Veneto;027039;30039 +L085;Teglio Veneto;VE;Veneto;027040;30025 +L267;Torre di Mosto;VE;Veneto;027041;30020 +L736;Venezia;VE;Veneto;027042;30100,30121-30126,30131-30133,30135,30141,30173 +L899;Vigonovo;VE;Veneto;027043;30030 +M308;Cavallino-Treporti;VE;Veneto;027044;30013 +A001;Abano Terme;PD;Veneto;028001;35031 +A075;Agna;PD;Veneto;028002;35021 +A161;Albignasego;PD;Veneto;028003;35020 +A296;Anguillara Veneta;PD;Veneto;028004;35022 +A434;Arquà Petrarca;PD;Veneto;028005;35032 +A438;Arre;PD;Veneto;028006;35020 +A458;Arzergrande;PD;Veneto;028007;35020 +A568;Bagnoli di Sopra;PD;Veneto;028008;35023 +A613;Baone;PD;Veneto;028009;35030 +A637;Barbona;PD;Veneto;028010;35040 +A714;Battaglia Terme;PD;Veneto;028011;35041 +A906;Boara Pisani;PD;Veneto;028012;35040 +B031;Borgoricco;PD;Veneto;028013;35010 +B106;Bovolenta;PD;Veneto;028014;35024 +B213;Brugine;PD;Veneto;028015;35020 +B345;Cadoneghe;PD;Veneto;028016;35010 +B524;Campodarsego;PD;Veneto;028017;35011 +B531;Campodoro;PD;Veneto;028018;35010 +B563;Camposampiero;PD;Veneto;028019;35012 +B564;Campo San Martino;PD;Veneto;028020;35010 +B589;Candiana;PD;Veneto;028021;35020 +B795;Carmignano di Brenta;PD;Veneto;028023;35010 +B848;Cartura;PD;Veneto;028026;35025 +B877;Casale di Scodosia;PD;Veneto;028027;35040 +B912;Casalserugo;PD;Veneto;028028;35020 +C057;Castelbaldo;PD;Veneto;028029;35040 +C544;Cervarese Santa Croce;PD;Veneto;028030;35030 +C713;Cinto Euganeo;PD;Veneto;028031;35030 +C743;Cittadella;PD;Veneto;028032;35013 +C812;Codevigo;PD;Veneto;028033;35020 +C964;Conselve;PD;Veneto;028034;35026 +D040;Correzzola;PD;Veneto;028035;35020 +D226;Curtarolo;PD;Veneto;028036;35010 +D442;Este;PD;Veneto;028037;35042 +D679;Fontaniva;PD;Veneto;028038;35014 +D879;Galliera Veneta;PD;Veneto;028039;35015 +D889;Galzignano Terme;PD;Veneto;028040;35030 +D956;Gazzo;PD;Veneto;028041;35010 +E145;Grantorto;PD;Veneto;028042;35010 +E146;Granze;PD;Veneto;028043;35040 +E515;Legnaro;PD;Veneto;028044;35020 +E592;Limena;PD;Veneto;028045;35010 +E684;Loreggia;PD;Veneto;028046;35010 +E709;Lozzo Atestino;PD;Veneto;028047;35034 +F011;Maserà di Padova;PD;Veneto;028048;35020 +F013;Masi;PD;Veneto;028049;35040 +F033;Massanzago;PD;Veneto;028050;35010 +F092;Megliadino San Vitale;PD;Veneto;028052;35040 +F148;Merlara;PD;Veneto;028053;35040 +F161;Mestrino;PD;Veneto;028054;35035 +F382;Monselice;PD;Veneto;028055;35043 +F394;Montagnana;PD;Veneto;028056;35044 +F529;Montegrotto Terme;PD;Veneto;028057;35036 +F962;Noventa Padovana;PD;Veneto;028058;35027 +G167;Ospedaletto Euganeo;PD;Veneto;028059;35045 +G224;Padova;PD;Veneto;028060;35100,35121-35143 +G461;Pernumia;PD;Veneto;028061;35020 +G534;Piacenza d'Adige;PD;Veneto;028062;35040 +G587;Piazzola sul Brenta;PD;Veneto;028063;35016 +G688;Piombino Dese;PD;Veneto;028064;35017 +G693;Piove di Sacco;PD;Veneto;028065;35028 +G802;Polverara;PD;Veneto;028066;35020 +G823;Ponso;PD;Veneto;028067;35040 +G850;Pontelongo;PD;Veneto;028068;35029 +G855;Ponte San Nicolò;PD;Veneto;028069;35020 +G963;Pozzonovo;PD;Veneto;028070;35020 +H622;Rovolon;PD;Veneto;028071;35030 +H625;Rubano;PD;Veneto;028072;35030 +H655;Saccolongo;PD;Veneto;028073;35030 +H893;San Giorgio delle Pertiche;PD;Veneto;028075;35010 +H897;San Giorgio in Bosco;PD;Veneto;028076;35010 +I008;San Martino di Lupari;PD;Veneto;028077;35018 +I107;San Pietro in Gu;PD;Veneto;028078;35010 +I120;San Pietro Viminario;PD;Veneto;028079;35020 +I207;Santa Giustina in Colle;PD;Veneto;028080;35010 +I275;Sant'Angelo di Piove di Sacco;PD;Veneto;028082;35020 +I319;Sant'Elena;PD;Veneto;028083;35040 +I375;Sant'Urbano;PD;Veneto;028084;35040 +I418;Saonara;PD;Veneto;028085;35020 +I595;Selvazzano Dentro;PD;Veneto;028086;35030 +I799;Solesino;PD;Veneto;028087;35047 +I938;Stanghella;PD;Veneto;028088;35048 +L100;Teolo;PD;Veneto;028089;35037 +L132;Terrassa Padovana;PD;Veneto;028090;35020 +L199;Tombolo;PD;Veneto;028091;35019 +L270;Torreglia;PD;Veneto;028092;35038 +L349;Trebaseleghe;PD;Veneto;028093;35010 +L414;Tribano;PD;Veneto;028094;35020 +L497;Urbana;PD;Veneto;028095;35040 +L710;Veggiano;PD;Veneto;028096;35030 +L805;Vescovana;PD;Veneto;028097;35040 +L892;Vigodarzere;PD;Veneto;028099;35010 +L900;Vigonza;PD;Veneto;028100;35010 +L934;Villa del Conte;PD;Veneto;028101;35010 +L937;Villa Estense;PD;Veneto;028102;35040 +L947;Villafranca Padovana;PD;Veneto;028103;35010 +L979;Villanova di Camposampiero;PD;Veneto;028104;35010 +M103;Vo';PD;Veneto;028105;35030 +M300;Due Carrare;PD;Veneto;028106;35020 +M402;Borgo Veneto;PD;Veneto;028107; +M438;Santa Caterina d'Este;PD;Veneto;028108; +A059;Adria;RO;Veneto;029001;45011 +A400;Ariano nel Polesine;RO;Veneto;029002;45012 +A435;Arquà Polesine;RO;Veneto;029003;45031 +A539;Badia Polesine;RO;Veneto;029004;45021 +A574;Bagnolo di Po;RO;Veneto;029005;45022 +A795;Bergantino;RO;Veneto;029006;45032 +B069;Bosaro;RO;Veneto;029007;45033 +B432;Calto;RO;Veneto;029008;45030 +B578;Canaro;RO;Veneto;029009;45034 +B582;Canda;RO;Veneto;029010;45020 +C122;Castelguglielmo;RO;Veneto;029011;45020 +C207;Castelmassa;RO;Veneto;029012;45035 +C215;Castelnovo Bariano;RO;Veneto;029013;45030 +C461;Ceneselli;RO;Veneto;029014;45030 +C500;Ceregnano;RO;Veneto;029015;45010 +C987;Corbola;RO;Veneto;029017;45015 +D105;Costa di Rovigo;RO;Veneto;029018;45023 +D161;Crespino;RO;Veneto;029019;45030 +D568;Ficarolo;RO;Veneto;029021;45036 +D577;Fiesso Umbertiano;RO;Veneto;029022;45024 +D776;Frassinelle Polesine;RO;Veneto;029023;45030 +D788;Fratta Polesine;RO;Veneto;029024;45025 +D855;Gaiba;RO;Veneto;029025;45030 +D942;Gavello;RO;Veneto;029026;45010 +E008;Giacciano con Baruchella;RO;Veneto;029027;45020 +E240;Guarda Veneta;RO;Veneto;029028;45030 +E522;Lendinara;RO;Veneto;029029;45026 +E689;Loreo;RO;Veneto;029030;45017 +E761;Lusia;RO;Veneto;029031;45020 +F095;Melara;RO;Veneto;029032;45037 +F994;Occhiobello;RO;Veneto;029033;45030 +G323;Papozze;RO;Veneto;029034;45010 +G525;Pettorazza Grimani;RO;Veneto;029035;45010 +G673;Pincara;RO;Veneto;029036;45020 +G782;Polesella;RO;Veneto;029037;45038 +G836;Pontecchio Polesine;RO;Veneto;029038;45030 +G923;Porto Tolle;RO;Veneto;029039;45018 +H573;Rosolina;RO;Veneto;029040;45010 +H620;Rovigo;RO;Veneto;029041;45100 +H689;Salara;RO;Veneto;029042;45030 +H768;San Bellino;RO;Veneto;029043;45020 +H996;San Martino di Venezze;RO;Veneto;029044;45030 +I953;Stienta;RO;Veneto;029045;45039 +L026;Taglio di Po;RO;Veneto;029046;45019 +L359;Trecenta;RO;Veneto;029047;45027 +L939;Villadose;RO;Veneto;029048;45010 +L967;Villamarzana;RO;Veneto;029049;45030 +L985;Villanova del Ghebbo;RO;Veneto;029050;45020 +L988;Villanova Marchesana;RO;Veneto;029051;45030 +G926;Porto Viro;RO;Veneto;029052;45014 +A103;Aiello del Friuli;UD;Friuli-Venezia Giulia;030001;33041 +A254;Amaro;UD;Friuli-Venezia Giulia;030002;33020 +A267;Ampezzo;UD;Friuli-Venezia Giulia;030003;33021 +A346;Aquileia;UD;Friuli-Venezia Giulia;030004;33051 +A447;Arta Terme;UD;Friuli-Venezia Giulia;030005;33022 +A448;Artegna;UD;Friuli-Venezia Giulia;030006;33011 +A491;Attimis;UD;Friuli-Venezia Giulia;030007;33040 +A553;Bagnaria Arsa;UD;Friuli-Venezia Giulia;030008;33050 +A700;Basiliano;UD;Friuli-Venezia Giulia;030009;33031 +A810;Bertiolo;UD;Friuli-Venezia Giulia;030010;33032 +A855;Bicinicco;UD;Friuli-Venezia Giulia;030011;33050 +A983;Bordano;UD;Friuli-Venezia Giulia;030012;33010 +B259;Buja;UD;Friuli-Venezia Giulia;030013;33030 +B309;Buttrio;UD;Friuli-Venezia Giulia;030014;33042 +B483;Camino al Tagliamento;UD;Friuli-Venezia Giulia;030015;33030 +B536;Campoformido;UD;Friuli-Venezia Giulia;030016;33030 +B788;Carlino;UD;Friuli-Venezia Giulia;030018;33050 +B994;Cassacco;UD;Friuli-Venezia Giulia;030019;33010 +C327;Castions di Strada;UD;Friuli-Venezia Giulia;030020;33050 +C389;Cavazzo Carnico;UD;Friuli-Venezia Giulia;030021;33020 +C494;Cercivento;UD;Friuli-Venezia Giulia;030022;33020 +C556;Cervignano del Friuli;UD;Friuli-Venezia Giulia;030023;33052 +C641;Chiopris-Viscone;UD;Friuli-Venezia Giulia;030024;33048 +C656;Chiusaforte;UD;Friuli-Venezia Giulia;030025;33010 +C758;Cividale del Friuli;UD;Friuli-Venezia Giulia;030026;33043 +C817;Codroipo;UD;Friuli-Venezia Giulia;030027;33033 +C885;Colloredo di Monte Albano;UD;Friuli-Venezia Giulia;030028;33010 +C918;Comeglians;UD;Friuli-Venezia Giulia;030029;33023 +D027;Corno di Rosazzo;UD;Friuli-Venezia Giulia;030030;33040 +D085;Coseano;UD;Friuli-Venezia Giulia;030031;33030 +D300;Dignano;UD;Friuli-Venezia Giulia;030032;33030 +D316;Dogna;UD;Friuli-Venezia Giulia;030033;33010 +D366;Drenchia;UD;Friuli-Venezia Giulia;030034;33040 +D408;Enemonzo;UD;Friuli-Venezia Giulia;030035;33020 +D455;Faedis;UD;Friuli-Venezia Giulia;030036;33040 +D461;Fagagna;UD;Friuli-Venezia Giulia;030037;33034 +D630;Flaibano;UD;Friuli-Venezia Giulia;030039;33030 +D718;Forni Avoltri;UD;Friuli-Venezia Giulia;030040;33020 +D719;Forni di Sopra;UD;Friuli-Venezia Giulia;030041;33024 +D720;Forni di Sotto;UD;Friuli-Venezia Giulia;030042;33020 +D962;Gemona del Friuli;UD;Friuli-Venezia Giulia;030043;33013 +E083;Gonars;UD;Friuli-Venezia Giulia;030044;33050 +E179;Grimacco;UD;Friuli-Venezia Giulia;030045;33040 +E473;Latisana;UD;Friuli-Venezia Giulia;030046;33053 +E476;Lauco;UD;Friuli-Venezia Giulia;030047;33029 +E553;Lestizza;UD;Friuli-Venezia Giulia;030048;33050 +E584;Lignano Sabbiadoro;UD;Friuli-Venezia Giulia;030049;33054 +E760;Lusevera;UD;Friuli-Venezia Giulia;030051;33010 +E820;Magnano in Riviera;UD;Friuli-Venezia Giulia;030052;33010 +E833;Majano;UD;Friuli-Venezia Giulia;030053;33030 +E847;Malborghetto Valbruna;UD;Friuli-Venezia Giulia;030054;33010 +E899;Manzano;UD;Friuli-Venezia Giulia;030055;33044 +E910;Marano Lagunare;UD;Friuli-Venezia Giulia;030056;33050 +E982;Martignacco;UD;Friuli-Venezia Giulia;030057;33035 +F144;Mereto di Tomba;UD;Friuli-Venezia Giulia;030058;33036 +F266;Moggio Udinese;UD;Friuli-Venezia Giulia;030059;33015 +F275;Moimacco;UD;Friuli-Venezia Giulia;030060;33040 +F574;Montenars;UD;Friuli-Venezia Giulia;030061;33010 +F756;Mortegliano;UD;Friuli-Venezia Giulia;030062;33050 +F760;Moruzzo;UD;Friuli-Venezia Giulia;030063;33030 +F832;Muzzana del Turgnano;UD;Friuli-Venezia Giulia;030064;33055 +F898;Nimis;UD;Friuli-Venezia Giulia;030065;33045 +G163;Osoppo;UD;Friuli-Venezia Giulia;030066;33010 +G198;Ovaro;UD;Friuli-Venezia Giulia;030067;33025 +G238;Pagnacco;UD;Friuli-Venezia Giulia;030068;33010 +G268;Palazzolo dello Stella;UD;Friuli-Venezia Giulia;030069;33056 +G284;Palmanova;UD;Friuli-Venezia Giulia;030070;33057 +G300;Paluzza;UD;Friuli-Venezia Giulia;030071;33026 +G352;Pasian di Prato;UD;Friuli-Venezia Giulia;030072;33037 +G381;Paularo;UD;Friuli-Venezia Giulia;030073;33027 +G389;Pavia di Udine;UD;Friuli-Venezia Giulia;030074;33050 +G743;Pocenia;UD;Friuli-Venezia Giulia;030075;33050 +G831;Pontebba;UD;Friuli-Venezia Giulia;030076;33016 +G891;Porpetto;UD;Friuli-Venezia Giulia;030077;33050 +G949;Povoletto;UD;Friuli-Venezia Giulia;030078;33040 +G966;Pozzuolo del Friuli;UD;Friuli-Venezia Giulia;030079;33050 +G969;Pradamano;UD;Friuli-Venezia Giulia;030080;33040 +H002;Prato Carnico;UD;Friuli-Venezia Giulia;030081;33020 +H014;Precenicco;UD;Friuli-Venezia Giulia;030082;33050 +H029;Premariacco;UD;Friuli-Venezia Giulia;030083;33040 +H038;Preone;UD;Friuli-Venezia Giulia;030084;33020 +H040;Prepotto;UD;Friuli-Venezia Giulia;030085;33040 +H089;Pulfero;UD;Friuli-Venezia Giulia;030086;33046 +H161;Ragogna;UD;Friuli-Venezia Giulia;030087;33030 +H196;Ravascletto;UD;Friuli-Venezia Giulia;030088;33020 +H200;Raveo;UD;Friuli-Venezia Giulia;030089;33029 +H206;Reana del Rojale;UD;Friuli-Venezia Giulia;030090; +H229;Remanzacco;UD;Friuli-Venezia Giulia;030091;33047 +H242;Resia;UD;Friuli-Venezia Giulia;030092;33010 +H244;Resiutta;UD;Friuli-Venezia Giulia;030093;33010 +H289;Rigolato;UD;Friuli-Venezia Giulia;030094;33020 +H347;Rive d'Arcano;UD;Friuli-Venezia Giulia;030095;33030 +H533;Ronchis;UD;Friuli-Venezia Giulia;030097;33050 +H629;Ruda;UD;Friuli-Venezia Giulia;030098;33050 +H816;San Daniele del Friuli;UD;Friuli-Venezia Giulia;030099;33038 +H895;San Giorgio di Nogaro;UD;Friuli-Venezia Giulia;030100;33058 +H906;San Giovanni al Natisone;UD;Friuli-Venezia Giulia;030101;33048 +H951;San Leonardo;UD;Friuli-Venezia Giulia;030102;33040 +I092;San Pietro al Natisone;UD;Friuli-Venezia Giulia;030103;33049 +I248;Santa Maria la Longa;UD;Friuli-Venezia Giulia;030104;33050 +I404;San Vito al Torre;UD;Friuli-Venezia Giulia;030105;33050 +I405;San Vito di Fagagna;UD;Friuli-Venezia Giulia;030106;33030 +I464;Sauris;UD;Friuli-Venezia Giulia;030107;33020 +I478;Savogna;UD;Friuli-Venezia Giulia;030108;33040 +I562;Sedegliano;UD;Friuli-Venezia Giulia;030109;33039 +I777;Socchieve;UD;Friuli-Venezia Giulia;030110;33020 +I974;Stregna;UD;Friuli-Venezia Giulia;030111;33040 +L018;Sutrio;UD;Friuli-Venezia Giulia;030112;33020 +G736;Taipana;UD;Friuli-Venezia Giulia;030113;33040 +L039;Talmassons;UD;Friuli-Venezia Giulia;030114;33030 +L050;Tarcento;UD;Friuli-Venezia Giulia;030116;33017 +L057;Tarvisio;UD;Friuli-Venezia Giulia;030117;33018 +L065;Tavagnacco;UD;Friuli-Venezia Giulia;030118;33010 +L144;Terzo d'Aquileia;UD;Friuli-Venezia Giulia;030120;33050 +L195;Tolmezzo;UD;Friuli-Venezia Giulia;030121;33028 +L246;Torreano;UD;Friuli-Venezia Giulia;030122;33040 +L309;Torviscosa;UD;Friuli-Venezia Giulia;030123;33050 +L335;Trasaghis;UD;Friuli-Venezia Giulia;030124;33010 +L382;Treppo Grande;UD;Friuli-Venezia Giulia;030126;33010 +L421;Tricesimo;UD;Friuli-Venezia Giulia;030127;33019 +L438;Trivignano Udinese;UD;Friuli-Venezia Giulia;030128;33050 +L483;Udine;UD;Friuli-Venezia Giulia;030129;33100 +L686;Varmo;UD;Friuli-Venezia Giulia;030130;33030 +L743;Venzone;UD;Friuli-Venezia Giulia;030131;33010 +L801;Verzegnis;UD;Friuli-Venezia Giulia;030132;33020 +L909;Villa Santina;UD;Friuli-Venezia Giulia;030133;33029 +M073;Visco;UD;Friuli-Venezia Giulia;030135;33040 +M200;Zuglio;UD;Friuli-Venezia Giulia;030136;33020 +D700;Forgaria nel Friuli;UD;Friuli-Venezia Giulia;030137;33030 +M311;Campolongo Tapogliano;UD;Friuli-Venezia Giulia;030138; +M317;Rivignano Teor;UD;Friuli-Venezia Giulia;030188;33061 +I421;Sappada;UD;Friuli-Venezia Giulia;030189; +M400;Fiumicello Villa Vicentina;UD;Friuli-Venezia Giulia;030190; +M399;Treppo Ligosullo;UD;Friuli-Venezia Giulia;030191; +B712;Capriva del Friuli;GO;Friuli-Venezia Giulia;031001;34070 +D014;Cormons;GO;Friuli-Venezia Giulia;031002;34071 +D312;Doberdò del Lago;GO;Friuli-Venezia Giulia;031003;34070 +D321;Dolegna del Collio;GO;Friuli-Venezia Giulia;031004;34070 +D504;Farra d'Isonzo;GO;Friuli-Venezia Giulia;031005;34072 +D645;Fogliano Redipuglia;GO;Friuli-Venezia Giulia;031006;34070 +E098;Gorizia;GO;Friuli-Venezia Giulia;031007;34170 +E124;Gradisca d'Isonzo;GO;Friuli-Venezia Giulia;031008;34072 +E125;Grado;GO;Friuli-Venezia Giulia;031009;34073 +E952;Mariano del Friuli;GO;Friuli-Venezia Giulia;031010;34070 +F081;Medea;GO;Friuli-Venezia Giulia;031011;34076 +F356;Monfalcone;GO;Friuli-Venezia Giulia;031012;34074 +F710;Moraro;GO;Friuli-Venezia Giulia;031013;34070 +F767;Mossa;GO;Friuli-Venezia Giulia;031014;34070 +H514;Romans d'Isonzo;GO;Friuli-Venezia Giulia;031015;34076 +H531;Ronchi dei Legionari;GO;Friuli-Venezia Giulia;031016;34077 +H665;Sagrado;GO;Friuli-Venezia Giulia;031017;34078 +H787;San Canzian d'Isonzo;GO;Friuli-Venezia Giulia;031018;34075 +H845;San Floriano del Collio;GO;Friuli-Venezia Giulia;031019;34070 +H964;San Lorenzo Isontino;GO;Friuli-Venezia Giulia;031020;34070 +I082;San Pier d'Isonzo;GO;Friuli-Venezia Giulia;031021;34070 +I479;Savogna d'Isonzo;GO;Friuli-Venezia Giulia;031022;34070 +I939;Staranzano;GO;Friuli-Venezia Giulia;031023;34079 +L474;Turriaco;GO;Friuli-Venezia Giulia;031024;34070 +M043;Villesse;GO;Friuli-Venezia Giulia;031025;34070 +D383;Duino Aurisina;TS;Friuli-Venezia Giulia;032001;34011 +F378;Monrupino;TS;Friuli-Venezia Giulia;032002;34016 +F795;Muggia;TS;Friuli-Venezia Giulia;032003;34015 +D324;San Dorligo della Valle;TS;Friuli-Venezia Giulia;032004;34018 +I715;Sgonico;TS;Friuli-Venezia Giulia;032005;34010 +L424;Trieste;TS;Friuli-Venezia Giulia;032006;34100,34121-34151 +A067;Agazzano;PC;Emilia-Romagna;033001;29010 +A223;Alseno;PC;Emilia-Romagna;033002;29010 +A823;Besenzone;PC;Emilia-Romagna;033003;29010 +A831;Bettola;PC;Emilia-Romagna;033004;29021 +A909;Bobbio;PC;Emilia-Romagna;033005;29022 +B025;Borgonovo Val Tidone;PC;Emilia-Romagna;033006;29011 +B332;Cadeo;PC;Emilia-Romagna;033007;29010 +B405;Calendasco;PC;Emilia-Romagna;033008;29010 +B643;Caorso;PC;Emilia-Romagna;033010;29012 +B812;Carpaneto Piacentino;PC;Emilia-Romagna;033011;29013 +C145;Castell'Arquato;PC;Emilia-Romagna;033012;29014 +C261;Castel San Giovanni;PC;Emilia-Romagna;033013;29015 +C288;Castelvetro Piacentino;PC;Emilia-Romagna;033014;29010 +C513;Cerignale;PC;Emilia-Romagna;033015;29020 +C838;Coli;PC;Emilia-Romagna;033016;29020 +D054;Corte Brugnatella;PC;Emilia-Romagna;033017;29020 +D061;Cortemaggiore;PC;Emilia-Romagna;033018;29016 +D502;Farini;PC;Emilia-Romagna;033019;29023 +D555;Ferriere;PC;Emilia-Romagna;033020;29024 +D611;Fiorenzuola d'Arda;PC;Emilia-Romagna;033021;29017 +D958;Gazzola;PC;Emilia-Romagna;033022;29010 +E114;Gossolengo;PC;Emilia-Romagna;033023;29020 +E132;Gragnano Trebbiense;PC;Emilia-Romagna;033024;29010 +E196;Gropparello;PC;Emilia-Romagna;033025;29025 +E726;Lugagnano Val d'Arda;PC;Emilia-Romagna;033026;29018 +F671;Monticelli d'Ongina;PC;Emilia-Romagna;033027;29010 +F724;Morfasso;PC;Emilia-Romagna;033028;29020 +G195;Ottone;PC;Emilia-Romagna;033030;29026 +G535;Piacenza;PC;Emilia-Romagna;033032;29100,29121-29122 +G557;Pianello Val Tidone;PC;Emilia-Romagna;033033;29010 +G696;Piozzano;PC;Emilia-Romagna;033034;29010 +G747;Podenzano;PC;Emilia-Romagna;033035;29027 +G842;Ponte dell'Olio;PC;Emilia-Romagna;033036;29028 +G852;Pontenure;PC;Emilia-Romagna;033037;29010 +H350;Rivergaro;PC;Emilia-Romagna;033038;29029 +H593;Rottofreno;PC;Emilia-Romagna;033039;29010 +H887;San Giorgio Piacentino;PC;Emilia-Romagna;033040;29019 +G788;San Pietro in Cerro;PC;Emilia-Romagna;033041;29010 +I434;Sarmato;PC;Emilia-Romagna;033042;29010 +L348;Travo;PC;Emilia-Romagna;033043;29020 +L772;Vernasca;PC;Emilia-Romagna;033044;29010 +L897;Vigolzone;PC;Emilia-Romagna;033045;29020 +L980;Villanova sull'Arda;PC;Emilia-Romagna;033046;29010 +M165;Zerba;PC;Emilia-Romagna;033047;29020 +L848;Ziano Piacentino;PC;Emilia-Romagna;033048;29010 +M386;Alta Val Tidone;PC;Emilia-Romagna;033049; +A138;Albareto;PR;Emilia-Romagna;034001;43051 +A646;Bardi;PR;Emilia-Romagna;034002;43032 +A731;Bedonia;PR;Emilia-Romagna;034003;43041 +A788;Berceto;PR;Emilia-Romagna;034004;43042 +A987;Bore;PR;Emilia-Romagna;034005;43030 +B042;Borgo Val di Taro;PR;Emilia-Romagna;034006;43043 +B293;Busseto;PR;Emilia-Romagna;034007;43011 +B408;Calestano;PR;Emilia-Romagna;034008;43030 +C852;Collecchio;PR;Emilia-Romagna;034009;43044 +C904;Colorno;PR;Emilia-Romagna;034010;43052 +C934;Compiano;PR;Emilia-Romagna;034011;43053 +D026;Corniglio;PR;Emilia-Romagna;034012;43021 +D526;Felino;PR;Emilia-Romagna;034013;43035 +B034;Fidenza;PR;Emilia-Romagna;034014;43036 +D673;Fontanellato;PR;Emilia-Romagna;034015;43012 +D685;Fontevivo;PR;Emilia-Romagna;034016;43010 +D728;Fornovo di Taro;PR;Emilia-Romagna;034017;43045 +E438;Langhirano;PR;Emilia-Romagna;034018;43013 +E547;Lesignano de' Bagni;PR;Emilia-Romagna;034019;43037 +F082;Medesano;PR;Emilia-Romagna;034020;43014 +F340;Monchio delle Corti;PR;Emilia-Romagna;034022;43010 +F473;Montechiarugolo;PR;Emilia-Romagna;034023;43022 +F882;Neviano degli Arduini;PR;Emilia-Romagna;034024;43024 +F914;Noceto;PR;Emilia-Romagna;034025;43015 +G255;Palanzano;PR;Emilia-Romagna;034026;43025 +G337;Parma;PR;Emilia-Romagna;034027;43100,43121-43126,43216 +G424;Pellegrino Parmense;PR;Emilia-Romagna;034028;43047 +H384;Roccabianca;PR;Emilia-Romagna;034030;43010 +H682;Sala Baganza;PR;Emilia-Romagna;034031;43038 +H720;Salsomaggiore Terme;PR;Emilia-Romagna;034032;43039 +I153;San Secondo Parmense;PR;Emilia-Romagna;034033;43017 +I803;Solignano;PR;Emilia-Romagna;034035;43040 +I840;Soragna;PR;Emilia-Romagna;034036;43019 +E548;Terenzo;PR;Emilia-Romagna;034038;43040 +L183;Tizzano Val Parma;PR;Emilia-Romagna;034039;43028 +L229;Tornolo;PR;Emilia-Romagna;034040;43059 +L299;Torrile;PR;Emilia-Romagna;034041;43056 +L346;Traversetolo;PR;Emilia-Romagna;034042;43029 +L641;Valmozzola;PR;Emilia-Romagna;034044;43050 +L672;Varano de' Melegari;PR;Emilia-Romagna;034045;43040 +L689;Varsi;PR;Emilia-Romagna;034046;43049 +M325;Sissa Trecasali;PR;Emilia-Romagna;034049;43018 +M367;Polesine Zibello;PR;Emilia-Romagna;034050; +M411;Sorbolo Mezzani;PR;Emilia-Romagna;034051; +A162;Albinea;RE;Emilia-Romagna;035001;42020 +A573;Bagnolo in Piano;RE;Emilia-Romagna;035002;42011 +A586;Baiso;RE;Emilia-Romagna;035003;42031 +A850;Bibbiano;RE;Emilia-Romagna;035004;42021 +A988;Boretto;RE;Emilia-Romagna;035005;42022 +B156;Brescello;RE;Emilia-Romagna;035006;42041 +B328;Cadelbosco di Sopra;RE;Emilia-Romagna;035008;42023 +B499;Campagnola Emilia;RE;Emilia-Romagna;035009;42012 +B502;Campegine;RE;Emilia-Romagna;035010;42040 +B825;Carpineti;RE;Emilia-Romagna;035011;42033 +B893;Casalgrande;RE;Emilia-Romagna;035012;42013 +B967;Casina;RE;Emilia-Romagna;035013;42034 +C141;Castellarano;RE;Emilia-Romagna;035014;42014 +C218;Castelnovo di Sotto;RE;Emilia-Romagna;035015;42024 +C219;Castelnovo ne' Monti;RE;Emilia-Romagna;035016;42035 +C405;Cavriago;RE;Emilia-Romagna;035017;42025 +C669;Canossa;RE;Emilia-Romagna;035018;42026 +D037;Correggio;RE;Emilia-Romagna;035020;42015 +D450;Fabbrico;RE;Emilia-Romagna;035021;42042 +D934;Gattatico;RE;Emilia-Romagna;035022;42043 +E232;Gualtieri;RE;Emilia-Romagna;035023;42044 +E253;Guastalla;RE;Emilia-Romagna;035024;42016 +E772;Luzzara;RE;Emilia-Romagna;035026;42045 +F463;Montecchio Emilia;RE;Emilia-Romagna;035027;42027 +F960;Novellara;RE;Emilia-Romagna;035028;42017 +G947;Poviglio;RE;Emilia-Romagna;035029;42028 +H122;Quattro Castella;RE;Emilia-Romagna;035030;42020 +H225;Reggiolo;RE;Emilia-Romagna;035032;42046 +H223;Reggio nell'Emilia;RE;Emilia-Romagna;035033; +H298;Rio Saliceto;RE;Emilia-Romagna;035034;42010 +H500;Rolo;RE;Emilia-Romagna;035035;42047 +H628;Rubiera;RE;Emilia-Romagna;035036;42048 +I011;San Martino in Rio;RE;Emilia-Romagna;035037;42018 +I123;San Polo d'Enza;RE;Emilia-Romagna;035038;42020 +I342;Sant'Ilario d'Enza;RE;Emilia-Romagna;035039;42049 +I496;Scandiano;RE;Emilia-Romagna;035040;42019 +L184;Toano;RE;Emilia-Romagna;035041;42010 +L815;Vetto;RE;Emilia-Romagna;035042;42020 +L820;Vezzano sul Crostolo;RE;Emilia-Romagna;035043;42030 +L831;Viano;RE;Emilia-Romagna;035044;42030 +L969;Villa Minozzo;RE;Emilia-Romagna;035045;42030 +M364;Ventasso;RE;Emilia-Romagna;035046; +A713;Bastiglia;MO;Emilia-Romagna;036001;41030 +A959;Bomporto;MO;Emilia-Romagna;036002;41030 +B539;Campogalliano;MO;Emilia-Romagna;036003;41011 +B566;Camposanto;MO;Emilia-Romagna;036004;41031 +B819;Carpi;MO;Emilia-Romagna;036005;41012 +C107;Castelfranco Emilia;MO;Emilia-Romagna;036006;41013 +C242;Castelnuovo Rangone;MO;Emilia-Romagna;036007;41051 +C287;Castelvetro di Modena;MO;Emilia-Romagna;036008;41014 +C398;Cavezzo;MO;Emilia-Romagna;036009;41032 +C951;Concordia sulla Secchia;MO;Emilia-Romagna;036010;41033 +D486;Fanano;MO;Emilia-Romagna;036011;41021 +D599;Finale Emilia;MO;Emilia-Romagna;036012;41034 +D607;Fiorano Modenese;MO;Emilia-Romagna;036013;41042 +D617;Fiumalbo;MO;Emilia-Romagna;036014;41022 +D711;Formigine;MO;Emilia-Romagna;036015;41043 +D783;Frassinoro;MO;Emilia-Romagna;036016;41044 +E264;Guiglia;MO;Emilia-Romagna;036017;41052 +E426;Lama Mocogno;MO;Emilia-Romagna;036018;41023 +E904;Maranello;MO;Emilia-Romagna;036019;41053 +E905;Marano sul Panaro;MO;Emilia-Romagna;036020;41054 +F087;Medolla;MO;Emilia-Romagna;036021;41036 +F240;Mirandola;MO;Emilia-Romagna;036022;41037 +F257;Modena;MO;Emilia-Romagna;036023;41100,41121-41122,41124-41127 +F484;Montecreto;MO;Emilia-Romagna;036024;41025 +F503;Montefiorino;MO;Emilia-Romagna;036025;41045 +F642;Montese;MO;Emilia-Romagna;036026;41055 +F930;Nonantola;MO;Emilia-Romagna;036027;41015 +F966;Novi di Modena;MO;Emilia-Romagna;036028;41016 +G250;Palagano;MO;Emilia-Romagna;036029;41046 +G393;Pavullo nel Frignano;MO;Emilia-Romagna;036030;41026 +G649;Pievepelago;MO;Emilia-Romagna;036031;41027 +G789;Polinago;MO;Emilia-Romagna;036032;41040 +H061;Prignano sulla Secchia;MO;Emilia-Romagna;036033;41048 +H195;Ravarino;MO;Emilia-Romagna;036034;41017 +H303;Riolunato;MO;Emilia-Romagna;036035;41020 +H794;San Cesario sul Panaro;MO;Emilia-Romagna;036036;41018 +H835;San Felice sul Panaro;MO;Emilia-Romagna;036037;41038 +I128;San Possidonio;MO;Emilia-Romagna;036038;41039 +I133;San Prospero;MO;Emilia-Romagna;036039;41030 +I462;Sassuolo;MO;Emilia-Romagna;036040;41049 +I473;Savignano sul Panaro;MO;Emilia-Romagna;036041;41056 +F357;Serramazzoni;MO;Emilia-Romagna;036042;41028 +I689;Sestola;MO;Emilia-Romagna;036043;41029 +I802;Soliera;MO;Emilia-Romagna;036044;41019 +I903;Spilamberto;MO;Emilia-Romagna;036045;41057 +L885;Vignola;MO;Emilia-Romagna;036046;41058 +M183;Zocca;MO;Emilia-Romagna;036047;41059 +A324;Anzola dell'Emilia;BO;Emilia-Romagna;037001;40011 +A392;Argelato;BO;Emilia-Romagna;037002;40050 +A665;Baricella;BO;Emilia-Romagna;037003;40052 +A785;Bentivoglio;BO;Emilia-Romagna;037005;40010 +A944;Bologna;BO;Emilia-Romagna;037006;40100,40121-40129,40131-40139,40141 +B044;Borgo Tossignano;BO;Emilia-Romagna;037007;40021 +B249;Budrio;BO;Emilia-Romagna;037008;40054 +B399;Calderara di Reno;BO;Emilia-Romagna;037009;40012 +B572;Camugnano;BO;Emilia-Romagna;037010;40032 +B880;Casalecchio di Reno;BO;Emilia-Romagna;037011;40033 +B892;Casalfiumanese;BO;Emilia-Romagna;037012;40020 +C075;Castel d'Aiano;BO;Emilia-Romagna;037013;40034 +C086;Castel del Rio;BO;Emilia-Romagna;037014;40022 +B969;Castel di Casio;BO;Emilia-Romagna;037015;40030 +C121;Castel Guelfo di Bologna;BO;Emilia-Romagna;037016;40023 +C185;Castello d'Argile;BO;Emilia-Romagna;037017;40050 +C204;Castel Maggiore;BO;Emilia-Romagna;037019;40013 +C265;Castel San Pietro Terme;BO;Emilia-Romagna;037020;40024 +C292;Castenaso;BO;Emilia-Romagna;037021;40055 +C296;Castiglione dei Pepoli;BO;Emilia-Romagna;037022;40035 +D166;Crevalcore;BO;Emilia-Romagna;037024;40014 +D360;Dozza;BO;Emilia-Romagna;037025;40060 +D668;Fontanelice;BO;Emilia-Romagna;037026;40025 +D847;Gaggio Montano;BO;Emilia-Romagna;037027;40041 +D878;Galliera;BO;Emilia-Romagna;037028;40015 +E136;Granarolo dell'Emilia;BO;Emilia-Romagna;037030;40057 +E187;Grizzana Morandi;BO;Emilia-Romagna;037031;40030 +E289;Imola;BO;Emilia-Romagna;037032;40026 +A771;Lizzano in Belvedere;BO;Emilia-Romagna;037033;40042 +E655;Loiano;BO;Emilia-Romagna;037034;40050 +E844;Malalbergo;BO;Emilia-Romagna;037035;40051 +B689;Marzabotto;BO;Emilia-Romagna;037036;40043 +F083;Medicina;BO;Emilia-Romagna;037037;40059 +F219;Minerbio;BO;Emilia-Romagna;037038;40061 +F288;Molinella;BO;Emilia-Romagna;037039;40062 +F363;Monghidoro;BO;Emilia-Romagna;037040;40063 +F597;Monterenzio;BO;Emilia-Romagna;037041;40050 +F627;Monte San Pietro;BO;Emilia-Romagna;037042;40050 +F706;Monzuno;BO;Emilia-Romagna;037044;40036 +F718;Mordano;BO;Emilia-Romagna;037045;40027 +G205;Ozzano dell'Emilia;BO;Emilia-Romagna;037046;40064 +G570;Pianoro;BO;Emilia-Romagna;037047;40065 +G643;Pieve di Cento;BO;Emilia-Romagna;037048;40066 +H678;Sala Bolognese;BO;Emilia-Romagna;037050;40010 +G566;San Benedetto Val di Sambro;BO;Emilia-Romagna;037051;40048 +H896;San Giorgio di Piano;BO;Emilia-Romagna;037052;40016 +G467;San Giovanni in Persiceto;BO;Emilia-Romagna;037053;40017 +H945;San Lazzaro di Savena;BO;Emilia-Romagna;037054;40068 +I110;San Pietro in Casale;BO;Emilia-Romagna;037055;40018 +I191;Sant'Agata Bolognese;BO;Emilia-Romagna;037056;40019 +G972;Sasso Marconi;BO;Emilia-Romagna;037057;40037 +L762;Vergato;BO;Emilia-Romagna;037059;40038 +M185;Zola Predosa;BO;Emilia-Romagna;037060;40069 +M320;Valsamoggia;BO;Emilia-Romagna;037061;40053 +M369;Alto Reno Terme;BO;Emilia-Romagna;037062; +A393;Argenta;FE;Emilia-Romagna;038001;44011 +A965;Bondeno;FE;Emilia-Romagna;038003;44012 +C469;Cento;FE;Emilia-Romagna;038004;44042 +C814;Codigoro;FE;Emilia-Romagna;038005;44021 +C912;Comacchio;FE;Emilia-Romagna;038006;44022 +C980;Copparo;FE;Emilia-Romagna;038007;44034 +D548;Ferrara;FE;Emilia-Romagna;038008;44121-44124 +E320;Jolanda di Savoia;FE;Emilia-Romagna;038010;44037 +E410;Lagosanto;FE;Emilia-Romagna;038011;44023 +F016;Masi Torello;FE;Emilia-Romagna;038012;44020 +F156;Mesola;FE;Emilia-Romagna;038014;44026 +G184;Ostellato;FE;Emilia-Romagna;038017;44020 +G768;Poggio Renatico;FE;Emilia-Romagna;038018;44028 +G916;Portomaggiore;FE;Emilia-Romagna;038019;44015 +L868;Vigarano Mainarda;FE;Emilia-Romagna;038022;44049 +M110;Voghiera;FE;Emilia-Romagna;038023;44019 +E107;Goro;FE;Emilia-Romagna;038025;44020 +M323;Fiscaglia;FE;Emilia-Romagna;038027;44027 +M381;Terre del Reno;FE;Emilia-Romagna;038028; +M410;Riva del Po;FE;Emilia-Romagna;038029; +M409;Tresignana;FE;Emilia-Romagna;038030; +A191;Alfonsine;RA;Emilia-Romagna;039001;48011 +A547;Bagnacavallo;RA;Emilia-Romagna;039002;48012 +A551;Bagnara di Romagna;RA;Emilia-Romagna;039003;48031 +B188;Brisighella;RA;Emilia-Romagna;039004;48013 +B982;Casola Valsenio;RA;Emilia-Romagna;039005;48032 +C065;Castel Bolognese;RA;Emilia-Romagna;039006;48014 +C553;Cervia;RA;Emilia-Romagna;039007;48015 +C963;Conselice;RA;Emilia-Romagna;039008;48017 +D121;Cotignola;RA;Emilia-Romagna;039009;48033 +D458;Faenza;RA;Emilia-Romagna;039010;48018 +D829;Fusignano;RA;Emilia-Romagna;039011;48034 +E730;Lugo;RA;Emilia-Romagna;039012;48022 +F029;Massa Lombarda;RA;Emilia-Romagna;039013;48024 +H199;Ravenna;RA;Emilia-Romagna;039014;48100 +H302;Riolo Terme;RA;Emilia-Romagna;039015;48025 +H642;Russi;RA;Emilia-Romagna;039016;48026 +I196;Sant'Agata sul Santerno;RA;Emilia-Romagna;039017;48020 +I787;Solarolo;RA;Emilia-Romagna;039018;48027 +A565;Bagno di Romagna;FC;Emilia-Romagna;040001;47021 +A809;Bertinoro;FC;Emilia-Romagna;040003;47032 +B001;Borghi;FC;Emilia-Romagna;040004;47030 +C339;Castrocaro Terme e Terra del Sole;FC;Emilia-Romagna;040005;47011 +C573;Cesena;FC;Emilia-Romagna;040007;47023 +C574;Cesenatico;FC;Emilia-Romagna;040008;47042 +C777;Civitella di Romagna;FC;Emilia-Romagna;040009;47012 +D357;Dovadola;FC;Emilia-Romagna;040011;47013 +D704;Forlì;FC;Emilia-Romagna;040012;47121-47122 +D705;Forlimpopoli;FC;Emilia-Romagna;040013;47034 +D867;Galeata;FC;Emilia-Romagna;040014;47010 +D899;Gambettola;FC;Emilia-Romagna;040015;47035 +D935;Gatteo;FC;Emilia-Romagna;040016;47043 +E675;Longiano;FC;Emilia-Romagna;040018;47020 +F097;Meldola;FC;Emilia-Romagna;040019;47014 +F139;Mercato Saraceno;FC;Emilia-Romagna;040020;47025 +F259;Modigliana;FC;Emilia-Romagna;040022;47015 +F668;Montiano;FC;Emilia-Romagna;040028;47020 +G904;Portico e San Benedetto;FC;Emilia-Romagna;040031;47010 +H017;Predappio;FC;Emilia-Romagna;040032;47016 +H034;Premilcuore;FC;Emilia-Romagna;040033;47010 +H437;Rocca San Casciano;FC;Emilia-Romagna;040036;47017 +H542;Roncofreddo;FC;Emilia-Romagna;040037;47020 +I027;San Mauro Pascoli;FC;Emilia-Romagna;040041;47030 +I310;Santa Sofia;FC;Emilia-Romagna;040043;47018 +I444;Sarsina;FC;Emilia-Romagna;040044;47027 +I472;Savignano sul Rubicone;FC;Emilia-Romagna;040045;47039 +I779;Sogliano al Rubicone;FC;Emilia-Romagna;040046;47030 +L361;Tredozio;FC;Emilia-Romagna;040049;47019 +L764;Verghereto;FC;Emilia-Romagna;040050;47028 +A035;Acqualagna;PU;Marche;041001;61041 +A327;Apecchio;PU;Marche;041002;61042 +A740;Belforte all'Isauro;PU;Marche;041005;61026 +B026;Borgo Pace;PU;Marche;041006;61040 +B352;Cagli;PU;Marche;041007;61043 +B636;Cantiano;PU;Marche;041008;61044 +B816;Carpegna;PU;Marche;041009;61021 +B846;Cartoceto;PU;Marche;041010;61030 +D488;Fano;PU;Marche;041013;61032 +D541;Fermignano;PU;Marche;041014;61033 +D749;Fossombrone;PU;Marche;041015;61034 +D791;Fratte Rosa;PU;Marche;041016;61040 +D807;Frontino;PU;Marche;041017;61021 +D808;Frontone;PU;Marche;041018;61040 +D836;Gabicce Mare;PU;Marche;041019;61011 +E122;Gradara;PU;Marche;041020;61012 +E351;Isola del Piano;PU;Marche;041021;61030 +E743;Lunano;PU;Marche;041022;61026 +E785;Macerata Feltria;PU;Marche;041023;61023 +F135;Mercatello sul Metauro;PU;Marche;041025;61040 +F136;Mercatino Conca;PU;Marche;041026;61013 +F310;Mombaroccio;PU;Marche;041027;61024 +F347;Mondavio;PU;Marche;041028;61040 +F348;Mondolfo;PU;Marche;041029;61037 +F450;Montecalvo in Foglia;PU;Marche;041030;61020 +F467;Monte Cerignone;PU;Marche;041031;61010 +F497;Montefelcino;PU;Marche;041034;61030 +F524;Monte Grimano Terme;PU;Marche;041035; +F533;Montelabbate;PU;Marche;041036;61025 +F589;Monte Porzio;PU;Marche;041038;61040 +G416;Peglio;PU;Marche;041041; +G453;Pergola;PU;Marche;041043;61045 +G479;Pesaro;PU;Marche;041044;61100,61121-61122 +G514;Petriano;PU;Marche;041045;61020 +G551;Piandimeleto;PU;Marche;041047;61026 +G627;Pietrarubbia;PU;Marche;041048;61023 +G682;Piobbico;PU;Marche;041049;61046 +H809;San Costanzo;PU;Marche;041051;61039 +H958;San Lorenzo in Campo;PU;Marche;041054;61047 +I287;Sant'Angelo in Vado;PU;Marche;041057;61048 +I344;Sant'Ippolito;PU;Marche;041058;61040 +I654;Serra Sant'Abbondio;PU;Marche;041061;61040 +L078;Tavoleto;PU;Marche;041064;61020 +L081;Tavullia;PU;Marche;041065;61010 +L498;Urbania;PU;Marche;041066;61049 +L500;Urbino;PU;Marche;041067;61029 +M331;Vallefoglia;PU;Marche;041068;61022 +M380;Colli al Metauro;PU;Marche;041069; +M379;Terre Roveresche;PU;Marche;041070; +M413;Sassocorvaro Auditore;PU;Marche;041071; +A092;Agugliano;AN;Marche;042001;60020 +A271;Ancona;AN;Marche;042002;60100,60121-60129,60131 +A366;Arcevia;AN;Marche;042003;60011 +A626;Barbara;AN;Marche;042004;60010 +A769;Belvedere Ostrense;AN;Marche;042005;60030 +B468;Camerano;AN;Marche;042006;60021 +B470;Camerata Picena;AN;Marche;042007;60020 +C060;Castelbellino;AN;Marche;042008;60030 +C100;Castelfidardo;AN;Marche;042010;60022 +C152;Castelleone di Suasa;AN;Marche;042011;60010 +C248;Castelplanio;AN;Marche;042012;60031 +C524;Cerreto d'Esi;AN;Marche;042013;60043 +C615;Chiaravalle;AN;Marche;042014;60033 +D007;Corinaldo;AN;Marche;042015;60013 +D211;Cupramontana;AN;Marche;042016;60034 +D451;Fabriano;AN;Marche;042017;60044 +D472;Falconara Marittima;AN;Marche;042018;60015 +D597;Filottrano;AN;Marche;042019;60024 +D965;Genga;AN;Marche;042020;60040 +E388;Jesi;AN;Marche;042021;60035 +E690;Loreto;AN;Marche;042022;60025 +E837;Maiolati Spontini;AN;Marche;042023;60030 +F145;Mergo;AN;Marche;042024;60030 +F381;Monsano;AN;Marche;042025;60030 +F453;Montecarotto;AN;Marche;042026;60036 +F560;Montemarciano;AN;Marche;042027;60018 +F600;Monte Roberto;AN;Marche;042029;60030 +F634;Monte San Vito;AN;Marche;042030;60037 +F745;Morro d'Alba;AN;Marche;042031;60030 +F978;Numana;AN;Marche;042032;60026 +G003;Offagna;AN;Marche;042033;60020 +G157;Osimo;AN;Marche;042034;60027 +F401;Ostra;AN;Marche;042035;60010 +F581;Ostra Vetere;AN;Marche;042036;60010 +G771;Poggio San Marcello;AN;Marche;042037;60030 +G803;Polverigi;AN;Marche;042038;60020 +H575;Rosora;AN;Marche;042040;60030 +H979;San Marcello;AN;Marche;042041;60030 +I071;San Paolo di Jesi;AN;Marche;042042;60038 +I251;Santa Maria Nuova;AN;Marche;042043;60030 +I461;Sassoferrato;AN;Marche;042044;60041 +I608;Senigallia;AN;Marche;042045;60019 +I643;Serra de' Conti;AN;Marche;042046;60030 +I653;Serra San Quirico;AN;Marche;042047;60048 +I758;Sirolo;AN;Marche;042048;60020 +I932;Staffolo;AN;Marche;042049;60039 +M318;Trecastelli;AN;Marche;042050;60012 +A329;Apiro;MC;Marche;043002;62021 +A334;Appignano;MC;Marche;043003;62010 +A739;Belforte del Chienti;MC;Marche;043004;62020 +A947;Bolognola;MC;Marche;043005;62035 +B398;Caldarola;MC;Marche;043006;62020 +B474;Camerino;MC;Marche;043007;62032 +B562;Camporotondo di Fiastrone;MC;Marche;043008;62020 +C251;Castelraimondo;MC;Marche;043009;62022 +C267;Castelsantangelo sul Nera;MC;Marche;043010;62039 +C582;Cessapalombo;MC;Marche;043011;62020 +C704;Cingoli;MC;Marche;043012;62011 +C770;Civitanova Marche;MC;Marche;043013;62012 +C886;Colmurano;MC;Marche;043014;62020 +D042;Corridonia;MC;Marche;043015;62014 +D429;Esanatoglia;MC;Marche;043016;62024 +D564;Fiastra;MC;Marche;043017;62035 +D628;Fiuminata;MC;Marche;043019;62025 +D853;Gagliole;MC;Marche;043020;62022 +E228;Gualdo;MC;Marche;043021;62020 +E694;Loro Piceno;MC;Marche;043022;62020 +E783;Macerata;MC;Marche;043023;62100 +F051;Matelica;MC;Marche;043024;62024 +F268;Mogliano;MC;Marche;043025;62010 +F454;Montecassiano;MC;Marche;043026;62010 +F460;Monte Cavallo;MC;Marche;043027;62036 +F482;Montecosaro;MC;Marche;043028;62010 +F496;Montefano;MC;Marche;043029;62010 +F552;Montelupone;MC;Marche;043030;62010 +F621;Monte San Giusto;MC;Marche;043031;62015 +F622;Monte San Martino;MC;Marche;043032;62020 +F749;Morrovalle;MC;Marche;043033;62010 +F793;Muccia;MC;Marche;043034;62034 +G436;Penna San Giovanni;MC;Marche;043035;62020 +G515;Petriolo;MC;Marche;043036;62014 +G657;Pieve Torina;MC;Marche;043038;62036 +G690;Pioraco;MC;Marche;043039;62025 +D566;Poggio San Vicino;MC;Marche;043040;62021 +F567;Pollenza;MC;Marche;043041;62010 +G919;Porto Recanati;MC;Marche;043042;62017 +F632;Potenza Picena;MC;Marche;043043;62018 +H211;Recanati;MC;Marche;043044;62019 +H323;Ripe San Ginesio;MC;Marche;043045;62020 +H876;San Ginesio;MC;Marche;043046;62026 +I156;San Severino Marche;MC;Marche;043047;62027 +I286;Sant'Angelo in Pontano;MC;Marche;043048;62020 +I436;Sarnano;MC;Marche;043049;62028 +I569;Sefro;MC;Marche;043050;62025 +I651;Serrapetrona;MC;Marche;043051;62020 +I661;Serravalle di Chienti;MC;Marche;043052;62038 +L191;Tolentino;MC;Marche;043053;62029 +L366;Treia;MC;Marche;043054;62010 +L501;Urbisaglia;MC;Marche;043055;62010 +L517;Ussita;MC;Marche;043056;62039 +M078;Visso;MC;Marche;043057;62039 +M382;Valfornace;MC;Marche;043058; +A044;Acquasanta Terme;AP;Marche;044001;63095 +A047;Acquaviva Picena;AP;Marche;044002;63075 +A335;Appignano del Tronto;AP;Marche;044005;63083 +A437;Arquata del Tronto;AP;Marche;044006;63096 +A462;Ascoli Piceno;AP;Marche;044007;63100 +B727;Carassai;AP;Marche;044010;63063 +C093;Castel di Lama;AP;Marche;044011;63082 +C321;Castignano;AP;Marche;044012;63072 +C331;Castorano;AP;Marche;044013;63081 +C877;Colli del Tronto;AP;Marche;044014;63079 +C935;Comunanza;AP;Marche;044015;63087 +D096;Cossignano;AP;Marche;044016;63067 +D210;Cupra Marittima;AP;Marche;044017;63064 +D652;Folignano;AP;Marche;044020;63084 +D691;Force;AP;Marche;044021;63086 +E207;Grottammare;AP;Marche;044023;63066 +E868;Maltignano;AP;Marche;044027;63085 +F044;Massignano;AP;Marche;044029;63061 +F380;Monsampolo del Tronto;AP;Marche;044031;63077 +F415;Montalto delle Marche;AP;Marche;044032;63068 +F487;Montedinove;AP;Marche;044034;63069 +F501;Montefiore dell'Aso;AP;Marche;044036;63062 +F516;Montegallo;AP;Marche;044038;63094 +F570;Montemonaco;AP;Marche;044044;63088 +F591;Monteprandone;AP;Marche;044045;63076 +G005;Offida;AP;Marche;044054;63073 +G289;Palmiano;AP;Marche;044056;63092 +H321;Ripatransone;AP;Marche;044063;63065 +H390;Roccafluvione;AP;Marche;044064;63093 +H588;Rotella;AP;Marche;044065;63071 +H769;San Benedetto del Tronto;AP;Marche;044066;63074 +I912;Spinetoli;AP;Marche;044071;63078 +L728;Venarotta;AP;Marche;044073;63091 +A496;Aulla;MS;Toscana;045001;54011 +A576;Bagnone;MS;Toscana;045002;54021 +B832;Carrara;MS;Toscana;045003;54033 +B979;Casola in Lunigiana;MS;Toscana;045004;54014 +C914;Comano;MS;Toscana;045005;54015 +D590;Filattiera;MS;Toscana;045006;54023 +D629;Fivizzano;MS;Toscana;045007;54013 +D735;Fosdinovo;MS;Toscana;045008;54035 +E574;Licciana Nardi;MS;Toscana;045009;54016 +F023;Massa;MS;Toscana;045010;54100 +F679;Montignoso;MS;Toscana;045011;54038 +F802;Mulazzo;MS;Toscana;045012;54026 +G746;Podenzana;MS;Toscana;045013;54010 +G870;Pontremoli;MS;Toscana;045014;54027 +L386;Tresana;MS;Toscana;045015;54012 +L946;Villafranca in Lunigiana;MS;Toscana;045016;54028 +M169;Zeri;MS;Toscana;045017;54029 +A241;Altopascio;LU;Toscana;046001;55011 +A560;Bagni di Lucca;LU;Toscana;046002;55022 +A657;Barga;LU;Toscana;046003;55051 +B007;Borgo a Mozzano;LU;Toscana;046004;55023 +B455;Camaiore;LU;Toscana;046005;55041 +B557;Camporgiano;LU;Toscana;046006;55031 +B648;Capannori;LU;Toscana;046007;55012 +B760;Careggine;LU;Toscana;046008;55030 +C236;Castelnuovo di Garfagnana;LU;Toscana;046009;55032 +C303;Castiglione di Garfagnana;LU;Toscana;046010;55033 +C996;Coreglia Antelminelli;LU;Toscana;046011;55025 +D730;Forte dei Marmi;LU;Toscana;046013;55042 +D734;Fosciandora;LU;Toscana;046014;55020 +D874;Gallicano;LU;Toscana;046015;55027 +E715;Lucca;LU;Toscana;046017;55100 +F035;Massarosa;LU;Toscana;046018;55054 +F225;Minucciano;LU;Toscana;046019;55034 +F283;Molazzana;LU;Toscana;046020;55020 +F452;Montecarlo;LU;Toscana;046021;55015 +G480;Pescaglia;LU;Toscana;046022;55064 +G582;Piazza al Serchio;LU;Toscana;046023;55035 +G628;Pietrasanta;LU;Toscana;046024;55045 +G648;Pieve Fosciana;LU;Toscana;046025;55036 +G882;Porcari;LU;Toscana;046026;55016 +I142;San Romano in Garfagnana;LU;Toscana;046027;55038 +I622;Seravezza;LU;Toscana;046028;55047 +I942;Stazzema;LU;Toscana;046030;55040 +L533;Vagli Sotto;LU;Toscana;046031;55030 +L833;Viareggio;LU;Toscana;046033;55049 +L913;Villa Basilica;LU;Toscana;046034;55019 +L926;Villa Collemandina;LU;Toscana;046035;55030 +M319;Fabbriche di Vergemoli;LU;Toscana;046036;55021 +M347;Sillano Giuncugnano;LU;Toscana;046037;55039 +A071;Agliana;PT;Toscana;047002;51031 +B251;Buggiano;PT;Toscana;047003;51011 +E432;Lamporecchio;PT;Toscana;047005;51035 +E451;Larciano;PT;Toscana;047006;51036 +E960;Marliana;PT;Toscana;047007;51010 +F025;Massa e Cozzile;PT;Toscana;047008;51010 +F384;Monsummano Terme;PT;Toscana;047009;51015 +F410;Montale;PT;Toscana;047010;51037 +A561;Montecatini-Terme;PT;Toscana;047011;51016 +G491;Pescia;PT;Toscana;047012;51017 +G636;Pieve a Nievole;PT;Toscana;047013;51018 +G713;Pistoia;PT;Toscana;047014;51100 +G833;Ponte Buggianese;PT;Toscana;047016;51019 +H109;Quarrata;PT;Toscana;047017;51039 +H744;Sambuca Pistoiese;PT;Toscana;047018;51020 +I660;Serravalle Pistoiese;PT;Toscana;047020;51034 +L522;Uzzano;PT;Toscana;047021;51010 +C631;Chiesina Uzzanese;PT;Toscana;047022;51013 +M376;Abetone Cutigliano;PT;Toscana;047023; +M377;San Marcello Piteglio;PT;Toscana;047024; +A564;Bagno a Ripoli;FI;Toscana;048001;50012 +A632;Barberino di Mugello;FI;Toscana;048002;50031 +B036;Borgo San Lorenzo;FI;Toscana;048004;50032 +B406;Calenzano;FI;Toscana;048005;50041 +B507;Campi Bisenzio;FI;Toscana;048006;50013 +B684;Capraia e Limite;FI;Toscana;048008;50050 +C101;Castelfiorentino;FI;Toscana;048010;50051 +C529;Cerreto Guidi;FI;Toscana;048011;50050 +C540;Certaldo;FI;Toscana;048012;50052 +D299;Dicomano;FI;Toscana;048013;50062 +D403;Empoli;FI;Toscana;048014;50053 +D575;Fiesole;FI;Toscana;048015;50014 +D612;Firenze;FI;Toscana;048017;50100,50121-50145 +D613;Firenzuola;FI;Toscana;048018;50033 +D815;Fucecchio;FI;Toscana;048019;50054 +D895;Gambassi Terme;FI;Toscana;048020;50050 +E169;Greve in Chianti;FI;Toscana;048021;50022 +E291;Impruneta;FI;Toscana;048022;50023 +E466;Lastra a Signa;FI;Toscana;048024;50055 +E668;Londa;FI;Toscana;048025;50060 +E971;Marradi;FI;Toscana;048026;50034 +F398;Montaione;FI;Toscana;048027;50050 +F551;Montelupo Fiorentino;FI;Toscana;048028;50056 +F648;Montespertoli;FI;Toscana;048030;50025 +G270;Palazzuolo sul Senio;FI;Toscana;048031;50035 +G420;Pelago;FI;Toscana;048032;50060 +G825;Pontassieve;FI;Toscana;048033;50065 +H222;Reggello;FI;Toscana;048035;50066 +H286;Rignano sull'Arno;FI;Toscana;048036;50067 +H635;Rufina;FI;Toscana;048037;50068 +H791;San Casciano in Val di Pesa;FI;Toscana;048038;50026 +H937;San Godenzo;FI;Toscana;048039;50060 +B962;Scandicci;FI;Toscana;048041;50018 +I684;Sesto Fiorentino;FI;Toscana;048043;50019 +I728;Signa;FI;Toscana;048044;50058 +L529;Vaglia;FI;Toscana;048046;50036 +L838;Vicchio;FI;Toscana;048049;50039 +M059;Vinci;FI;Toscana;048050;50059 +M321;Figline e Incisa Valdarno;FI;Toscana;048052;50063 +M326;Scarperia e San Piero;FI;Toscana;048053;50038 +M408;Barberino Tavarnelle;FI;Toscana;048054; +A852;Bibbona;LI;Toscana;049001;57020 +B509;Campiglia Marittima;LI;Toscana;049002;57021 +B553;Campo nell'Elba;LI;Toscana;049003;57034 +B669;Capoliveri;LI;Toscana;049004;57031 +B685;Capraia Isola;LI;Toscana;049005;57032 +C044;Castagneto Carducci;LI;Toscana;049006;57022 +C415;Cecina;LI;Toscana;049007;57023 +C869;Collesalvetti;LI;Toscana;049008;57014 +E625;Livorno;LI;Toscana;049009;57100,57121-57128 +E930;Marciana;LI;Toscana;049010;57030 +E931;Marciana Marina;LI;Toscana;049011;57033 +G687;Piombino;LI;Toscana;049012;57025 +E680;Porto Azzurro;LI;Toscana;049013;57036 +G912;Portoferraio;LI;Toscana;049014;57037 +H570;Rosignano Marittimo;LI;Toscana;049017;57016 +I390;San Vincenzo;LI;Toscana;049018;57027 +I454;Sassetta;LI;Toscana;049019;57020 +L019;Suvereto;LI;Toscana;049020;57028 +M391;Rio;LI;Toscana;049021; +A864;Bientina;PI;Toscana;050001;56031 +B303;Buti;PI;Toscana;050002;56032 +B390;Calci;PI;Toscana;050003;56011 +B392;Calcinaia;PI;Toscana;050004;56012 +B647;Capannoli;PI;Toscana;050005;56033 +B878;Casale Marittimo;PI;Toscana;050006;56040 +B950;Cascina;PI;Toscana;050008;56021 +C113;Castelfranco di Sotto;PI;Toscana;050009;56022 +C174;Castellina Marittima;PI;Toscana;050010;56040 +C244;Castelnuovo di Val di Cecina;PI;Toscana;050011;56041 +C609;Chianni;PI;Toscana;050012;56034 +D510;Fauglia;PI;Toscana;050014;56043 +E250;Guardistallo;PI;Toscana;050015;56040 +E413;Lajatico;PI;Toscana;050016;56030 +F458;Montecatini Val di Cecina;PI;Toscana;050019;56040 +F640;Montescudaio;PI;Toscana;050020;56040 +F661;Monteverdi Marittimo;PI;Toscana;050021;56040 +F686;Montopoli in Val d'Arno;PI;Toscana;050022;56020 +G090;Orciano Pisano;PI;Toscana;050023;56040 +G254;Palaia;PI;Toscana;050024;56036 +G395;Peccioli;PI;Toscana;050025;56037 +G702;Pisa;PI;Toscana;050026;56100,56121-56128 +G804;Pomarance;PI;Toscana;050027;56045 +G822;Ponsacco;PI;Toscana;050028;56038 +G843;Pontedera;PI;Toscana;050029;56025 +H319;Riparbella;PI;Toscana;050030;56046 +A562;San Giuliano Terme;PI;Toscana;050031;56017 +I046;San Miniato;PI;Toscana;050032;56028 +I177;Santa Croce sull'Arno;PI;Toscana;050033;56029 +I217;Santa Luce;PI;Toscana;050034;56040 +I232;Santa Maria a Monte;PI;Toscana;050035;56020 +L138;Terricciola;PI;Toscana;050036;56030 +L702;Vecchiano;PI;Toscana;050037;56019 +L850;Vicopisano;PI;Toscana;050038;56010 +M126;Volterra;PI;Toscana;050039;56048 +M327;Casciana Terme Lari;PI;Toscana;050040;56035 +M328;Crespina Lorenzana;PI;Toscana;050041;56042 +A291;Anghiari;AR;Toscana;051001;52031 +A390;Arezzo;AR;Toscana;051002;52100 +A541;Badia Tedalda;AR;Toscana;051003;52032 +A851;Bibbiena;AR;Toscana;051004;52011 +B243;Bucine;AR;Toscana;051005;52021 +B670;Capolona;AR;Toscana;051006;52010 +B693;Caprese Michelangelo;AR;Toscana;051007;52033 +C102;Castel Focognano;AR;Toscana;051008;52016 +C263;Castel San Niccolò;AR;Toscana;051010;52018 +C318;Castiglion Fibocchi;AR;Toscana;051011;52029 +C319;Castiglion Fiorentino;AR;Toscana;051012;52043 +C407;Cavriglia;AR;Toscana;051013;52022 +C648;Chitignano;AR;Toscana;051014;52010 +C663;Chiusi della Verna;AR;Toscana;051015;52010 +C774;Civitella in Val di Chiana;AR;Toscana;051016;52041 +D077;Cortona;AR;Toscana;051017;52044 +D649;Foiano della Chiana;AR;Toscana;051018;52045 +E693;Loro Ciuffenna;AR;Toscana;051020;52024 +E718;Lucignano;AR;Toscana;051021;52046 +E933;Marciano della Chiana;AR;Toscana;051022;52047 +F565;Montemignaio;AR;Toscana;051023;52010 +F594;Monterchi;AR;Toscana;051024;52035 +F628;Monte San Savino;AR;Toscana;051025;52048 +F656;Montevarchi;AR;Toscana;051026;52025 +G139;Ortignano Raggiolo;AR;Toscana;051027;52010 +G653;Pieve Santo Stefano;AR;Toscana;051030;52036 +G879;Poppi;AR;Toscana;051031;52014 +H901;San Giovanni Valdarno;AR;Toscana;051033;52027 +I155;Sansepolcro;AR;Toscana;051034;52037 +I681;Sestino;AR;Toscana;051035;52038 +I991;Subbiano;AR;Toscana;051037;52010 +L038;Talla;AR;Toscana;051038;52010 +L123;Terranuova Bracciolini;AR;Toscana;051039;52028 +M322;Castelfranco Piandiscò;AR;Toscana;051040;52026 +M329;Pratovecchio Stia;AR;Toscana;051041;52015 +M392;Laterina Pergine Valdarno;AR;Toscana;051042; +A006;Abbadia San Salvatore;SI;Toscana;052001;53021 +A461;Asciano;SI;Toscana;052002;53041 +B269;Buonconvento;SI;Toscana;052003;53022 +B984;Casole d'Elsa;SI;Toscana;052004;53031 +C172;Castellina in Chianti;SI;Toscana;052005;53011 +C227;Castelnuovo Berardenga;SI;Toscana;052006;53019 +C313;Castiglione d'Orcia;SI;Toscana;052007;53023 +C587;Cetona;SI;Toscana;052008;53040 +C608;Chianciano Terme;SI;Toscana;052009;53042 +C661;Chiusdino;SI;Toscana;052010;53012 +C662;Chiusi;SI;Toscana;052011;53043 +C847;Colle di Val d'Elsa;SI;Toscana;052012;53034 +D858;Gaiole in Chianti;SI;Toscana;052013;53013 +F592;Montepulciano;SI;Toscana;052015;53045 +F598;Monteriggioni;SI;Toscana;052016;53035 +F605;Monteroni d'Arbia;SI;Toscana;052017;53014 +F676;Monticiano;SI;Toscana;052018;53015 +F815;Murlo;SI;Toscana;052019;53016 +G547;Piancastagnaio;SI;Toscana;052020;53025 +G602;Pienza;SI;Toscana;052021;53026 +G752;Poggibonsi;SI;Toscana;052022;53036 +H153;Radda in Chianti;SI;Toscana;052023;53017 +H156;Radicofani;SI;Toscana;052024;53040 +H157;Radicondoli;SI;Toscana;052025;53030 +H185;Rapolano Terme;SI;Toscana;052026;53040 +H790;San Casciano dei Bagni;SI;Toscana;052027;53040 +H875;San Gimignano;SI;Toscana;052028;53037 +I135;San Quirico d'Orcia;SI;Toscana;052030;53027 +I445;Sarteano;SI;Toscana;052031;53047 +I726;Siena;SI;Toscana;052032;53100 +A468;Sinalunga;SI;Toscana;052033;53048 +I877;Sovicille;SI;Toscana;052034;53018 +L303;Torrita di Siena;SI;Toscana;052035;53049 +L384;Trequanda;SI;Toscana;052036;53020 +M378;Montalcino;SI;Toscana;052037;53024 +A369;Arcidosso;GR;Toscana;053001;58031 +B497;Campagnatico;GR;Toscana;053002;58042 +B646;Capalbio;GR;Toscana;053003;58011 +C085;Castel del Piano;GR;Toscana;053004;58033 +C147;Castell'Azzara;GR;Toscana;053005;58034 +C310;Castiglione della Pescaia;GR;Toscana;053006;58043 +C705;Cinigiano;GR;Toscana;053007;58044 +C782;Civitella Paganico;GR;Toscana;053008;58045 +D656;Follonica;GR;Toscana;053009;58022 +D948;Gavorrano;GR;Toscana;053010;58023 +E202;Grosseto;GR;Toscana;053011;58100 +E348;Isola del Giglio;GR;Toscana;053012;58012 +E810;Magliano in Toscana;GR;Toscana;053013;58051 +E875;Manciano;GR;Toscana;053014;58014 +F032;Massa Marittima;GR;Toscana;053015;58024 +F437;Monte Argentario;GR;Toscana;053016;58019 +F677;Montieri;GR;Toscana;053017;58026 +G088;Orbetello;GR;Toscana;053018;58015 +G716;Pitigliano;GR;Toscana;053019;58017 +H417;Roccalbegna;GR;Toscana;053020;58053 +H449;Roccastrada;GR;Toscana;053021;58036 +I187;Santa Fiora;GR;Toscana;053022;58037 +I504;Scansano;GR;Toscana;053023;58054 +I510;Scarlino;GR;Toscana;053024;58020 +I571;Seggiano;GR;Toscana;053025;58038 +I841;Sorano;GR;Toscana;053026;58010 +F612;Monterotondo Marittimo;GR;Toscana;053027;58025 +I601;Semproniano;GR;Toscana;053028;58055 +A475;Assisi;PG;Umbria;054001;06081 +A710;Bastia Umbra;PG;Umbria;054002; +A832;Bettona;PG;Umbria;054003;06084 +A835;Bevagna;PG;Umbria;054004;06031 +B504;Campello sul Clitunno;PG;Umbria;054005;06042 +B609;Cannara;PG;Umbria;054006;06033 +B948;Cascia;PG;Umbria;054007;06043 +C252;Castel Ritaldi;PG;Umbria;054008;06044 +C309;Castiglione del Lago;PG;Umbria;054009;06061 +C527;Cerreto di Spoleto;PG;Umbria;054010;06041 +C742;Citerna;PG;Umbria;054011;06010 +C744;Città della Pieve;PG;Umbria;054012;06062 +C745;Città di Castello;PG;Umbria;054013;06012 +C845;Collazzone;PG;Umbria;054014;06050 +C990;Corciano;PG;Umbria;054015;06073 +D108;Costacciaro;PG;Umbria;054016;06021 +D279;Deruta;PG;Umbria;054017;06053 +D653;Foligno;PG;Umbria;054018;06034 +D745;Fossato di Vico;PG;Umbria;054019;06022 +D787;Fratta Todina;PG;Umbria;054020;06054 +E012;Giano dell'Umbria;PG;Umbria;054021;06030 +E229;Gualdo Cattaneo;PG;Umbria;054022;06035 +E230;Gualdo Tadino;PG;Umbria;054023;06023 +E256;Gubbio;PG;Umbria;054024;06024 +E613;Lisciano Niccone;PG;Umbria;054025;06060 +E805;Magione;PG;Umbria;054026;06063 +E975;Marsciano;PG;Umbria;054027;06055 +F024;Massa Martana;PG;Umbria;054028;06056 +F456;Monte Castello di Vibio;PG;Umbria;054029;06057 +F492;Montefalco;PG;Umbria;054030;06036 +F540;Monteleone di Spoleto;PG;Umbria;054031;06045 +F629;Monte Santa Maria Tiberina;PG;Umbria;054032;06010 +F685;Montone;PG;Umbria;054033;06014 +F911;Nocera Umbra;PG;Umbria;054034;06025 +F935;Norcia;PG;Umbria;054035;06046 +G212;Paciano;PG;Umbria;054036;06060 +G308;Panicale;PG;Umbria;054037;06064 +G359;Passignano sul Trasimeno;PG;Umbria;054038;06065 +G478;Perugia;PG;Umbria;054039;06100,06121-06135 +G601;Piegaro;PG;Umbria;054040;06066 +G618;Pietralunga;PG;Umbria;054041;06026 +G758;Poggiodomo;PG;Umbria;054042;06040 +H015;Preci;PG;Umbria;054043;06047 +H935;San Giustino;PG;Umbria;054044;06016 +I263;Sant'Anatolia di Narco;PG;Umbria;054045;06040 +I522;Scheggia e Pascelupo;PG;Umbria;054046;06027 +I523;Scheggino;PG;Umbria;054047;06040 +I585;Sellano;PG;Umbria;054048;06030 +I727;Sigillo;PG;Umbria;054049;06028 +I888;Spello;PG;Umbria;054050;06038 +I921;Spoleto;PG;Umbria;054051;06049 +L188;Todi;PG;Umbria;054052;06059 +L216;Torgiano;PG;Umbria;054053;06089 +L397;Trevi;PG;Umbria;054054;06039 +L466;Tuoro sul Trasimeno;PG;Umbria;054055;06069 +D786;Umbertide;PG;Umbria;054056;06019 +L573;Valfabbrica;PG;Umbria;054057;06029 +L627;Vallo di Nera;PG;Umbria;054058;06040 +L653;Valtopina;PG;Umbria;054059;06030 +A045;Acquasparta;TR;Umbria;055001;05021 +A207;Allerona;TR;Umbria;055002;05011 +A242;Alviano;TR;Umbria;055003;05020 +A262;Amelia;TR;Umbria;055004;05022 +A439;Arrone;TR;Umbria;055005;05031 +A490;Attigliano;TR;Umbria;055006;05012 +A691;Baschi;TR;Umbria;055007;05023 +B446;Calvi dell'Umbria;TR;Umbria;055008;05032 +C117;Castel Giorgio;TR;Umbria;055009;05013 +C289;Castel Viscardo;TR;Umbria;055010;05014 +D454;Fabro;TR;Umbria;055011;05015 +D538;Ferentillo;TR;Umbria;055012;05034 +D570;Ficulle;TR;Umbria;055013;05016 +E045;Giove;TR;Umbria;055014;05024 +E241;Guardea;TR;Umbria;055015;05025 +E729;Lugnano in Teverina;TR;Umbria;055016;05020 +F457;Montecastrilli;TR;Umbria;055017;05026 +F462;Montecchio;TR;Umbria;055018;05020 +F510;Montefranco;TR;Umbria;055019;05030 +F513;Montegabbione;TR;Umbria;055020;05010 +F543;Monteleone d'Orvieto;TR;Umbria;055021;05017 +F844;Narni;TR;Umbria;055022;05035 +G148;Orvieto;TR;Umbria;055023;05018 +G189;Otricoli;TR;Umbria;055024;05030 +G344;Parrano;TR;Umbria;055025;05010 +G432;Penna in Teverina;TR;Umbria;055026;05028 +G790;Polino;TR;Umbria;055027;05030 +G881;Porano;TR;Umbria;055028;05010 +H857;San Gemini;TR;Umbria;055029;05029 +I381;San Venanzo;TR;Umbria;055030;05010 +I981;Stroncone;TR;Umbria;055031;05039 +L117;Terni;TR;Umbria;055032;05100 +M258;Avigliano Umbro;TR;Umbria;055033;05020 +A040;Acquapendente;VT;Lazio;056001;01021 +A412;Arlena di Castro;VT;Lazio;056002;01010 +A577;Bagnoregio;VT;Lazio;056003;01022 +A628;Barbarano Romano;VT;Lazio;056004;01010 +A704;Bassano Romano;VT;Lazio;056005;01030 +A706;Bassano in Teverina;VT;Lazio;056006;01030 +A857;Blera;VT;Lazio;056007;01010 +A949;Bolsena;VT;Lazio;056008;01023 +A955;Bomarzo;VT;Lazio;056009;01020 +B388;Calcata;VT;Lazio;056010;01030 +B597;Canepina;VT;Lazio;056011;01030 +B604;Canino;VT;Lazio;056012;01011 +B663;Capodimonte;VT;Lazio;056013;01010 +B688;Capranica;VT;Lazio;056014;01012 +B691;Caprarola;VT;Lazio;056015;01032 +B735;Carbognano;VT;Lazio;056016;01030 +C269;Castel Sant'Elia;VT;Lazio;056017;01030 +C315;Castiglione in Teverina;VT;Lazio;056018;01024 +C446;Celleno;VT;Lazio;056019;01020 +C447;Cellere;VT;Lazio;056020;01010 +C765;Civita Castellana;VT;Lazio;056021;01033 +C780;Civitella d'Agliano;VT;Lazio;056022;01020 +C988;Corchiano;VT;Lazio;056023;01030 +D452;Fabrica di Roma;VT;Lazio;056024;01034 +D475;Faleria;VT;Lazio;056025;01030 +D503;Farnese;VT;Lazio;056026;01010 +D870;Gallese;VT;Lazio;056027;01035 +E126;Gradoli;VT;Lazio;056028;01010 +E128;Graffignano;VT;Lazio;056029;01020 +E210;Grotte di Castro;VT;Lazio;056030;01025 +E330;Ischia di Castro;VT;Lazio;056031;01010 +E467;Latera;VT;Lazio;056032;01010 +E713;Lubriano;VT;Lazio;056033;01020 +E978;Marta;VT;Lazio;056034;01010 +F419;Montalto di Castro;VT;Lazio;056035;01014 +F499;Montefiascone;VT;Lazio;056036;01027 +F603;Monte Romano;VT;Lazio;056037;01010 +F606;Monterosi;VT;Lazio;056038;01030 +F868;Nepi;VT;Lazio;056039;01036 +G065;Onano;VT;Lazio;056040;01010 +G111;Oriolo Romano;VT;Lazio;056041;01010 +G135;Orte;VT;Lazio;056042;01028 +G571;Piansano;VT;Lazio;056043;01010 +H071;Proceno;VT;Lazio;056044;01020 +H534;Ronciglione;VT;Lazio;056045;01037 +H913;Villa San Giovanni in Tuscia;VT;Lazio;056046;01010 +H969;San Lorenzo Nuovo;VT;Lazio;056047;01020 +I855;Soriano nel Cimino;VT;Lazio;056048;01038 +L017;Sutri;VT;Lazio;056049;01015 +D024;Tarquinia;VT;Lazio;056050;01016 +L150;Tessennano;VT;Lazio;056051;01010 +L310;Tuscania;VT;Lazio;056052;01017 +L569;Valentano;VT;Lazio;056053;01018 +L612;Vallerano;VT;Lazio;056054;01030 +A701;Vasanello;VT;Lazio;056055;01030 +L713;Vejano;VT;Lazio;056056;01010 +L814;Vetralla;VT;Lazio;056057;01019 +L882;Vignanello;VT;Lazio;056058;01039 +M082;Viterbo;VT;Lazio;056059;01100 +M086;Vitorchiano;VT;Lazio;056060;01030 +A019;Accumoli;RI;Lazio;057001;02011 +A258;Amatrice;RI;Lazio;057002;02012 +A315;Antrodoco;RI;Lazio;057003;02013 +A464;Ascrea;RI;Lazio;057004;02020 +A765;Belmonte in Sabina;RI;Lazio;057005;02020 +A981;Borbona;RI;Lazio;057006;02010 +B008;Borgorose;RI;Lazio;057007;02021 +A996;Borgo Velino;RI;Lazio;057008;02010 +B627;Cantalice;RI;Lazio;057009;02014 +B631;Cantalupo in Sabina;RI;Lazio;057010;02040 +B934;Casaprota;RI;Lazio;057011;02030 +A472;Casperia;RI;Lazio;057012;02041 +C098;Castel di Tora;RI;Lazio;057013;02020 +C224;Castelnuovo di Farfa;RI;Lazio;057014;02031 +C268;Castel Sant'Angelo;RI;Lazio;057015;02010 +C746;Cittaducale;RI;Lazio;057016;02015 +C749;Cittareale;RI;Lazio;057017;02010 +C841;Collalto Sabino;RI;Lazio;057018;02022 +C857;Colle di Tora;RI;Lazio;057019;02020 +C859;Collegiove;RI;Lazio;057020;02020 +C876;Collevecchio;RI;Lazio;057021;02042 +C880;Colli sul Velino;RI;Lazio;057022;02010 +C946;Concerviano;RI;Lazio;057023;02020 +C959;Configni;RI;Lazio;057024;02040 +C969;Contigliano;RI;Lazio;057025;02043 +D124;Cottanello;RI;Lazio;057026;02040 +D493;Fara in Sabina;RI;Lazio;057027;02032 +D560;Fiamignano;RI;Lazio;057028;02023 +D689;Forano;RI;Lazio;057029;02044 +D785;Frasso Sabino;RI;Lazio;057030;02030 +E160;Greccio;RI;Lazio;057031;02045 +E393;Labro;RI;Lazio;057032;02010 +E535;Leonessa;RI;Lazio;057033;02016 +E681;Longone Sabino;RI;Lazio;057034;02020 +E812;Magliano Sabina;RI;Lazio;057035;02046 +E927;Marcetelli;RI;Lazio;057036;02020 +F193;Micigliano;RI;Lazio;057037;02010 +F319;Mompeo;RI;Lazio;057038;02040 +F430;Montasola;RI;Lazio;057039;02040 +F446;Montebuono;RI;Lazio;057040;02040 +F541;Monteleone Sabino;RI;Lazio;057041;02033 +F579;Montenero Sabino;RI;Lazio;057042;02040 +F619;Monte San Giovanni in Sabina;RI;Lazio;057043;02040 +F687;Montopoli di Sabina;RI;Lazio;057044;02034 +F746;Morro Reatino;RI;Lazio;057045;02010 +F876;Nespolo;RI;Lazio;057046;02020 +B595;Orvinio;RI;Lazio;057047;02035 +G232;Paganico Sabino;RI;Lazio;057048;02020 +G498;Pescorocchiano;RI;Lazio;057049;02024 +G513;Petrella Salto;RI;Lazio;057050;02025 +G756;Poggio Bustone;RI;Lazio;057051;02018 +G757;Poggio Catino;RI;Lazio;057052;02040 +G763;Poggio Mirteto;RI;Lazio;057053;02047 +G764;Poggio Moiano;RI;Lazio;057054;02037 +G765;Poggio Nativo;RI;Lazio;057055;02030 +G770;Poggio San Lorenzo;RI;Lazio;057056;02030 +G934;Posta;RI;Lazio;057057;02019 +G951;Pozzaglia Sabina;RI;Lazio;057058;02030 +H282;Rieti;RI;Lazio;057059;02100 +H354;Rivodutri;RI;Lazio;057060;02010 +H427;Roccantica;RI;Lazio;057061;02040 +H446;Rocca Sinibalda;RI;Lazio;057062;02026 +H713;Salisano;RI;Lazio;057063;02040 +I499;Scandriglia;RI;Lazio;057064;02038 +I581;Selci;RI;Lazio;057065;02040 +I959;Stimigliano;RI;Lazio;057066;02048 +L046;Tarano;RI;Lazio;057067;02040 +L189;Toffia;RI;Lazio;057068;02039 +L293;Torricella in Sabina;RI;Lazio;057069;02030 +L286;Torri in Sabina;RI;Lazio;057070;02049 +G507;Turania;RI;Lazio;057071;02020 +L525;Vacone;RI;Lazio;057072;02040 +L676;Varco Sabino;RI;Lazio;057073;02020 +A062;Affile;RM;Lazio;058001;00021 +A084;Agosta;RM;Lazio;058002;00020 +A132;Albano Laziale;RM;Lazio;058003;00041 +A210;Allumiere;RM;Lazio;058004;00051 +A297;Anguillara Sabazia;RM;Lazio;058005;00061 +A309;Anticoli Corrado;RM;Lazio;058006;00022 +A323;Anzio;RM;Lazio;058007;00042 +A370;Arcinazzo Romano;RM;Lazio;058008;00020 +A401;Ariccia;RM;Lazio;058009;00072 +A446;Arsoli;RM;Lazio;058010;00023 +A449;Artena;RM;Lazio;058011;00031 +A749;Bellegra;RM;Lazio;058012;00030 +B114;Bracciano;RM;Lazio;058013;00062 +B472;Camerata Nuova;RM;Lazio;058014;00020 +B496;Campagnano di Roma;RM;Lazio;058015;00063 +B576;Canale Monterano;RM;Lazio;058016;00060 +B635;Canterano;RM;Lazio;058017;00020 +B649;Capena;RM;Lazio;058018;00060 +B687;Capranica Prenestina;RM;Lazio;058019;00030 +B828;Carpineto Romano;RM;Lazio;058020;00032 +B932;Casape;RM;Lazio;058021;00010 +C116;Castel Gandolfo;RM;Lazio;058022;00073 +C203;Castel Madama;RM;Lazio;058023;00024 +C237;Castelnuovo di Porto;RM;Lazio;058024;00060 +C266;Castel San Pietro Romano;RM;Lazio;058025;00030 +C390;Cave;RM;Lazio;058026;00033 +C518;Cerreto Laziale;RM;Lazio;058027;00020 +C543;Cervara di Roma;RM;Lazio;058028;00020 +C552;Cerveteri;RM;Lazio;058029;00052 +C677;Ciciliano;RM;Lazio;058030;00020 +C702;Cineto Romano;RM;Lazio;058031;00020 +C773;Civitavecchia;RM;Lazio;058032;00053 +C784;Civitella San Paolo;RM;Lazio;058033;00060 +C858;Colleferro;RM;Lazio;058034;00034 +C900;Colonna;RM;Lazio;058035;00030 +D561;Fiano Romano;RM;Lazio;058036;00065 +D586;Filacciano;RM;Lazio;058037;00060 +D707;Formello;RM;Lazio;058038;00060 +D773;Frascati;RM;Lazio;058039;00044 +D875;Gallicano nel Lazio;RM;Lazio;058040;00010 +D945;Gavignano;RM;Lazio;058041;00030 +D964;Genazzano;RM;Lazio;058042;00030 +D972;Genzano di Roma;RM;Lazio;058043;00045 +D978;Gerano;RM;Lazio;058044;00025 +E091;Gorga;RM;Lazio;058045;00030 +E204;Grottaferrata;RM;Lazio;058046;00046 +E263;Guidonia Montecelio;RM;Lazio;058047;00012 +E382;Jenne;RM;Lazio;058048;00020 +E392;Labico;RM;Lazio;058049;00030 +C767;Lanuvio;RM;Lazio;058050;00075 +E576;Licenza;RM;Lazio;058051;00026 +E813;Magliano Romano;RM;Lazio;058052;00060 +B632;Mandela;RM;Lazio;058053;00020 +E900;Manziana;RM;Lazio;058054;00066 +E908;Marano Equo;RM;Lazio;058055;00020 +E924;Marcellina;RM;Lazio;058056;00010 +E958;Marino;RM;Lazio;058057;00047 +F064;Mazzano Romano;RM;Lazio;058058;00060 +F127;Mentana;RM;Lazio;058059;00013 +F477;Monte Compatri;RM;Lazio;058060; +F504;Monteflavio;RM;Lazio;058061;00010 +F534;Montelanico;RM;Lazio;058062;00030 +F545;Montelibretti;RM;Lazio;058063;00010 +F590;Monte Porzio Catone;RM;Lazio;058064;00078 +F611;Monterotondo;RM;Lazio;058065;00015 +F692;Montorio Romano;RM;Lazio;058066;00010 +F730;Moricone;RM;Lazio;058067;00010 +F734;Morlupo;RM;Lazio;058068;00067 +F857;Nazzano;RM;Lazio;058069;00060 +F865;Nemi;RM;Lazio;058070;00074 +F871;Nerola;RM;Lazio;058071;00017 +F880;Nettuno;RM;Lazio;058072;00048 +G022;Olevano Romano;RM;Lazio;058073;00035 +G274;Palestrina;RM;Lazio;058074;00036 +G293;Palombara Sabina;RM;Lazio;058075;00018 +G444;Percile;RM;Lazio;058076;00020 +G704;Pisoniano;RM;Lazio;058077;00020 +G784;Poli;RM;Lazio;058078;00010 +G811;Pomezia;RM;Lazio;058079;00071 +G874;Ponzano Romano;RM;Lazio;058080;00060 +H267;Riano;RM;Lazio;058081;00060 +H288;Rignano Flaminio;RM;Lazio;058082;00068 +H300;Riofreddo;RM;Lazio;058083;00020 +H387;Rocca Canterano;RM;Lazio;058084;00020 +H401;Rocca di Cave;RM;Lazio;058085;00030 +H404;Rocca di Papa;RM;Lazio;058086;00040 +H411;Roccagiovine;RM;Lazio;058087;00020 +H432;Rocca Priora;RM;Lazio;058088;00079 +H441;Rocca Santo Stefano;RM;Lazio;058089;00030 +H494;Roiate;RM;Lazio;058090;00030 +H501;Roma;RM;Lazio;058091;00118-00128,00131-00139,00141-00149,00151-00159,00161-00169,00171-00179,00181-00189,00191-00199 +H618;Roviano;RM;Lazio;058092;00027 +H658;Sacrofano;RM;Lazio;058093;00060 +H745;Sambuci;RM;Lazio;058094;00020 +H942;San Gregorio da Sassola;RM;Lazio;058095;00010 +I125;San Polo dei Cavalieri;RM;Lazio;058096;00010 +I255;Santa Marinella;RM;Lazio;058097;00058 +I284;Sant'Angelo Romano;RM;Lazio;058098;00010 +I352;Sant'Oreste;RM;Lazio;058099;00060 +I400;San Vito Romano;RM;Lazio;058100;00030 +I424;Saracinesco;RM;Lazio;058101;00020 +I573;Segni;RM;Lazio;058102;00037 +I992;Subiaco;RM;Lazio;058103;00028 +L182;Tivoli;RM;Lazio;058104;00019 +L192;Tolfa;RM;Lazio;058105;00059 +L302;Torrita Tiberina;RM;Lazio;058106;00060 +L401;Trevignano Romano;RM;Lazio;058107;00069 +L611;Vallepietra;RM;Lazio;058108;00020 +L625;Vallinfreda;RM;Lazio;058109;00020 +L639;Valmontone;RM;Lazio;058110;00038 +L719;Velletri;RM;Lazio;058111;00049 +L851;Vicovaro;RM;Lazio;058112;00029 +M095;Vivaro Romano;RM;Lazio;058113;00020 +M141;Zagarolo;RM;Lazio;058114;00039 +M207;Lariano;RM;Lazio;058115;00076 +M212;Ladispoli;RM;Lazio;058116;00055 +M213;Ardea;RM;Lazio;058117;00040 +M272;Ciampino;RM;Lazio;058118;00043 +M295;San Cesareo;RM;Lazio;058119;00030 +M297;Fiumicino;RM;Lazio;058120;00054 +M309;Fonte Nuova;RM;Lazio;058122;00013 +A341;Aprilia;LT;Lazio;059001;04011 +A707;Bassiano;LT;Lazio;059002;04010 +B527;Campodimele;LT;Lazio;059003;04020 +C104;Castelforte;LT;Lazio;059004;04021 +C740;Cisterna di Latina;LT;Lazio;059005;04012 +D003;Cori;LT;Lazio;059006;04010 +D662;Fondi;LT;Lazio;059007;04022 +D708;Formia;LT;Lazio;059008;04023 +D843;Gaeta;LT;Lazio;059009;04024 +E375;Itri;LT;Lazio;059010;04020 +E472;Latina;LT;Lazio;059011;04100 +E527;Lenola;LT;Lazio;059012;04025 +E798;Maenza;LT;Lazio;059013;04010 +F224;Minturno;LT;Lazio;059014;04026 +F616;Monte San Biagio;LT;Lazio;059015;04020 +F937;Norma;LT;Lazio;059016;04010 +G865;Pontinia;LT;Lazio;059017;04014 +G871;Ponza;LT;Lazio;059018;04027 +G698;Priverno;LT;Lazio;059019;04015 +H076;Prossedi;LT;Lazio;059020;04010 +H413;Roccagorga;LT;Lazio;059021;04010 +H421;Rocca Massima;LT;Lazio;059022;04010 +H444;Roccasecca dei Volsci;LT;Lazio;059023;04010 +H647;Sabaudia;LT;Lazio;059024;04016 +H836;San Felice Circeo;LT;Lazio;059025;04017 +I339;Santi Cosma e Damiano;LT;Lazio;059026;04020 +I634;Sermoneta;LT;Lazio;059027;04013 +I712;Sezze;LT;Lazio;059028;04018 +I832;Sonnino;LT;Lazio;059029;04010 +I892;Sperlonga;LT;Lazio;059030;04029 +I902;Spigno Saturnia;LT;Lazio;059031;04020 +L120;Terracina;LT;Lazio;059032;04019 +L742;Ventotene;LT;Lazio;059033;04020 +A032;Acquafondata;FR;Lazio;060001;03040 +A054;Acuto;FR;Lazio;060002;03010 +A123;Alatri;FR;Lazio;060003;03011 +A244;Alvito;FR;Lazio;060004;03041 +A256;Amaseno;FR;Lazio;060005;03021 +A269;Anagni;FR;Lazio;060006;03012 +A348;Aquino;FR;Lazio;060007;03031 +A363;Arce;FR;Lazio;060008;03032 +A421;Arnara;FR;Lazio;060009;03020 +A433;Arpino;FR;Lazio;060010;03033 +A486;Atina;FR;Lazio;060011;03042 +A502;Ausonia;FR;Lazio;060012;03040 +A763;Belmonte Castello;FR;Lazio;060013;03040 +A720;Boville Ernica;FR;Lazio;060014;03022 +B195;Broccostella;FR;Lazio;060015;03030 +B543;Campoli Appennino;FR;Lazio;060016;03030 +B862;Casalattico;FR;Lazio;060017;03030 +B919;Casalvieri;FR;Lazio;060018;03034 +C034;Cassino;FR;Lazio;060019;03043 +C177;Castelliri;FR;Lazio;060020;03030 +C223;Castelnuovo Parano;FR;Lazio;060021;03040 +C340;Castrocielo;FR;Lazio;060022;03030 +C338;Castro dei Volsci;FR;Lazio;060023;03020 +C413;Ceccano;FR;Lazio;060024;03023 +C479;Ceprano;FR;Lazio;060025;03024 +C545;Cervaro;FR;Lazio;060026;03044 +C836;Colfelice;FR;Lazio;060027;03030 +C864;Collepardo;FR;Lazio;060028;03010 +C870;Colle San Magno;FR;Lazio;060029;03030 +C998;Coreno Ausonio;FR;Lazio;060030;03040 +D440;Esperia;FR;Lazio;060031;03045 +D483;Falvaterra;FR;Lazio;060032;03020 +D539;Ferentino;FR;Lazio;060033;03013 +D591;Filettino;FR;Lazio;060034;03010 +A310;Fiuggi;FR;Lazio;060035;03014 +D667;Fontana Liri;FR;Lazio;060036;03035 +D682;Fontechiari;FR;Lazio;060037;03030 +D810;Frosinone;FR;Lazio;060038;03100 +D819;Fumone;FR;Lazio;060039;03010 +D881;Gallinaro;FR;Lazio;060040;03040 +E057;Giuliano di Roma;FR;Lazio;060041;03020 +E236;Guarcino;FR;Lazio;060042;03016 +E340;Isola del Liri;FR;Lazio;060043;03036 +F620;Monte San Giovanni Campano;FR;Lazio;060044;03025 +F740;Morolo;FR;Lazio;060045;03017 +G276;Paliano;FR;Lazio;060046;03018 +G362;Pastena;FR;Lazio;060047;03020 +G374;Patrica;FR;Lazio;060048;03010 +G500;Pescosolido;FR;Lazio;060049;03030 +G591;Picinisco;FR;Lazio;060050;03040 +G592;Pico;FR;Lazio;060051;03020 +G598;Piedimonte San Germano;FR;Lazio;060052;03030 +G659;Piglio;FR;Lazio;060053;03010 +G662;Pignataro Interamna;FR;Lazio;060054;03040 +G749;Pofi;FR;Lazio;060055;03026 +G838;Pontecorvo;FR;Lazio;060056;03037 +G935;Posta Fibreno;FR;Lazio;060057;03030 +H324;Ripi;FR;Lazio;060058;03027 +H393;Rocca d'Arce;FR;Lazio;060059;03030 +H443;Roccasecca;FR;Lazio;060060;03038 +H779;San Biagio Saracinisco;FR;Lazio;060061;03040 +H824;San Donato Val di Comino;FR;Lazio;060062;03046 +H880;San Giorgio a Liri;FR;Lazio;060063;03047 +H917;San Giovanni Incarico;FR;Lazio;060064;03028 +I256;Sant'Ambrogio sul Garigliano;FR;Lazio;060065;03040 +I265;Sant'Andrea del Garigliano;FR;Lazio;060066;03040 +I302;Sant'Apollinare;FR;Lazio;060067;03048 +I321;Sant'Elia Fiumerapido;FR;Lazio;060068;03049 +I351;Santopadre;FR;Lazio;060069;03030 +I408;San Vittore del Lazio;FR;Lazio;060070;03040 +I669;Serrone;FR;Lazio;060071;03010 +I697;Settefrati;FR;Lazio;060072;03040 +I716;Sgurgola;FR;Lazio;060073;03010 +I838;Sora;FR;Lazio;060074;03039 +I973;Strangolagalli;FR;Lazio;060075;03020 +L009;Supino;FR;Lazio;060076;03019 +L105;Terelle;FR;Lazio;060077;03040 +L243;Torre Cajetani;FR;Lazio;060078;03010 +L290;Torrice;FR;Lazio;060079;03020 +L398;Trevi nel Lazio;FR;Lazio;060080;03010 +L437;Trivigliano;FR;Lazio;060081;03010 +L598;Vallecorsa;FR;Lazio;060082;03020 +L605;Vallemaio;FR;Lazio;060083;03040 +L614;Vallerotonda;FR;Lazio;060084;03040 +L780;Veroli;FR;Lazio;060085;03029 +L836;Vicalvi;FR;Lazio;060086;03030 +L843;Vico nel Lazio;FR;Lazio;060087;03010 +A081;Villa Latina;FR;Lazio;060088;03040 +L905;Villa Santa Lucia;FR;Lazio;060089;03030 +I364;Villa Santo Stefano;FR;Lazio;060090;03020 +M083;Viticuso;FR;Lazio;060091;03040 +A106;Ailano;CE;Campania;061001;81010 +A200;Alife;CE;Campania;061002;81011 +A243;Alvignano;CE;Campania;061003;81012 +A403;Arienzo;CE;Campania;061004;81021 +A512;Aversa;CE;Campania;061005;81031 +A579;Baia e Latina;CE;Campania;061006;81010 +A755;Bellona;CE;Campania;061007;81041 +B361;Caianello;CE;Campania;061008;81059 +B362;Caiazzo;CE;Campania;061009;81013 +B445;Calvi Risorta;CE;Campania;061010;81042 +B477;Camigliano;CE;Campania;061011;81050 +B581;Cancello ed Arnone;CE;Campania;061012;81030 +B667;Capodrise;CE;Campania;061013;81020 +B704;Capriati a Volturno;CE;Campania;061014;81014 +B715;Capua;CE;Campania;061015;81043 +B779;Carinaro;CE;Campania;061016;81032 +B781;Carinola;CE;Campania;061017;81030 +B860;Casagiove;CE;Campania;061018;81022 +B872;Casal di Principe;CE;Campania;061019;81033 +B916;Casaluce;CE;Campania;061020;81030 +B935;Casapulla;CE;Campania;061021;81020 +B963;Caserta;CE;Campania;061022;81100 +B494;Castel Campagnano;CE;Campania;061023;81010 +C097;Castel di Sasso;CE;Campania;061024;81040 +C178;Castello del Matese;CE;Campania;061025;81016 +C211;Castel Morrone;CE;Campania;061026;81020 +C291;Castel Volturno;CE;Campania;061027;81030 +C558;Cervino;CE;Campania;061028;81023 +C561;Cesa;CE;Campania;061029;81030 +C716;Ciorlano;CE;Campania;061030;81010 +C939;Conca della Campania;CE;Campania;061031;81044 +D228;Curti;CE;Campania;061032;81040 +D361;Dragoni;CE;Campania;061033;81010 +D683;Fontegreca;CE;Campania;061034;81014 +D709;Formicola;CE;Campania;061035;81040 +D769;Francolise;CE;Campania;061036;81050 +D799;Frignano;CE;Campania;061037;81030 +D884;Gallo Matese;CE;Campania;061038;81010 +D886;Galluccio;CE;Campania;061039;81044 +E011;Giano Vetusto;CE;Campania;061040;81042 +E039;Gioia Sannitica;CE;Campania;061041;81010 +E158;Grazzanise;CE;Campania;061042;81046 +E173;Gricignano di Aversa;CE;Campania;061043;81030 +E554;Letino;CE;Campania;061044;81010 +E570;Liberi;CE;Campania;061045;81040 +E754;Lusciano;CE;Campania;061046;81030 +E784;Macerata Campania;CE;Campania;061047;81047 +E791;Maddaloni;CE;Campania;061048;81024 +E932;Marcianise;CE;Campania;061049;81025 +E998;Marzano Appio;CE;Campania;061050;81035 +F203;Mignano Monte Lungo;CE;Campania;061051;81049 +F352;Mondragone;CE;Campania;061052;81034 +G130;Orta di Atella;CE;Campania;061053;81030 +G333;Parete;CE;Campania;061054;81030 +G364;Pastorano;CE;Campania;061055;81050 +G541;Piana di Monte Verna;CE;Campania;061056;81013 +G596;Piedimonte Matese;CE;Campania;061057;81016 +G620;Pietramelara;CE;Campania;061058;81051 +G630;Pietravairano;CE;Campania;061059;81040 +G661;Pignataro Maggiore;CE;Campania;061060;81052 +G849;Pontelatone;CE;Campania;061061;81040 +G903;Portico di Caserta;CE;Campania;061062;81050 +G991;Prata Sannita;CE;Campania;061063;81010 +G995;Pratella;CE;Campania;061064;81010 +H045;Presenzano;CE;Campania;061065;81050 +H202;Raviscanina;CE;Campania;061066;81017 +H210;Recale;CE;Campania;061067;81020 +H268;Riardo;CE;Campania;061068;81053 +H398;Rocca d'Evandro;CE;Campania;061069;81040 +H423;Roccamonfina;CE;Campania;061070;81035 +H436;Roccaromana;CE;Campania;061071;81051 +H459;Rocchetta e Croce;CE;Campania;061072;81042 +H165;Ruviano;CE;Campania;061073;81010 +H798;San Cipriano d'Aversa;CE;Campania;061074;81036 +H834;San Felice a Cancello;CE;Campania;061075;81027 +H939;San Gregorio Matese;CE;Campania;061076;81010 +H978;San Marcellino;CE;Campania;061077;81030 +I056;San Nicola la Strada;CE;Campania;061078;81020 +I113;San Pietro Infine;CE;Campania;061079;81049 +I130;San Potito Sannitico;CE;Campania;061080;81016 +I131;San Prisco;CE;Campania;061081;81054 +I233;Santa Maria a Vico;CE;Campania;061082;81028 +I234;Santa Maria Capua Vetere;CE;Campania;061083;81055 +I247;Santa Maria la Fossa;CE;Campania;061084;81050 +I261;San Tammaro;CE;Campania;061085;81050 +I273;Sant'Angelo d'Alife;CE;Campania;061086;81017 +I306;Sant'Arpino;CE;Campania;061087;81030 +I676;Sessa Aurunca;CE;Campania;061088;81037 +I885;Sparanise;CE;Campania;061089;81056 +I993;Succivo;CE;Campania;061090;81030 +L083;Teano;CE;Campania;061091;81057 +L155;Teverola;CE;Campania;061092;81030 +L205;Tora e Piccilli;CE;Campania;061093;81044 +L379;Trentola Ducenta;CE;Campania;061094;81038 +L540;Vairano Patenora;CE;Campania;061095;81058 +L594;Valle Agricola;CE;Campania;061096;81010 +L591;Valle di Maddaloni;CE;Campania;061097;81020 +D801;Villa di Briano;CE;Campania;061098;81030 +L844;Villa Literno;CE;Campania;061099;81039 +M092;Vitulazio;CE;Campania;061100;81041 +D471;Falciano del Massico;CE;Campania;061101;81030 +M262;Cellole;CE;Campania;061102;81030 +M260;Casapesenna;CE;Campania;061103;81030 +F043;San Marco Evangelista;CE;Campania;061104;81020 +A110;Airola;BN;Campania;062001;82011 +A265;Amorosi;BN;Campania;062002;82031 +A328;Apice;BN;Campania;062003;82021 +A330;Apollosa;BN;Campania;062004;82030 +A431;Arpaia;BN;Campania;062005;82011 +A432;Arpaise;BN;Campania;062006;82010 +A696;Baselice;BN;Campania;062007;82020 +A783;Benevento;BN;Campania;062008;82100 +A970;Bonea;BN;Campania;062009;82013 +B239;Bucciano;BN;Campania;062010;82010 +B267;Buonalbergo;BN;Campania;062011;82020 +B444;Calvi;BN;Campania;062012;82018 +B541;Campolattaro;BN;Campania;062013;82020 +B542;Campoli del Monte Taburno;BN;Campania;062014;82030 +B873;Casalduni;BN;Campania;062015;82027 +C106;Castelfranco in Miscano;BN;Campania;062016;82022 +C245;Castelpagano;BN;Campania;062017;82024 +C250;Castelpoto;BN;Campania;062018;82030 +C280;Castelvenere;BN;Campania;062019;82037 +C284;Castelvetere in Val Fortore;BN;Campania;062020;82023 +C359;Cautano;BN;Campania;062021;82030 +C476;Ceppaloni;BN;Campania;062022;82010 +C525;Cerreto Sannita;BN;Campania;062023;82032 +C719;Circello;BN;Campania;062024;82020 +C846;Colle Sannita;BN;Campania;062025;82024 +D230;Cusano Mutri;BN;Campania;062026;82033 +D380;Dugenta;BN;Campania;062027;82030 +D386;Durazzano;BN;Campania;062028;82015 +D469;Faicchio;BN;Campania;062029;82030 +D644;Foglianise;BN;Campania;062030;82030 +D650;Foiano di Val Fortore;BN;Campania;062031;82020 +D693;Forchia;BN;Campania;062032;82011 +D755;Fragneto l'Abate;BN;Campania;062033;82020 +D756;Fragneto Monforte;BN;Campania;062034;82020 +D784;Frasso Telesino;BN;Campania;062035;82030 +E034;Ginestra degli Schiavoni;BN;Campania;062036;82020 +E249;Guardia Sanframondi;BN;Campania;062037;82034 +E589;Limatola;BN;Campania;062038;82030 +F113;Melizzano;BN;Campania;062039;82030 +F274;Moiano;BN;Campania;062040;82010 +F287;Molinara;BN;Campania;062041;82020 +F494;Montefalcone di Val Fortore;BN;Campania;062042;82025 +F636;Montesarchio;BN;Campania;062043;82016 +F717;Morcone;BN;Campania;062044;82026 +G227;Paduli;BN;Campania;062045;82020 +G243;Pago Veiano;BN;Campania;062046;82020 +G311;Pannarano;BN;Campania;062047;82017 +G318;Paolisi;BN;Campania;062048;82011 +G386;Paupisi;BN;Campania;062049;82030 +G494;Pesco Sannita;BN;Campania;062050;82020 +G626;Pietraroja;BN;Campania;062051;82030 +G631;Pietrelcina;BN;Campania;062052;82020 +G827;Ponte;BN;Campania;062053;82030 +G848;Pontelandolfo;BN;Campania;062054;82027 +H087;Puglianello;BN;Campania;062055;82030 +H227;Reino;BN;Campania;062056;82020 +H764;San Bartolomeo in Galdo;BN;Campania;062057;82028 +H894;San Giorgio del Sannio;BN;Campania;062058;82018 +H898;San Giorgio La Molara;BN;Campania;062059;82020 +H953;San Leucio del Sannio;BN;Campania;062060;82010 +H955;San Lorenzello;BN;Campania;062061;82030 +H967;San Lorenzo Maggiore;BN;Campania;062062;82034 +H973;San Lupo;BN;Campania;062063;82034 +H984;San Marco dei Cavoti;BN;Campania;062064;82029 +I002;San Martino Sannita;BN;Campania;062065;82010 +I049;San Nazzaro;BN;Campania;062066;82018 +I062;San Nicola Manfredi;BN;Campania;062067;82010 +I145;San Salvatore Telesino;BN;Campania;062068;82030 +I179;Santa Croce del Sannio;BN;Campania;062069;82020 +I197;Sant'Agata de' Goti;BN;Campania;062070;82019 +I277;Sant'Angelo a Cupolo;BN;Campania;062071;82010 +I455;Sassinoro;BN;Campania;062072;82026 +I809;Solopaca;BN;Campania;062073;82036 +L086;Telese Terme;BN;Campania;062074;82037 +L185;Tocco Caudio;BN;Campania;062075;82030 +L254;Torrecuso;BN;Campania;062076;82030 +M093;Vitulano;BN;Campania;062077;82038 +F557;Sant'Arcangelo Trimonte;BN;Campania;062078;82021 +A024;Acerra;NA;Campania;063001;80011 +A064;Afragola;NA;Campania;063002;80021 +A068;Agerola;NA;Campania;063003;80051 +A268;Anacapri;NA;Campania;063004;80071 +A455;Arzano;NA;Campania;063005;80022 +A535;Bacoli;NA;Campania;063006;80070 +A617;Barano d'Ischia;NA;Campania;063007;80070 +B076;Boscoreale;NA;Campania;063008;80041 +B077;Boscotrecase;NA;Campania;063009;80042 +B227;Brusciano;NA;Campania;063010;80031 +B371;Caivano;NA;Campania;063011;80023 +B452;Calvizzano;NA;Campania;063012;80012 +B565;Camposano;NA;Campania;063013;80030 +B696;Capri;NA;Campania;063014;80073 +B740;Carbonara di Nola;NA;Campania;063015;80030 +B759;Cardito;NA;Campania;063016;80024 +B905;Casalnuovo di Napoli;NA;Campania;063017;80013 +B922;Casamarciano;NA;Campania;063018;80032 +B924;Casamicciola Terme;NA;Campania;063019;80074 +B925;Casandrino;NA;Campania;063020;80025 +B946;Casavatore;NA;Campania;063021;80020 +B980;Casola di Napoli;NA;Campania;063022;80050 +B990;Casoria;NA;Campania;063023;80026 +C129;Castellammare di Stabia;NA;Campania;063024;80053 +C188;Castello di Cisterna;NA;Campania;063025;80030 +C495;Cercola;NA;Campania;063026;80040 +C675;Cicciano;NA;Campania;063027;80033 +C697;Cimitile;NA;Campania;063028;80030 +C929;Comiziano;NA;Campania;063029;80030 +D170;Crispano;NA;Campania;063030;80020 +D702;Forio;NA;Campania;063031;80075 +D789;Frattamaggiore;NA;Campania;063032;80027 +D790;Frattaminore;NA;Campania;063033;80020 +E054;Giugliano in Campania;NA;Campania;063034;80014 +E131;Gragnano;NA;Campania;063035;80054 +E224;Grumo Nevano;NA;Campania;063036;80028 +E329;Ischia;NA;Campania;063037;80077 +E396;Lacco Ameno;NA;Campania;063038;80076 +E557;Lettere;NA;Campania;063039;80050 +E620;Liveri;NA;Campania;063040;80030 +E906;Marano di Napoli;NA;Campania;063041;80016 +E954;Mariglianella;NA;Campania;063042;80030 +E955;Marigliano;NA;Campania;063043;80034 +F030;Massa Lubrense;NA;Campania;063044;80061 +F111;Melito di Napoli;NA;Campania;063045;80017 +F162;Meta;NA;Campania;063046;80062 +F488;Monte di Procida;NA;Campania;063047;80070 +F799;Mugnano di Napoli;NA;Campania;063048;80018 +F839;Napoli;NA;Campania;063049;80100,80121-80129,80131-80139,80141-80147 +F924;Nola;NA;Campania;063050;80035 +G190;Ottaviano;NA;Campania;063051;80044 +G283;Palma Campania;NA;Campania;063052;80036 +G568;Piano di Sorrento;NA;Campania;063053;80063 +G670;Pimonte;NA;Campania;063054;80050 +G762;Poggiomarino;NA;Campania;063055;80040 +G795;Pollena Trocchia;NA;Campania;063056;80040 +G812;Pomigliano d'Arco;NA;Campania;063057;80038 +G813;Pompei;NA;Campania;063058;80045 +G902;Portici;NA;Campania;063059;80055 +G964;Pozzuoli;NA;Campania;063060;80078 +H072;Procida;NA;Campania;063061;80079 +H101;Qualiano;NA;Campania;063062;80019 +H114;Quarto;NA;Campania;063063;80010 +H243;Ercolano;NA;Campania;063064;80056 +H433;Roccarainola;NA;Campania;063065;80030 +H860;San Gennaro Vesuviano;NA;Campania;063066;80040 +H892;San Giorgio a Cremano;NA;Campania;063067;80046 +H931;San Giuseppe Vesuviano;NA;Campania;063068;80047 +I073;San Paolo Bel Sito;NA;Campania;063069;80030 +I151;San Sebastiano al Vesuvio;NA;Campania;063070;80040 +I208;Sant'Agnello;NA;Campania;063071;80065 +I262;Sant'Anastasia;NA;Campania;063072;80048 +I293;Sant'Antimo;NA;Campania;063073;80029 +I300;Sant'Antonio Abate;NA;Campania;063074;80057 +I391;San Vitaliano;NA;Campania;063075;80030 +I469;Saviano;NA;Campania;063076;80039 +I540;Scisciano;NA;Campania;063077;80030 +I652;Serrara Fontana;NA;Campania;063078;80070 +I820;Somma Vesuviana;NA;Campania;063079;80049 +I862;Sorrento;NA;Campania;063080;80067 +I978;Striano;NA;Campania;063081;80040 +L142;Terzigno;NA;Campania;063082;80040 +L245;Torre Annunziata;NA;Campania;063083;80058 +L259;Torre del Greco;NA;Campania;063084;80059 +L460;Tufino;NA;Campania;063085;80030 +L845;Vico Equense;NA;Campania;063086;80069 +G309;Villaricca;NA;Campania;063087;80010 +M072;Visciano;NA;Campania;063088;80030 +M115;Volla;NA;Campania;063089;80040 +M273;Santa Maria la Carità;NA;Campania;063090;80050 +M280;Trecase;NA;Campania;063091;80040 +M289;Massa di Somma;NA;Campania;063092;80040 +A101;Aiello del Sabato;AV;Campania;064001;83020 +A228;Altavilla Irpina;AV;Campania;064002;83011 +A284;Andretta;AV;Campania;064003;83040 +A347;Aquilonia;AV;Campania;064004;83041 +A399;Ariano Irpino;AV;Campania;064005;83031 +A489;Atripalda;AV;Campania;064006;83042 +A508;Avella;AV;Campania;064007;83021 +A509;Avellino;AV;Campania;064008;83100 +A566;Bagnoli Irpino;AV;Campania;064009;83043 +A580;Baiano;AV;Campania;064010;83022 +A881;Bisaccia;AV;Campania;064011;83044 +A975;Bonito;AV;Campania;064012;83032 +B367;Cairano;AV;Campania;064013;83040 +B374;Calabritto;AV;Campania;064014;83040 +B415;Calitri;AV;Campania;064015;83045 +B590;Candida;AV;Campania;064016;83040 +B674;Caposele;AV;Campania;064017;83040 +B706;Capriglia Irpina;AV;Campania;064018;83010 +B776;Carife;AV;Campania;064019;83040 +B866;Casalbore;AV;Campania;064020;83034 +B997;Cassano Irpino;AV;Campania;064021;83040 +C058;Castel Baronia;AV;Campania;064022;83040 +C105;Castelfranci;AV;Campania;064023;83040 +C283;Castelvetere sul Calore;AV;Campania;064024;83040 +C557;Cervinara;AV;Campania;064025;83012 +C576;Cesinali;AV;Campania;064026;83020 +C606;Chianche;AV;Campania;064027;83010 +C659;Chiusano di San Domenico;AV;Campania;064028;83040 +C971;Contrada;AV;Campania;064029;83020 +C976;Conza della Campania;AV;Campania;064030;83040 +D331;Domicella;AV;Campania;064031;83020 +D638;Flumeri;AV;Campania;064032;83040 +D671;Fontanarosa;AV;Campania;064033;83040 +D701;Forino;AV;Campania;064034;83020 +D798;Frigento;AV;Campania;064035;83040 +D998;Gesualdo;AV;Campania;064036;83040 +E161;Greci;AV;Campania;064037;83030 +E206;Grottaminarda;AV;Campania;064038;83035 +E214;Grottolella;AV;Campania;064039;83010 +E245;Guardia Lombardi;AV;Campania;064040;83040 +E397;Lacedonia;AV;Campania;064041;83046 +E448;Lapio;AV;Campania;064042;83030 +E487;Lauro;AV;Campania;064043;83023 +E605;Lioni;AV;Campania;064044;83047 +E746;Luogosano;AV;Campania;064045;83040 +E891;Manocalzati;AV;Campania;064046;83030 +E997;Marzano di Nola;AV;Campania;064047;83020 +F110;Melito Irpino;AV;Campania;064048;83030 +F141;Mercogliano;AV;Campania;064049;83013 +F230;Mirabella Eclano;AV;Campania;064050;83036 +F397;Montaguto;AV;Campania;064051;83030 +F448;Montecalvo Irpino;AV;Campania;064052;83037 +F491;Montefalcione;AV;Campania;064053;83030 +F506;Monteforte Irpino;AV;Campania;064054;83024 +F511;Montefredane;AV;Campania;064055;83030 +F512;Montefusco;AV;Campania;064056;83030 +F546;Montella;AV;Campania;064057;83048 +F559;Montemarano;AV;Campania;064058;83040 +F566;Montemiletto;AV;Campania;064059;83038 +F660;Monteverde;AV;Campania;064060;83049 +F744;Morra De Sanctis;AV;Campania;064063;83040 +F762;Moschiano;AV;Campania;064064;83020 +F798;Mugnano del Cardinale;AV;Campania;064065;83027 +F988;Nusco;AV;Campania;064066;83051 +G165;Ospedaletto d'Alpinolo;AV;Campania;064067;83014 +G242;Pago del Vallo di Lauro;AV;Campania;064068;83020 +G340;Parolise;AV;Campania;064069;83050 +G370;Paternopoli;AV;Campania;064070;83052 +G519;Petruro Irpino;AV;Campania;064071;83010 +G611;Pietradefusi;AV;Campania;064072;83030 +G629;Pietrastornina;AV;Campania;064073;83015 +G990;Prata di Principato Ultra;AV;Campania;064074;83030 +H006;Pratola Serra;AV;Campania;064075;83039 +H097;Quadrelle;AV;Campania;064076;83020 +H128;Quindici;AV;Campania;064077;83020 +H382;Roccabascerana;AV;Campania;064078;83016 +H438;Rocca San Felice;AV;Campania;064079;83050 +H592;Rotondi;AV;Campania;064080;83017 +H733;Salza Irpina;AV;Campania;064081;83050 +H975;San Mango sul Calore;AV;Campania;064082;83050 +I016;San Martino Valle Caudina;AV;Campania;064083;83018 +I034;San Michele di Serino;AV;Campania;064084;83020 +I061;San Nicola Baronia;AV;Campania;064085;83050 +I129;San Potito Ultra;AV;Campania;064086;83050 +I163;San Sossio Baronia;AV;Campania;064087;83050 +I219;Santa Lucia di Serino;AV;Campania;064088;83020 +I264;Sant'Andrea di Conza;AV;Campania;064089;83053 +I279;Sant'Angelo all'Esca;AV;Campania;064090;83050 +I280;Sant'Angelo a Scala;AV;Campania;064091;83010 +I281;Sant'Angelo dei Lombardi;AV;Campania;064092;83054 +I301;Santa Paolina;AV;Campania;064093;83030 +I357;Santo Stefano del Sole;AV;Campania;064095;83050 +I471;Savignano Irpino;AV;Campania;064096;83030 +I493;Scampitella;AV;Campania;064097;83050 +I606;Senerchia;AV;Campania;064098;83050 +I630;Serino;AV;Campania;064099;83028 +I756;Sirignano;AV;Campania;064100;83020 +I805;Solofra;AV;Campania;064101;83029 +I843;Sorbo Serpico;AV;Campania;064102;83050 +I893;Sperone;AV;Campania;064103;83020 +I990;Sturno;AV;Campania;064104;83055 +L004;Summonte;AV;Campania;064105;83010 +L061;Taurano;AV;Campania;064106;83020 +L062;Taurasi;AV;Campania;064107;83030 +L102;Teora;AV;Campania;064108;83056 +L214;Torella dei Lombardi;AV;Campania;064109;83057 +L272;Torre Le Nocelle;AV;Campania;064110;83030 +L301;Torrioni;AV;Campania;064111;83010 +L399;Trevico;AV;Campania;064112;83058 +L461;Tufo;AV;Campania;064113;83010 +L589;Vallata;AV;Campania;064114;83059 +L616;Vallesaccarda;AV;Campania;064115;83050 +L739;Venticano;AV;Campania;064116;83030 +L965;Villamaina;AV;Campania;064117;83050 +L973;Villanova del Battista;AV;Campania;064118;83030 +M130;Volturara Irpina;AV;Campania;064119;83050 +M203;Zungoli;AV;Campania;064120;83030 +M330;Montoro;AV;Campania;064121;83025 +A023;Acerno;SA;Campania;065001;84042 +A091;Agropoli;SA;Campania;065002;84043 +A128;Albanella;SA;Campania;065003;84044 +A186;Alfano;SA;Campania;065004;84040 +A230;Altavilla Silentina;SA;Campania;065005;84045 +A251;Amalfi;SA;Campania;065006;84011 +A294;Angri;SA;Campania;065007;84012 +A343;Aquara;SA;Campania;065008;84020 +A460;Ascea;SA;Campania;065009;84046 +A484;Atena Lucana;SA;Campania;065010;84030 +A487;Atrani;SA;Campania;065011;84010 +A495;Auletta;SA;Campania;065012;84031 +A674;Baronissi;SA;Campania;065013;84081 +A717;Battipaglia;SA;Campania;065014;84091 +A756;Bellosguardo;SA;Campania;065015;84020 +B115;Bracigliano;SA;Campania;065016;84082 +B242;Buccino;SA;Campania;065017;84021 +B266;Buonabitacolo;SA;Campania;065018;84032 +B351;Caggiano;SA;Campania;065019;84030 +B437;Calvanico;SA;Campania;065020;84080 +B476;Camerota;SA;Campania;065021;84059 +B492;Campagna;SA;Campania;065022;84022 +B555;Campora;SA;Campania;065023;84040 +B608;Cannalonga;SA;Campania;065024;84040 +B644;Capaccio Paestum;SA;Campania;065025; +B868;Casalbuono;SA;Campania;065026;84030 +B888;Casaletto Spartano;SA;Campania;065027;84030 +B895;Casal Velino;SA;Campania;065028;84040 +B959;Caselle in Pittari;SA;Campania;065029;84030 +C069;Castelcivita;SA;Campania;065030;84020 +C125;Castellabate;SA;Campania;065031;84048 +C231;Castelnuovo Cilento;SA;Campania;065032;84040 +C235;Castelnuovo di Conza;SA;Campania;065033;84020 +C259;Castel San Giorgio;SA;Campania;065034;84083 +C262;Castel San Lorenzo;SA;Campania;065035;84049 +C306;Castiglione del Genovesi;SA;Campania;065036;84090 +C361;Cava de' Tirreni;SA;Campania;065037;84013 +C444;Celle di Bulgheria;SA;Campania;065038;84040 +C470;Centola;SA;Campania;065039;84051 +C485;Ceraso;SA;Campania;065040;84052 +C584;Cetara;SA;Campania;065041;84010 +C676;Cicerale;SA;Campania;065042;84053 +C879;Colliano;SA;Campania;065043;84020 +C940;Conca dei Marini;SA;Campania;065044;84010 +C973;Controne;SA;Campania;065045;84020 +C974;Contursi Terme;SA;Campania;065046;84024 +C984;Corbara;SA;Campania;065047;84010 +D011;Corleto Monforte;SA;Campania;065048;84020 +D195;Cuccaro Vetere;SA;Campania;065049;84050 +D390;Eboli;SA;Campania;065050;84025 +D527;Felitto;SA;Campania;065051;84055 +D615;Fisciano;SA;Campania;065052;84084 +D826;Furore;SA;Campania;065053;84010 +D832;Futani;SA;Campania;065054;84050 +E026;Giffoni Sei Casali;SA;Campania;065055;84090 +E027;Giffoni Valle Piana;SA;Campania;065056;84095 +E037;Gioi;SA;Campania;065057;84056 +E060;Giungano;SA;Campania;065058;84050 +E365;Ispani;SA;Campania;065059;84050 +E480;Laureana Cilento;SA;Campania;065060;84050 +E485;Laurino;SA;Campania;065061;84057 +E486;Laurito;SA;Campania;065062;84050 +E498;Laviano;SA;Campania;065063;84020 +E767;Lustra;SA;Campania;065064;84050 +E814;Magliano Vetere;SA;Campania;065065;84050 +E839;Maiori;SA;Campania;065066;84010 +F138;Mercato San Severino;SA;Campania;065067;84085 +F223;Minori;SA;Campania;065068;84010 +F278;Moio della Civitella;SA;Campania;065069;84060 +F426;Montano Antilia;SA;Campania;065070;84060 +F479;Montecorice;SA;Campania;065071;84060 +F480;Montecorvino Pugliano;SA;Campania;065072;84090 +F481;Montecorvino Rovella;SA;Campania;065073;84096 +F507;Monteforte Cilento;SA;Campania;065074;84060 +F618;Monte San Giacomo;SA;Campania;065075;84030 +F625;Montesano sulla Marcellana;SA;Campania;065076;84033 +F731;Morigerati;SA;Campania;065077;84030 +F912;Nocera Inferiore;SA;Campania;065078;84014 +F913;Nocera Superiore;SA;Campania;065079;84015 +F967;Novi Velia;SA;Campania;065080;84060 +G011;Ogliastro Cilento;SA;Campania;065081;84061 +G023;Olevano sul Tusciano;SA;Campania;065082;84062 +G039;Oliveto Citra;SA;Campania;065083;84020 +G063;Omignano;SA;Campania;065084;84060 +G121;Orria;SA;Campania;065085;84060 +G192;Ottati;SA;Campania;065086;84020 +G226;Padula;SA;Campania;065087;84034 +G230;Pagani;SA;Campania;065088;84016 +G292;Palomonte;SA;Campania;065089;84020 +G426;Pellezzano;SA;Campania;065090;84080 +G447;Perdifumo;SA;Campania;065091;84060 +G455;Perito;SA;Campania;065092;84060 +G476;Pertosa;SA;Campania;065093;84030 +G509;Petina;SA;Campania;065094;84020 +G538;Piaggine;SA;Campania;065095;84065 +G707;Pisciotta;SA;Campania;065096;84066 +G793;Polla;SA;Campania;065097;84035 +G796;Pollica;SA;Campania;065098;84068 +G834;Pontecagnano Faiano;SA;Campania;065099;84098 +G932;Positano;SA;Campania;065100;84017 +G939;Postiglione;SA;Campania;065101;84026 +G976;Praiano;SA;Campania;065102;84010 +H062;Prignano Cilento;SA;Campania;065103;84060 +H198;Ravello;SA;Campania;065104;84010 +H277;Ricigliano;SA;Campania;065105;84020 +H394;Roccadaspide;SA;Campania;065106;84069 +H412;Roccagloriosa;SA;Campania;065107;84060 +H431;Roccapiemonte;SA;Campania;065108;84086 +H485;Rofrano;SA;Campania;065109;84070 +H503;Romagnano al Monte;SA;Campania;065110;84020 +H564;Roscigno;SA;Campania;065111;84020 +H644;Rutino;SA;Campania;065112;84070 +H654;Sacco;SA;Campania;065113;84070 +H683;Sala Consilina;SA;Campania;065114;84036 +H686;Salento;SA;Campania;065115;84070 +H703;Salerno;SA;Campania;065116;84100,84121-84135 +H732;Salvitelle;SA;Campania;065117;84020 +H800;San Cipriano Picentino;SA;Campania;065118;84099 +H907;San Giovanni a Piro;SA;Campania;065119;84070 +H943;San Gregorio Magno;SA;Campania;065120;84020 +H977;San Mango Piemonte;SA;Campania;065121;84090 +I019;San Marzano sul Sarno;SA;Campania;065122;84010 +I031;San Mauro Cilento;SA;Campania;065123;84070 +I032;San Mauro la Bruca;SA;Campania;065124;84070 +I089;San Pietro al Tanagro;SA;Campania;065125;84030 +I143;San Rufo;SA;Campania;065126;84030 +I253;Santa Marina;SA;Campania;065127;84067 +I278;Sant'Angelo a Fasanella;SA;Campania;065128;84027 +I307;Sant'Arsenio;SA;Campania;065129;84037 +I317;Sant'Egidio del Monte Albino;SA;Campania;065130;84010 +I260;Santomenna;SA;Campania;065131;84020 +I377;San Valentino Torio;SA;Campania;065132;84010 +I410;Sanza;SA;Campania;065133;84030 +I422;Sapri;SA;Campania;065134;84073 +I438;Sarno;SA;Campania;065135;84087 +I451;Sassano;SA;Campania;065136;84038 +I483;Scafati;SA;Campania;065137;84018 +I486;Scala;SA;Campania;065138;84010 +I648;Serramezzana;SA;Campania;065139;84070 +I666;Serre;SA;Campania;065140;84028 +I677;Sessa Cilento;SA;Campania;065141;84074 +I720;Siano;SA;Campania;065142;84088 +M253;Sicignano degli Alburni;SA;Campania;065143;84029 +G887;Stella Cilento;SA;Campania;065144;84070 +I960;Stio;SA;Campania;065145;84075 +D292;Teggiano;SA;Campania;065146;84039 +L212;Torchiara;SA;Campania;065147;84076 +L233;Torraca;SA;Campania;065148;84030 +L274;Torre Orsaia;SA;Campania;065149;84077 +L306;Tortorella;SA;Campania;065150;84030 +L323;Tramonti;SA;Campania;065151;84010 +L377;Trentinara;SA;Campania;065152;84070 +G540;Valle dell'Angelo;SA;Campania;065153;84070 +L628;Vallo della Lucania;SA;Campania;065154;84078 +L656;Valva;SA;Campania;065155;84020 +L835;Vibonati;SA;Campania;065156;84079 +L860;Vietri sul Mare;SA;Campania;065157;84019 +M294;Bellizzi;SA;Campania;065158;84092 +A018;Acciano;AQ;Abruzzo;066001;67020 +A100;Aielli;AQ;Abruzzo;066002;67041 +A187;Alfedena;AQ;Abruzzo;066003;67030 +A318;Anversa degli Abruzzi;AQ;Abruzzo;066004;67030 +A481;Ateleta;AQ;Abruzzo;066005;67030 +A515;Avezzano;AQ;Abruzzo;066006;67051 +A603;Balsorano;AQ;Abruzzo;066007;67052 +A656;Barete;AQ;Abruzzo;066008;67010 +A667;Barisciano;AQ;Abruzzo;066009;67021 +A678;Barrea;AQ;Abruzzo;066010;67030 +A884;Bisegna;AQ;Abruzzo;066011;67050 +B256;Bugnara;AQ;Abruzzo;066012;67030 +B358;Cagnano Amiterno;AQ;Abruzzo;066013;67012 +B382;Calascio;AQ;Abruzzo;066014;67020 +B526;Campo di Giove;AQ;Abruzzo;066015;67030 +B569;Campotosto;AQ;Abruzzo;066016;67013 +B606;Canistro;AQ;Abruzzo;066017;67050 +B624;Cansano;AQ;Abruzzo;066018;67030 +B651;Capestrano;AQ;Abruzzo;066019;67022 +B656;Capistrello;AQ;Abruzzo;066020;67053 +B658;Capitignano;AQ;Abruzzo;066021;67014 +B672;Caporciano;AQ;Abruzzo;066022;67020 +B677;Cappadocia;AQ;Abruzzo;066023;67060 +B725;Carapelle Calvisio;AQ;Abruzzo;066024;67020 +B842;Carsoli;AQ;Abruzzo;066025;67061 +C083;Castel del Monte;AQ;Abruzzo;066026;67023 +C090;Castel di Ieri;AQ;Abruzzo;066027;67020 +C096;Castel di Sangro;AQ;Abruzzo;066028;67031 +C126;Castellafiume;AQ;Abruzzo;066029;67050 +C278;Castelvecchio Calvisio;AQ;Abruzzo;066030;67020 +C279;Castelvecchio Subequo;AQ;Abruzzo;066031;67024 +C426;Celano;AQ;Abruzzo;066032;67043 +C492;Cerchio;AQ;Abruzzo;066033;67044 +C766;Civita d'Antino;AQ;Abruzzo;066034;67050 +C778;Civitella Alfedena;AQ;Abruzzo;066035;67030 +C783;Civitella Roveto;AQ;Abruzzo;066036;67054 +C811;Cocullo;AQ;Abruzzo;066037;67030 +C844;Collarmele;AQ;Abruzzo;066038;67040 +C862;Collelongo;AQ;Abruzzo;066039;67050 +C866;Collepietro;AQ;Abruzzo;066040;67020 +C999;Corfinio;AQ;Abruzzo;066041;67030 +D465;Fagnano Alto;AQ;Abruzzo;066042;67020 +D681;Fontecchio;AQ;Abruzzo;066043;67020 +D736;Fossa;AQ;Abruzzo;066044;67020 +D850;Gagliano Aterno;AQ;Abruzzo;066045;67020 +E040;Gioia dei Marsi;AQ;Abruzzo;066046;67055 +E096;Goriano Sicoli;AQ;Abruzzo;066047;67030 +E307;Introdacqua;AQ;Abruzzo;066048;67030 +A345;L'Aquila;AQ;Abruzzo;066049;67100 +E505;Lecce nei Marsi;AQ;Abruzzo;066050;67050 +E723;Luco dei Marsi;AQ;Abruzzo;066051;67056 +E724;Lucoli;AQ;Abruzzo;066052;67045 +E811;Magliano de' Marsi;AQ;Abruzzo;066053;67062 +F022;Massa d'Albe;AQ;Abruzzo;066054;67050 +M255;Molina Aterno;AQ;Abruzzo;066055;67020 +F595;Montereale;AQ;Abruzzo;066056;67015 +F732;Morino;AQ;Abruzzo;066057;67050 +F852;Navelli;AQ;Abruzzo;066058;67020 +F996;Ocre;AQ;Abruzzo;066059;67040 +G002;Ofena;AQ;Abruzzo;066060;67025 +G079;Opi;AQ;Abruzzo;066061;67030 +G102;Oricola;AQ;Abruzzo;066062;67063 +G142;Ortona dei Marsi;AQ;Abruzzo;066063;67050 +G145;Ortucchio;AQ;Abruzzo;066064;67050 +G200;Ovindoli;AQ;Abruzzo;066065;67046 +G210;Pacentro;AQ;Abruzzo;066066;67030 +G449;Pereto;AQ;Abruzzo;066067;67064 +G484;Pescasseroli;AQ;Abruzzo;066068;67032 +G492;Pescina;AQ;Abruzzo;066069;67057 +G493;Pescocostanzo;AQ;Abruzzo;066070;67033 +G524;Pettorano sul Gizio;AQ;Abruzzo;066071;67034 +G726;Pizzoli;AQ;Abruzzo;066072;67017 +G766;Poggio Picenze;AQ;Abruzzo;066073;67026 +G992;Prata d'Ansidonia;AQ;Abruzzo;066074;67020 +H007;Pratola Peligna;AQ;Abruzzo;066075;67035 +H056;Prezza;AQ;Abruzzo;066076;67030 +H166;Raiano;AQ;Abruzzo;066077;67027 +H353;Rivisondoli;AQ;Abruzzo;066078;67036 +H389;Roccacasale;AQ;Abruzzo;066079;67030 +H399;Rocca di Botte;AQ;Abruzzo;066080;67066 +H400;Rocca di Cambio;AQ;Abruzzo;066081;67047 +H402;Rocca di Mezzo;AQ;Abruzzo;066082;67048 +H429;Rocca Pia;AQ;Abruzzo;066083;67030 +H434;Roccaraso;AQ;Abruzzo;066084;67037 +H772;San Benedetto dei Marsi;AQ;Abruzzo;066085;67058 +H773;San Benedetto in Perillis;AQ;Abruzzo;066086;67020 +H819;San Demetrio ne' Vestini;AQ;Abruzzo;066087;67028 +I121;San Pio delle Camere;AQ;Abruzzo;066088;67020 +I326;Sante Marie;AQ;Abruzzo;066089;67067 +I336;Sant'Eusanio Forconese;AQ;Abruzzo;066090;67020 +I360;Santo Stefano di Sessanio;AQ;Abruzzo;066091;67020 +I389;San Vincenzo Valle Roveto;AQ;Abruzzo;066092;67050 +I501;Scanno;AQ;Abruzzo;066093;67038 +I543;Scontrone;AQ;Abruzzo;066094;67030 +I546;Scoppito;AQ;Abruzzo;066095;67019 +I553;Scurcola Marsicana;AQ;Abruzzo;066096;67068 +I558;Secinaro;AQ;Abruzzo;066097;67029 +I804;Sulmona;AQ;Abruzzo;066098;67039 +L025;Tagliacozzo;AQ;Abruzzo;066099;67069 +L173;Tione degli Abruzzi;AQ;Abruzzo;066100;67020 +L227;Tornimparte;AQ;Abruzzo;066101;67049 +L334;Trasacco;AQ;Abruzzo;066102;67059 +L958;Villalago;AQ;Abruzzo;066103;67030 +M021;Villa Santa Lucia degli Abruzzi;AQ;Abruzzo;066104;67020 +M023;Villa Sant'Angelo;AQ;Abruzzo;066105;67020 +M031;Villavallelonga;AQ;Abruzzo;066106;67050 +M041;Villetta Barrea;AQ;Abruzzo;066107;67030 +M090;Vittorito;AQ;Abruzzo;066108;67030 +A125;Alba Adriatica;TE;Abruzzo;067001;64011 +A270;Ancarano;TE;Abruzzo;067002;64010 +A445;Arsita;TE;Abruzzo;067003;64031 +A488;Atri;TE;Abruzzo;067004;64032 +A692;Basciano;TE;Abruzzo;067005;64030 +A746;Bellante;TE;Abruzzo;067006;64020 +A885;Bisenti;TE;Abruzzo;067007;64033 +B515;Campli;TE;Abruzzo;067008;64012 +B640;Canzano;TE;Abruzzo;067009;64020 +C040;Castel Castagna;TE;Abruzzo;067010;64030 +C128;Castellalto;TE;Abruzzo;067011;64020 +C169;Castelli;TE;Abruzzo;067012;64041 +C316;Castiglione Messer Raimondo;TE;Abruzzo;067013;64034 +C322;Castilenti;TE;Abruzzo;067014;64035 +C449;Cellino Attanasio;TE;Abruzzo;067015;64036 +C517;Cermignano;TE;Abruzzo;067016;64037 +C781;Civitella del Tronto;TE;Abruzzo;067017;64010 +C311;Colledara;TE;Abruzzo;067018;64042 +C901;Colonnella;TE;Abruzzo;067019;64010 +C972;Controguerra;TE;Abruzzo;067020;64010 +D043;Corropoli;TE;Abruzzo;067021;64013 +D076;Cortino;TE;Abruzzo;067022;64040 +D179;Crognaleto;TE;Abruzzo;067023;64043 +D489;Fano Adriano;TE;Abruzzo;067024;64044 +E058;Giulianova;TE;Abruzzo;067025;64021 +E343;Isola del Gran Sasso d'Italia;TE;Abruzzo;067026;64045 +F500;Montefino;TE;Abruzzo;067027;64030 +F690;Montorio al Vomano;TE;Abruzzo;067028;64046 +F747;Morro d'Oro;TE;Abruzzo;067029;64020 +F764;Mosciano Sant'Angelo;TE;Abruzzo;067030;64023 +F870;Nereto;TE;Abruzzo;067031;64015 +F942;Notaresco;TE;Abruzzo;067032;64024 +G437;Penna Sant'Andrea;TE;Abruzzo;067033;64039 +G608;Pietracamela;TE;Abruzzo;067034;64047 +F831;Pineto;TE;Abruzzo;067035;64025 +H440;Rocca Santa Maria;TE;Abruzzo;067036;64010 +F585;Roseto degli Abruzzi;TE;Abruzzo;067037;64026 +I318;Sant'Egidio alla Vibrata;TE;Abruzzo;067038;64016 +I348;Sant'Omero;TE;Abruzzo;067039;64027 +I741;Silvi;TE;Abruzzo;067040;64028 +L103;Teramo;TE;Abruzzo;067041;64100 +L207;Torano Nuovo;TE;Abruzzo;067042;64010 +L295;Torricella Sicura;TE;Abruzzo;067043;64010 +L307;Tortoreto;TE;Abruzzo;067044;64018 +L314;Tossicia;TE;Abruzzo;067045;64049 +L597;Valle Castellana;TE;Abruzzo;067046;64010 +E989;Martinsicuro;TE;Abruzzo;067047;64014 +A008;Abbateggio;PE;Abruzzo;068001;65020 +A120;Alanno;PE;Abruzzo;068002;65020 +A945;Bolognano;PE;Abruzzo;068003;65020 +B193;Brittoli;PE;Abruzzo;068004;65010 +B294;Bussi sul Tirino;PE;Abruzzo;068005;65022 +B681;Cappelle sul Tavo;PE;Abruzzo;068006;65010 +B722;Caramanico Terme;PE;Abruzzo;068007;65023 +B827;Carpineto della Nora;PE;Abruzzo;068008;65010 +C308;Castiglione a Casauria;PE;Abruzzo;068009;65020 +C354;Catignano;PE;Abruzzo;068010;65011 +C474;Cepagatti;PE;Abruzzo;068011;65012 +C750;Città Sant'Angelo;PE;Abruzzo;068012;65013 +C771;Civitaquana;PE;Abruzzo;068013;65010 +C779;Civitella Casanova;PE;Abruzzo;068014;65010 +C853;Collecorvino;PE;Abruzzo;068015;65010 +D078;Corvara;PE;Abruzzo;068016;65020 +D201;Cugnoli;PE;Abruzzo;068017;65020 +D394;Elice;PE;Abruzzo;068018;65010 +D501;Farindola;PE;Abruzzo;068019;65010 +E558;Lettomanoppello;PE;Abruzzo;068020;65020 +E691;Loreto Aprutino;PE;Abruzzo;068021;65014 +E892;Manoppello;PE;Abruzzo;068022;65024 +F441;Montebello di Bertona;PE;Abruzzo;068023;65010 +F646;Montesilvano;PE;Abruzzo;068024;65015 +F765;Moscufo;PE;Abruzzo;068025;65010 +F908;Nocciano;PE;Abruzzo;068026;65010 +G438;Penne;PE;Abruzzo;068027;65017 +G482;Pescara;PE;Abruzzo;068028;65100,65121-65129,65132 +G499;Pescosansonesco;PE;Abruzzo;068029;65020 +G555;Pianella;PE;Abruzzo;068030;65019 +G589;Picciano;PE;Abruzzo;068031;65010 +G621;Pietranico;PE;Abruzzo;068032;65020 +G878;Popoli Terme;PE;Abruzzo;068033; +H425;Roccamorice;PE;Abruzzo;068034;65020 +H562;Rosciano;PE;Abruzzo;068035;65020 +H715;Salle;PE;Abruzzo;068036;65020 +I332;Sant'Eufemia a Maiella;PE;Abruzzo;068037;65020 +I376;San Valentino in Abruzzo Citeriore;PE;Abruzzo;068038;65020 +I482;Scafa;PE;Abruzzo;068039;65027 +I649;Serramonacesca;PE;Abruzzo;068040;65025 +I922;Spoltore;PE;Abruzzo;068041;65010 +L186;Tocco da Casauria;PE;Abruzzo;068042;65028 +L263;Torre de' Passeri;PE;Abruzzo;068043;65029 +L475;Turrivalignani;PE;Abruzzo;068044;65020 +L846;Vicoli;PE;Abruzzo;068045;65010 +L922;Villa Celiera;PE;Abruzzo;068046;65010 +A235;Altino;CH;Abruzzo;069001;66040 +A367;Archi;CH;Abruzzo;069002;66044 +A398;Ari;CH;Abruzzo;069003;66010 +A402;Arielli;CH;Abruzzo;069004;66030 +A485;Atessa;CH;Abruzzo;069005;66041 +A956;Bomba;CH;Abruzzo;069006;66042 +B057;Borrello;CH;Abruzzo;069007;66040 +B238;Bucchianico;CH;Abruzzo;069008;66011 +B268;Montebello sul Sangro;CH;Abruzzo;069009;66040 +B620;Canosa Sannita;CH;Abruzzo;069010;66010 +B826;Carpineto Sinello;CH;Abruzzo;069011;66030 +B853;Carunchio;CH;Abruzzo;069012;66050 +B859;Casacanditella;CH;Abruzzo;069013;66010 +B861;Casalanguida;CH;Abruzzo;069014;66031 +B865;Casalbordino;CH;Abruzzo;069015;66021 +B896;Casalincontrada;CH;Abruzzo;069016;66012 +B985;Casoli;CH;Abruzzo;069017;66043 +C114;Castel Frentano;CH;Abruzzo;069018;66032 +C123;Castelguidone;CH;Abruzzo;069019;66040 +C298;Castiglione Messer Marino;CH;Abruzzo;069020;66033 +C428;Celenza sul Trigno;CH;Abruzzo;069021;66050 +C632;Chieti;CH;Abruzzo;069022;66100 +C768;Civitaluparella;CH;Abruzzo;069023;66040 +C776;Civitella Messer Raimondo;CH;Abruzzo;069024;66010 +C855;Colledimacine;CH;Abruzzo;069025;66010 +C856;Colledimezzo;CH;Abruzzo;069026;66040 +D137;Crecchio;CH;Abruzzo;069027;66014 +D209;Cupello;CH;Abruzzo;069028;66051 +D315;Dogliola;CH;Abruzzo;069029;66050 +D494;Fara Filiorum Petri;CH;Abruzzo;069030;66010 +D495;Fara San Martino;CH;Abruzzo;069031;66015 +D592;Filetto;CH;Abruzzo;069032;66030 +D738;Fossacesia;CH;Abruzzo;069033;66022 +D757;Fraine;CH;Abruzzo;069034;66050 +D763;Francavilla al Mare;CH;Abruzzo;069035;66023 +D796;Fresagrandinaria;CH;Abruzzo;069036;66050 +D803;Frisa;CH;Abruzzo;069037;66030 +D823;Furci;CH;Abruzzo;069038;66050 +D898;Gamberale;CH;Abruzzo;069039;66040 +D996;Gessopalena;CH;Abruzzo;069040;66010 +E052;Gissi;CH;Abruzzo;069041;66052 +E056;Giuliano Teatino;CH;Abruzzo;069042;66010 +E243;Guardiagrele;CH;Abruzzo;069043;66016 +E266;Guilmi;CH;Abruzzo;069044;66050 +E424;Lama dei Peligni;CH;Abruzzo;069045;66010 +E435;Lanciano;CH;Abruzzo;069046;66034 +E531;Lentella;CH;Abruzzo;069047;66050 +E559;Lettopalena;CH;Abruzzo;069048;66010 +E611;Liscia;CH;Abruzzo;069049;66050 +F196;Miglianico;CH;Abruzzo;069050;66010 +F433;Montazzoli;CH;Abruzzo;069051;66030 +F498;Monteferrante;CH;Abruzzo;069052;66040 +F535;Montelapiano;CH;Abruzzo;069053;66040 +F578;Montenerodomo;CH;Abruzzo;069054;66010 +F582;Monteodorisio;CH;Abruzzo;069055;66050 +F785;Mozzagrogna;CH;Abruzzo;069056;66030 +G128;Orsogna;CH;Abruzzo;069057;66036 +G141;Ortona;CH;Abruzzo;069058;66026 +G237;Paglieta;CH;Abruzzo;069059;66020 +G271;Palena;CH;Abruzzo;069060;66017 +G290;Palmoli;CH;Abruzzo;069061;66050 +G294;Palombaro;CH;Abruzzo;069062;66010 +G434;Pennadomo;CH;Abruzzo;069063;66040 +G435;Pennapiedimonte;CH;Abruzzo;069064;66010 +G441;Perano;CH;Abruzzo;069065;66040 +G724;Pizzoferrato;CH;Abruzzo;069066;66040 +G760;Poggiofiorito;CH;Abruzzo;069067;66030 +G799;Pollutri;CH;Abruzzo;069068;66020 +H052;Pretoro;CH;Abruzzo;069069;66010 +H098;Quadri;CH;Abruzzo;069070;66040 +H184;Rapino;CH;Abruzzo;069071;66010 +H320;Ripa Teatina;CH;Abruzzo;069072;66010 +H424;Roccamontepiano;CH;Abruzzo;069073;66010 +H439;Rocca San Giovanni;CH;Abruzzo;069074;66020 +H442;Roccascalegna;CH;Abruzzo;069075;66040 +H448;Roccaspinalveti;CH;Abruzzo;069076;66050 +H495;Roio del Sangro;CH;Abruzzo;069077;66040 +H566;Rosello;CH;Abruzzo;069078;66040 +H784;San Buono;CH;Abruzzo;069079;66050 +H923;San Giovanni Lipioni;CH;Abruzzo;069080;66050 +D690;San Giovanni Teatino;CH;Abruzzo;069081;66020 +H991;San Martino sulla Marrucina;CH;Abruzzo;069082;66010 +I148;San Salvo;CH;Abruzzo;069083;66050 +I244;Santa Maria Imbaro;CH;Abruzzo;069084;66030 +I335;Sant'Eusanio del Sangro;CH;Abruzzo;069085;66037 +I394;San Vito Chietino;CH;Abruzzo;069086;66038 +I520;Scerni;CH;Abruzzo;069087;66020 +I526;Schiavi di Abruzzo;CH;Abruzzo;069088;66045 +L047;Taranta Peligna;CH;Abruzzo;069089;66018 +L194;Tollo;CH;Abruzzo;069090;66010 +L218;Torino di Sangro;CH;Abruzzo;069091;66020 +L224;Tornareccio;CH;Abruzzo;069092;66046 +L253;Torrebruna;CH;Abruzzo;069093;66050 +L284;Torrevecchia Teatina;CH;Abruzzo;069094;66010 +L291;Torricella Peligna;CH;Abruzzo;069095;66019 +L363;Treglio;CH;Abruzzo;069096;66030 +L459;Tufillo;CH;Abruzzo;069097;66050 +L526;Vacri;CH;Abruzzo;069098;66010 +E372;Vasto;CH;Abruzzo;069099;66054 +L961;Villalfonsina;CH;Abruzzo;069100;66020 +L964;Villamagna;CH;Abruzzo;069101;66010 +M022;Villa Santa Maria;CH;Abruzzo;069102;66047 +G613;Pietraferrazzana;CH;Abruzzo;069103;66040 +D480;Fallo;CH;Abruzzo;069104;66040 +A050;Acquaviva Collecroce;CB;Molise;070001;86030 +A616;Baranello;CB;Molise;070002;86011 +A930;Bojano;CB;Molise;070003;86021 +A971;Bonefro;CB;Molise;070004;86041 +B295;Busso;CB;Molise;070005;86010 +B519;Campobasso;CB;Molise;070006;86100 +B522;Campochiaro;CB;Molise;070007;86020 +B528;Campodipietra;CB;Molise;070008;86010 +B544;Campolieto;CB;Molise;070009;86040 +B550;Campomarino;CB;Molise;070010;86042 +B858;Casacalenda;CB;Molise;070011;86043 +B871;Casalciprano;CB;Molise;070012;86010 +C066;Castelbottaccio;CB;Molise;070013;86030 +C175;Castellino del Biferno;CB;Molise;070014;86020 +C197;Castelmauro;CB;Molise;070015;86031 +C346;Castropignano;CB;Molise;070016;86010 +C486;Cercemaggiore;CB;Molise;070017;86012 +C488;Cercepiccola;CB;Molise;070018;86010 +C764;Civitacampomarano;CB;Molise;070019;86030 +C854;Colle d'Anchise;CB;Molise;070020;86020 +C875;Colletorto;CB;Molise;070021;86044 +C772;Duronia;CB;Molise;070022;86020 +D550;Ferrazzano;CB;Molise;070023;86010 +D737;Fossalto;CB;Molise;070024;86020 +D896;Gambatesa;CB;Molise;070025;86013 +E030;Gildone;CB;Molise;070026;86010 +E244;Guardialfiera;CB;Molise;070027;86030 +E248;Guardiaregia;CB;Molise;070028;86014 +E259;Guglionesi;CB;Molise;070029;86034 +E381;Jelsi;CB;Molise;070030;86015 +E456;Larino;CB;Molise;070031;86035 +E599;Limosano;CB;Molise;070032;86022 +E722;Lucito;CB;Molise;070033;86030 +E748;Lupara;CB;Molise;070034;86030 +E780;Macchia Valfortore;CB;Molise;070035;86040 +E799;Mafalda;CB;Molise;070036;86030 +F055;Matrice;CB;Molise;070037;86030 +F233;Mirabello Sannitico;CB;Molise;070038;86010 +F294;Molise;CB;Molise;070039;86020 +F322;Monacilioni;CB;Molise;070040;86040 +F391;Montagano;CB;Molise;070041;86023 +F475;Montecilfone;CB;Molise;070042;86032 +F495;Montefalcone nel Sannio;CB;Molise;070043;86033 +F548;Montelongo;CB;Molise;070044;86040 +F569;Montemitro;CB;Molise;070045;86030 +F576;Montenero di Bisaccia;CB;Molise;070046;86036 +F689;Montorio nei Frentani;CB;Molise;070047;86040 +F748;Morrone del Sannio;CB;Molise;070048;86040 +G086;Oratino;CB;Molise;070049;86010 +G257;Palata;CB;Molise;070050;86037 +G506;Petacciato;CB;Molise;070051;86038 +G512;Petrella Tifernina;CB;Molise;070052;86024 +G609;Pietracatella;CB;Molise;070053;86040 +G610;Pietracupa;CB;Molise;070054;86020 +G910;Portocannone;CB;Molise;070055;86045 +H083;Provvidenti;CB;Molise;070056;86040 +H273;Riccia;CB;Molise;070057;86016 +H311;Ripabottoni;CB;Molise;070058;86040 +H313;Ripalimosani;CB;Molise;070059;86025 +H454;Roccavivara;CB;Molise;070060;86020 +H589;Rotello;CB;Molise;070061;86040 +H693;Salcito;CB;Molise;070062;86026 +H782;San Biase;CB;Molise;070063;86020 +H833;San Felice del Molise;CB;Molise;070064;86030 +H867;San Giacomo degli Schiavoni;CB;Molise;070065;86030 +H920;San Giovanni in Galdo;CB;Molise;070066;86010 +H928;San Giuliano del Sannio;CB;Molise;070067;86010 +H929;San Giuliano di Puglia;CB;Molise;070068;86040 +H990;San Martino in Pensilis;CB;Molise;070069;86046 +I023;San Massimo;CB;Molise;070070;86027 +I122;San Polo Matese;CB;Molise;070071;86020 +I181;Santa Croce di Magliano;CB;Molise;070072;86047 +I289;Sant'Angelo Limosano;CB;Molise;070073;86020 +I320;Sant'Elia a Pianisi;CB;Molise;070074;86048 +I618;Sepino;CB;Molise;070075;86017 +I910;Spinete;CB;Molise;070076;86020 +L069;Tavenna;CB;Molise;070077;86030 +L113;Termoli;CB;Molise;070078;86039 +L215;Torella del Sannio;CB;Molise;070079;86028 +L230;Toro;CB;Molise;070080;86018 +L435;Trivento;CB;Molise;070081;86029 +L458;Tufara;CB;Molise;070082;86010 +L505;Ururi;CB;Molise;070083;86049 +M057;Vinchiaturo;CB;Molise;070084;86019 +A015;Accadia;FG;Puglia;071001;71021 +A150;Alberona;FG;Puglia;071002;71031 +A320;Anzano di Puglia;FG;Puglia;071003;71020 +A339;Apricena;FG;Puglia;071004;71011 +A463;Ascoli Satriano;FG;Puglia;071005;71022 +A854;Biccari;FG;Puglia;071006;71032 +B104;Bovino;FG;Puglia;071007;71023 +B357;Cagnano Varano;FG;Puglia;071008;71010 +B584;Candela;FG;Puglia;071009;71024 +B724;Carapelle;FG;Puglia;071010;71041 +B784;Carlantino;FG;Puglia;071011;71030 +B829;Carpino;FG;Puglia;071012;71010 +B904;Casalnuovo Monterotaro;FG;Puglia;071013;71033 +B917;Casalvecchio di Puglia;FG;Puglia;071014;71030 +C198;Castelluccio dei Sauri;FG;Puglia;071015;71025 +C202;Castelluccio Valmaggiore;FG;Puglia;071016;71020 +C222;Castelnuovo della Daunia;FG;Puglia;071017;71034 +C429;Celenza Valfortore;FG;Puglia;071018;71035 +C442;Celle di San Vito;FG;Puglia;071019;71020 +C514;Cerignola;FG;Puglia;071020;71042 +C633;Chieuti;FG;Puglia;071021;71010 +D269;Deliceto;FG;Puglia;071022;71026 +D459;Faeto;FG;Puglia;071023;71020 +D643;Foggia;FG;Puglia;071024;71100,71121-71122 +E332;Ischitella;FG;Puglia;071025;71010 +E363;Isole Tremiti;FG;Puglia;071026;71040 +E549;Lesina;FG;Puglia;071027;71010 +E716;Lucera;FG;Puglia;071028;71036 +E885;Manfredonia;FG;Puglia;071029;71043 +F059;Mattinata;FG;Puglia;071031;71030 +F538;Monteleone di Puglia;FG;Puglia;071032;71020 +F631;Monte Sant'Angelo;FG;Puglia;071033;71037 +F777;Motta Montecorvino;FG;Puglia;071034;71030 +G125;Orsara di Puglia;FG;Puglia;071035;71027 +G131;Orta Nova;FG;Puglia;071036;71045 +G312;Panni;FG;Puglia;071037;71020 +G487;Peschici;FG;Puglia;071038;71010 +G604;Pietramontecorvino;FG;Puglia;071039;71038 +G761;Poggio Imperiale;FG;Puglia;071040;71010 +H287;Rignano Garganico;FG;Puglia;071041;71010 +H467;Rocchetta Sant'Antonio;FG;Puglia;071042;71020 +H480;Rodi Garganico;FG;Puglia;071043;71012 +H568;Roseto Valfortore;FG;Puglia;071044;71039 +H926;San Giovanni Rotondo;FG;Puglia;071046;71013 +H985;San Marco in Lamis;FG;Puglia;071047;71014 +H986;San Marco la Catola;FG;Puglia;071048;71030 +I054;San Nicandro Garganico;FG;Puglia;071049;71015 +I072;San Paolo di Civitate;FG;Puglia;071050;71010 +I158;San Severo;FG;Puglia;071051;71016 +I193;Sant'Agata di Puglia;FG;Puglia;071052;71028 +I641;Serracapriola;FG;Puglia;071053;71010 +I962;Stornara;FG;Puglia;071054;71047 +I963;Stornarella;FG;Puglia;071055;71048 +L273;Torremaggiore;FG;Puglia;071056;71017 +L447;Troia;FG;Puglia;071058;71029 +L842;Vico del Gargano;FG;Puglia;071059;71018 +L858;Vieste;FG;Puglia;071060;71019 +M131;Volturara Appula;FG;Puglia;071061;71030 +M132;Volturino;FG;Puglia;071062;71030 +M266;Ordona;FG;Puglia;071063;71040 +M267;Zapponeta;FG;Puglia;071064;71030 +A048;Acquaviva delle Fonti;BA;Puglia;072001;70021 +A055;Adelfia;BA;Puglia;072002;70010 +A149;Alberobello;BA;Puglia;072003;70011 +A225;Altamura;BA;Puglia;072004;70022 +A662;Bari;BA;Puglia;072006;70100,70121-70132 +A874;Binetto;BA;Puglia;072008;70020 +A892;Bitetto;BA;Puglia;072010;70020 +A893;Bitonto;BA;Puglia;072011;70032 +A894;Bitritto;BA;Puglia;072012;70020 +B716;Capurso;BA;Puglia;072014;70010 +B923;Casamassima;BA;Puglia;072015;70010 +B998;Cassano delle Murge;BA;Puglia;072016;70020 +C134;Castellana Grotte;BA;Puglia;072017;70013 +C436;Cellamare;BA;Puglia;072018;70010 +C975;Conversano;BA;Puglia;072019;70014 +C983;Corato;BA;Puglia;072020;70033 +E038;Gioia del Colle;BA;Puglia;072021;70023 +E047;Giovinazzo;BA;Puglia;072022;70054 +E155;Gravina in Puglia;BA;Puglia;072023;70024 +E223;Grumo Appula;BA;Puglia;072024;70025 +E645;Locorotondo;BA;Puglia;072025;70010 +F262;Modugno;BA;Puglia;072027;70026 +F280;Mola di Bari;BA;Puglia;072028;70042 +F284;Molfetta;BA;Puglia;072029;70056 +F376;Monopoli;BA;Puglia;072030;70043 +F915;Noci;BA;Puglia;072031;70015 +F923;Noicattaro;BA;Puglia;072032;70016 +G291;Palo del Colle;BA;Puglia;072033;70027 +G769;Poggiorsini;BA;Puglia;072034;70020 +G787;Polignano a Mare;BA;Puglia;072035;70044 +H096;Putignano;BA;Puglia;072036;70017 +H643;Rutigliano;BA;Puglia;072037;70018 +H645;Ruvo di Puglia;BA;Puglia;072038;70037 +H749;Sammichele di Bari;BA;Puglia;072039;70010 +I053;Sannicandro di Bari;BA;Puglia;072040;70028 +I330;Santeramo in Colle;BA;Puglia;072041;70029 +L109;Terlizzi;BA;Puglia;072043;70038 +L220;Toritto;BA;Puglia;072044;70020 +L425;Triggiano;BA;Puglia;072046;70019 +L472;Turi;BA;Puglia;072047;70010 +L571;Valenzano;BA;Puglia;072048;70010 +A514;Avetrana;TA;Puglia;073001;74020 +B808;Carosino;TA;Puglia;073002;74021 +C136;Castellaneta;TA;Puglia;073003;74011 +D171;Crispiano;TA;Puglia;073004;74012 +D463;Faggiano;TA;Puglia;073005;74020 +D754;Fragagnano;TA;Puglia;073006;74022 +E036;Ginosa;TA;Puglia;073007;74013 +E205;Grottaglie;TA;Puglia;073008;74023 +E469;Laterza;TA;Puglia;073009;74014 +E537;Leporano;TA;Puglia;073010;74020 +E630;Lizzano;TA;Puglia;073011;74020 +E882;Manduria;TA;Puglia;073012;74024 +E986;Martina Franca;TA;Puglia;073013;74015 +E995;Maruggio;TA;Puglia;073014;74020 +F027;Massafra;TA;Puglia;073015;74016 +F531;Monteiasi;TA;Puglia;073016;74020 +F563;Montemesola;TA;Puglia;073017;74020 +F587;Monteparano;TA;Puglia;073018;74020 +F784;Mottola;TA;Puglia;073019;74017 +G251;Palagianello;TA;Puglia;073020;74018 +G252;Palagiano;TA;Puglia;073021;74019 +H090;Pulsano;TA;Puglia;073022;74026 +H409;Roccaforzata;TA;Puglia;073023;74020 +H882;San Giorgio Ionico;TA;Puglia;073024;74027 +I018;San Marzano di San Giuseppe;TA;Puglia;073025;74020 +I467;Sava;TA;Puglia;073026;74028 +L049;Taranto;TA;Puglia;073027;74100,74121-74123 +L294;Torricella;TA;Puglia;073028;74020 +M298;Statte;TA;Puglia;073029;74010 +B180;Brindisi;BR;Puglia;074001;72100 +B809;Carovigno;BR;Puglia;074002;72012 +C424;Ceglie Messapica;BR;Puglia;074003;72013 +C448;Cellino San Marco;BR;Puglia;074004;72020 +C741;Cisternino;BR;Puglia;074005;72014 +D422;Erchie;BR;Puglia;074006;72020 +D508;Fasano;BR;Puglia;074007;72015 +D761;Francavilla Fontana;BR;Puglia;074008;72021 +E471;Latiano;BR;Puglia;074009;72022 +F152;Mesagne;BR;Puglia;074010;72023 +G098;Oria;BR;Puglia;074011;72024 +G187;Ostuni;BR;Puglia;074012;72017 +H822;San Donaci;BR;Puglia;074013;72025 +I045;San Michele Salentino;BR;Puglia;074014;72018 +I066;San Pancrazio Salentino;BR;Puglia;074015;72026 +I119;San Pietro Vernotico;BR;Puglia;074016;72027 +I396;San Vito dei Normanni;BR;Puglia;074017;72019 +L213;Torchiarolo;BR;Puglia;074018;72020 +L280;Torre Santa Susanna;BR;Puglia;074019;72028 +L920;Villa Castelli;BR;Puglia;074020;72029 +A184;Alessano;LE;Puglia;075002;73031 +A185;Alezio;LE;Puglia;075003;73011 +A208;Alliste;LE;Puglia;075004;73040 +A281;Andrano;LE;Puglia;075005;73032 +A350;Aradeo;LE;Puglia;075006;73040 +A425;Arnesano;LE;Puglia;075007;73010 +A572;Bagnolo del Salento;LE;Puglia;075008;73020 +B086;Botrugno;LE;Puglia;075009;73020 +B413;Calimera;LE;Puglia;075010;73021 +B506;Campi Salentina;LE;Puglia;075011;73012 +B616;Cannole;LE;Puglia;075012;73020 +B690;Caprarica di Lecce;LE;Puglia;075013;73010 +B792;Carmiano;LE;Puglia;075014;73041 +B822;Carpignano Salentino;LE;Puglia;075015;73020 +B936;Casarano;LE;Puglia;075016;73042 +C334;Castri di Lecce;LE;Puglia;075017;73020 +C335;Castrignano de' Greci;LE;Puglia;075018;73020 +C336;Castrignano del Capo;LE;Puglia;075019;73040 +C377;Cavallino;LE;Puglia;075020;73020 +C865;Collepasso;LE;Puglia;075021;73040 +C978;Copertino;LE;Puglia;075022;73043 +D006;Corigliano d'Otranto;LE;Puglia;075023;73022 +D044;Corsano;LE;Puglia;075024;73033 +D223;Cursi;LE;Puglia;075025;73020 +D237;Cutrofiano;LE;Puglia;075026;73020 +D305;Diso;LE;Puglia;075027;73030 +D851;Gagliano del Capo;LE;Puglia;075028;73034 +D862;Galatina;LE;Puglia;075029;73013 +D863;Galatone;LE;Puglia;075030;73044 +D883;Gallipoli;LE;Puglia;075031;73014 +E053;Giuggianello;LE;Puglia;075032;73030 +E061;Giurdignano;LE;Puglia;075033;73020 +E227;Guagnano;LE;Puglia;075034;73010 +E506;Lecce;LE;Puglia;075035;73100 +E538;Lequile;LE;Puglia;075036;73010 +E563;Leverano;LE;Puglia;075037;73045 +E629;Lizzanello;LE;Puglia;075038;73023 +E815;Maglie;LE;Puglia;075039;73024 +E979;Martano;LE;Puglia;075040;73025 +E984;Martignano;LE;Puglia;075041;73020 +F054;Matino;LE;Puglia;075042;73046 +F101;Melendugno;LE;Puglia;075043;73026 +F109;Melissano;LE;Puglia;075044;73040 +F117;Melpignano;LE;Puglia;075045;73020 +F194;Miggiano;LE;Puglia;075046;73035 +F221;Minervino di Lecce;LE;Puglia;075047;73027 +F604;Monteroni di Lecce;LE;Puglia;075048;73047 +F623;Montesano Salentino;LE;Puglia;075049;73030 +F716;Morciano di Leuca;LE;Puglia;075050;73040 +F816;Muro Leccese;LE;Puglia;075051;73036 +F842;Nardò;LE;Puglia;075052;73048 +F881;Neviano;LE;Puglia;075053;73040 +F916;Nociglia;LE;Puglia;075054;73020 +F970;Novoli;LE;Puglia;075055;73051 +G136;Ortelle;LE;Puglia;075056;73030 +G188;Otranto;LE;Puglia;075057;73028 +G285;Palmariggi;LE;Puglia;075058;73020 +G325;Parabita;LE;Puglia;075059;73052 +G378;Patù;LE;Puglia;075060;73053 +G751;Poggiardo;LE;Puglia;075061;73037 +H147;Racale;LE;Puglia;075063;73055 +H632;Ruffano;LE;Puglia;075064;73049 +H708;Salice Salentino;LE;Puglia;075065;73015 +H729;Salve;LE;Puglia;075066;73050 +H757;Sanarica;LE;Puglia;075067;73030 +H793;San Cesario di Lecce;LE;Puglia;075068;73016 +H826;San Donato di Lecce;LE;Puglia;075069;73010 +I059;Sannicola;LE;Puglia;075070;73017 +I115;San Pietro in Lama;LE;Puglia;075071;73010 +I172;Santa Cesarea Terme;LE;Puglia;075072;73020 +I549;Scorrano;LE;Puglia;075073;73020 +I559;Seclì;LE;Puglia;075074;73050 +I780;Sogliano Cavour;LE;Puglia;075075;73010 +I800;Soleto;LE;Puglia;075076;73010 +I887;Specchia;LE;Puglia;075077;73040 +I923;Spongano;LE;Puglia;075078;73038 +I930;Squinzano;LE;Puglia;075079;73018 +I950;Sternatia;LE;Puglia;075080;73010 +L008;Supersano;LE;Puglia;075081;73040 +L010;Surano;LE;Puglia;075082;73030 +L011;Surbo;LE;Puglia;075083;73010 +L064;Taurisano;LE;Puglia;075084;73056 +L074;Taviano;LE;Puglia;075085;73057 +L166;Tiggiano;LE;Puglia;075086;73030 +L383;Trepuzzi;LE;Puglia;075087;73019 +L419;Tricase;LE;Puglia;075088;73039 +L462;Tuglie;LE;Puglia;075089;73058 +L484;Ugento;LE;Puglia;075090;73059 +L485;Uggiano la Chiesa;LE;Puglia;075091;73020 +L711;Veglie;LE;Puglia;075092;73010 +L776;Vernole;LE;Puglia;075093;73029 +M187;Zollino;LE;Puglia;075094;73010 +M264;San Cassiano;LE;Puglia;075095;73020 +M261;Castro;LE;Puglia;075096; +M263;Porto Cesareo;LE;Puglia;075097;73010 +M428;Presicce-Acquarica;LE;Puglia;075098; +A013;Abriola;PZ;Basilicata;076001;85010 +A020;Acerenza;PZ;Basilicata;076002;85011 +A131;Albano di Lucania;PZ;Basilicata;076003;85010 +A321;Anzi;PZ;Basilicata;076004;85010 +A415;Armento;PZ;Basilicata;076005;85010 +A482;Atella;PZ;Basilicata;076006;85020 +A519;Avigliano;PZ;Basilicata;076007;85021 +A604;Balvano;PZ;Basilicata;076008;85050 +A612;Banzi;PZ;Basilicata;076009;85010 +A615;Baragiano;PZ;Basilicata;076010;85050 +A666;Barile;PZ;Basilicata;076011;85022 +A743;Bella;PZ;Basilicata;076012;85051 +B173;Brienza;PZ;Basilicata;076013;85050 +B181;Brindisi Montagna;PZ;Basilicata;076014;85010 +B440;Calvello;PZ;Basilicata;076015;85010 +B443;Calvera;PZ;Basilicata;076016;85030 +B549;Campomaggiore;PZ;Basilicata;076017;85010 +B580;Cancellara;PZ;Basilicata;076018;85010 +B743;Carbone;PZ;Basilicata;076019;85030 +B906;San Paolo Albanese;PZ;Basilicata;076020;85030 +C120;Castelgrande;PZ;Basilicata;076021;85050 +C199;Castelluccio Inferiore;PZ;Basilicata;076022;85040 +C201;Castelluccio Superiore;PZ;Basilicata;076023;85040 +C209;Castelmezzano;PZ;Basilicata;076024;85010 +C271;Castelsaraceno;PZ;Basilicata;076025;85031 +C345;Castronuovo di Sant'Andrea;PZ;Basilicata;076026;85030 +C539;Cersosimo;PZ;Basilicata;076027;85030 +C619;Chiaromonte;PZ;Basilicata;076028;85032 +D010;Corleto Perticara;PZ;Basilicata;076029;85012 +D414;Episcopia;PZ;Basilicata;076030;85033 +D497;Fardella;PZ;Basilicata;076031;85034 +D593;Filiano;PZ;Basilicata;076032;85020 +D696;Forenza;PZ;Basilicata;076033;85023 +D766;Francavilla in Sinni;PZ;Basilicata;076034;85034 +D876;Gallicchio;PZ;Basilicata;076035;85010 +D971;Genzano di Lucania;PZ;Basilicata;076036;85013 +E221;Grumento Nova;PZ;Basilicata;076037;85050 +E246;Guardia Perticara;PZ;Basilicata;076038;85010 +E409;Lagonegro;PZ;Basilicata;076039;85042 +E474;Latronico;PZ;Basilicata;076040;85043 +E482;Laurenzana;PZ;Basilicata;076041;85014 +E483;Lauria;PZ;Basilicata;076042;85044 +E493;Lavello;PZ;Basilicata;076043;85024 +E919;Maratea;PZ;Basilicata;076044;85046 +E976;Marsico Nuovo;PZ;Basilicata;076045;85052 +E977;Marsicovetere;PZ;Basilicata;076046;85050 +F006;Maschito;PZ;Basilicata;076047;85020 +F104;Melfi;PZ;Basilicata;076048;85025 +F249;Missanello;PZ;Basilicata;076049;85010 +F295;Moliterno;PZ;Basilicata;076050;85047 +F568;Montemilone;PZ;Basilicata;076051;85020 +F573;Montemurro;PZ;Basilicata;076052;85053 +F817;Muro Lucano;PZ;Basilicata;076053;85054 +F866;Nemoli;PZ;Basilicata;076054;85040 +F917;Noepoli;PZ;Basilicata;076055;85035 +G081;Oppido Lucano;PZ;Basilicata;076056;85015 +G261;Palazzo San Gervasio;PZ;Basilicata;076057;85026 +G496;Pescopagano;PZ;Basilicata;076058;85020 +G590;Picerno;PZ;Basilicata;076059;85055 +G616;Pietragalla;PZ;Basilicata;076060;85016 +G623;Pietrapertosa;PZ;Basilicata;076061;85010 +G663;Pignola;PZ;Basilicata;076062;85010 +G942;Potenza;PZ;Basilicata;076063;85100 +H186;Rapolla;PZ;Basilicata;076064;85027 +H187;Rapone;PZ;Basilicata;076065;85020 +H307;Rionero in Vulture;PZ;Basilicata;076066;85028 +H312;Ripacandida;PZ;Basilicata;076067;85020 +H348;Rivello;PZ;Basilicata;076068;85040 +H426;Roccanova;PZ;Basilicata;076069;85036 +H590;Rotonda;PZ;Basilicata;076070;85048 +H641;Ruoti;PZ;Basilicata;076071;85056 +H646;Ruvo del Monte;PZ;Basilicata;076072;85020 +H795;San Chirico Nuovo;PZ;Basilicata;076073;85010 +H796;San Chirico Raparo;PZ;Basilicata;076074;85030 +H808;San Costantino Albanese;PZ;Basilicata;076075;85030 +H831;San Fele;PZ;Basilicata;076076;85020 +H994;San Martino d'Agri;PZ;Basilicata;076077;85030 +I157;San Severino Lucano;PZ;Basilicata;076078;85030 +I288;Sant'Angelo Le Fratte;PZ;Basilicata;076079;85050 +I305;Sant'Arcangelo;PZ;Basilicata;076080;85037 +I426;Sarconi;PZ;Basilicata;076081;85050 +I457;Sasso di Castalda;PZ;Basilicata;076082;85050 +G614;Satriano di Lucania;PZ;Basilicata;076083;85050 +H730;Savoia di Lucania;PZ;Basilicata;076084;85050 +I610;Senise;PZ;Basilicata;076085;85038 +I917;Spinoso;PZ;Basilicata;076086;85039 +L082;Teana;PZ;Basilicata;076087;85032 +L126;Terranova di Pollino;PZ;Basilicata;076088;85030 +L181;Tito;PZ;Basilicata;076089;85050 +L197;Tolve;PZ;Basilicata;076090;85017 +L326;Tramutola;PZ;Basilicata;076091;85057 +L357;Trecchina;PZ;Basilicata;076092;85049 +L439;Trivigno;PZ;Basilicata;076093;85018 +L532;Vaglio Basilicata;PZ;Basilicata;076094;85010 +L738;Venosa;PZ;Basilicata;076095;85029 +L859;Vietri di Potenza;PZ;Basilicata;076096;85058 +L873;Viggianello;PZ;Basilicata;076097;85040 +L874;Viggiano;PZ;Basilicata;076098;85059 +E033;Ginestra;PZ;Basilicata;076099;85020 +M269;Paterno;PZ;Basilicata;076100;85050 +A017;Accettura;MT;Basilicata;077001;75011 +A196;Aliano;MT;Basilicata;077002;75010 +A801;Bernalda;MT;Basilicata;077003;75012 +B391;Calciano;MT;Basilicata;077004;75010 +C723;Cirigliano;MT;Basilicata;077005;75010 +C888;Colobraro;MT;Basilicata;077006;75021 +D128;Craco;MT;Basilicata;077007;75010 +D547;Ferrandina;MT;Basilicata;077008;75013 +D909;Garaguso;MT;Basilicata;077009;75010 +E093;Gorgoglione;MT;Basilicata;077010;75010 +E147;Grassano;MT;Basilicata;077011;75014 +E213;Grottole;MT;Basilicata;077012;75010 +E326;Irsina;MT;Basilicata;077013;75022 +F052;Matera;MT;Basilicata;077014;75100 +F201;Miglionico;MT;Basilicata;077015;75010 +F399;Montalbano Jonico;MT;Basilicata;077016;75023 +F637;Montescaglioso;MT;Basilicata;077017;75024 +A942;Nova Siri;MT;Basilicata;077018;75020 +G037;Oliveto Lucano;MT;Basilicata;077019;75010 +G712;Pisticci;MT;Basilicata;077020;75015 +G786;Policoro;MT;Basilicata;077021;75025 +G806;Pomarico;MT;Basilicata;077022;75016 +H591;Rotondella;MT;Basilicata;077023;75026 +H687;Salandra;MT;Basilicata;077024;75017 +H888;San Giorgio Lucano;MT;Basilicata;077025;75027 +I029;San Mauro Forte;MT;Basilicata;077026;75010 +I954;Stigliano;MT;Basilicata;077027;75018 +L418;Tricarico;MT;Basilicata;077028;75019 +L477;Tursi;MT;Basilicata;077029;75028 +D513;Valsinni;MT;Basilicata;077030;75029 +M256;Scanzano Jonico;MT;Basilicata;077031;75020 +A033;Acquaformosa;CS;Calabria;078001;87010 +A041;Acquappesa;CS;Calabria;078002;87020 +A053;Acri;CS;Calabria;078003;87041 +A102;Aiello Calabro;CS;Calabria;078004;87031 +A105;Aieta;CS;Calabria;078005;87020 +A160;Albidona;CS;Calabria;078006;87070 +A183;Alessandria del Carretto;CS;Calabria;078007;87070 +A234;Altilia;CS;Calabria;078008;87040 +A240;Altomonte;CS;Calabria;078009;87042 +A253;Amantea;CS;Calabria;078010;87032 +A263;Amendolara;CS;Calabria;078011;87071 +A340;Aprigliano;CS;Calabria;078012;87051 +A762;Belmonte Calabro;CS;Calabria;078013;87033 +A768;Belsito;CS;Calabria;078014;87030 +A773;Belvedere Marittimo;CS;Calabria;078015;87021 +A842;Bianchi;CS;Calabria;078016;87050 +A887;Bisignano;CS;Calabria;078017;87043 +A912;Bocchigliero;CS;Calabria;078018;87060 +A973;Bonifati;CS;Calabria;078019;87020 +B270;Buonvicino;CS;Calabria;078020;87020 +B424;Calopezzati;CS;Calabria;078021;87060 +B426;Caloveto;CS;Calabria;078022;87060 +B500;Campana;CS;Calabria;078023;87061 +B607;Canna;CS;Calabria;078024;87070 +B774;Cariati;CS;Calabria;078025;87062 +B802;Carolei;CS;Calabria;078026;87030 +B813;Carpanzano;CS;Calabria;078027;87050 +C002;Cassano all'Ionio;CS;Calabria;078029; +C301;Castiglione Cosentino;CS;Calabria;078030;87040 +C108;Castrolibero;CS;Calabria;078031;87040 +C348;Castroregio;CS;Calabria;078032;87070 +C349;Castrovillari;CS;Calabria;078033;87012 +C430;Celico;CS;Calabria;078034;87053 +C437;Cellara;CS;Calabria;078035;87050 +C489;Cerchiara di Calabria;CS;Calabria;078036;87070 +C515;Cerisano;CS;Calabria;078037;87044 +C554;Cervicati;CS;Calabria;078038;87010 +C560;Cerzeto;CS;Calabria;078039;87040 +C588;Cetraro;CS;Calabria;078040;87022 +C763;Civita;CS;Calabria;078041;87010 +C795;Cleto;CS;Calabria;078042;87030 +C905;Colosimi;CS;Calabria;078043;87050 +D086;Cosenza;CS;Calabria;078045;87100 +D180;Cropalati;CS;Calabria;078046;87060 +D184;Crosia;CS;Calabria;078047;87060 +D289;Diamante;CS;Calabria;078048;87023 +D304;Dipignano;CS;Calabria;078049;87045 +D328;Domanico;CS;Calabria;078050;87030 +D464;Fagnano Castello;CS;Calabria;078051;87013 +D473;Falconara Albanese;CS;Calabria;078052;87030 +D582;Figline Vegliaturo;CS;Calabria;078053;87050 +D614;Firmo;CS;Calabria;078054;87010 +D624;Fiumefreddo Bruzio;CS;Calabria;078055;87030 +D764;Francavilla Marittima;CS;Calabria;078056;87072 +D774;Frascineto;CS;Calabria;078057;87010 +D828;Fuscaldo;CS;Calabria;078058;87024 +E180;Grimaldi;CS;Calabria;078059;87034 +E185;Grisolia;CS;Calabria;078060;87020 +E242;Guardia Piemontese;CS;Calabria;078061;87020 +E407;Lago;CS;Calabria;078062;87035 +E417;Laino Borgo;CS;Calabria;078063;87014 +E419;Laino Castello;CS;Calabria;078064;87015 +E450;Lappano;CS;Calabria;078065;87050 +E475;Lattarico;CS;Calabria;078066;87010 +E677;Longobardi;CS;Calabria;078067;87030 +E678;Longobucco;CS;Calabria;078068;87066 +E745;Lungro;CS;Calabria;078069;87010 +E773;Luzzi;CS;Calabria;078070;87040 +E835;Maierà;CS;Calabria;078071;87020 +E859;Malito;CS;Calabria;078072;87030 +E872;Malvito;CS;Calabria;078073;87010 +E878;Mandatoriccio;CS;Calabria;078074;87060 +E888;Mangone;CS;Calabria;078075;87050 +E914;Marano Marchesato;CS;Calabria;078076;87040 +E915;Marano Principato;CS;Calabria;078077;87040 +F001;Marzi;CS;Calabria;078078;87050 +F125;Mendicino;CS;Calabria;078079;87040 +F370;Mongrassano;CS;Calabria;078080;87040 +F416;Montalto Uffugo;CS;Calabria;078081;87046 +F519;Montegiordano;CS;Calabria;078082;87070 +F708;Morano Calabro;CS;Calabria;078083;87016 +F735;Mormanno;CS;Calabria;078084;87026 +F775;Mottafollone;CS;Calabria;078085;87010 +F907;Nocara;CS;Calabria;078086;87070 +G110;Oriolo;CS;Calabria;078087;87073 +G129;Orsomarso;CS;Calabria;078088;87020 +G298;Paludi;CS;Calabria;078089;87060 +G307;Panettieri;CS;Calabria;078090;87050 +G317;Paola;CS;Calabria;078091;87027 +G320;Papasidero;CS;Calabria;078092;87020 +G331;Parenti;CS;Calabria;078093;87040 +G372;Paterno Calabro;CS;Calabria;078094;87040 +G411;Pedivigliano;CS;Calabria;078096;87050 +G553;Piane Crati;CS;Calabria;078097;87050 +G615;Pietrafitta;CS;Calabria;078098;87050 +G622;Pietrapaola;CS;Calabria;078099;87060 +G733;Plataci;CS;Calabria;078100;87070 +G975;Praia a Mare;CS;Calabria;078101;87028 +H235;Rende;CS;Calabria;078102;87036 +H416;Rocca Imperiale;CS;Calabria;078103;87074 +H488;Roggiano Gravina;CS;Calabria;078104;87017 +H490;Rogliano;CS;Calabria;078105;87054 +H565;Rose;CS;Calabria;078106;87040 +H572;Roseto Capo Spulico;CS;Calabria;078107;87070 +H585;Rota Greca;CS;Calabria;078109;87010 +H621;Rovito;CS;Calabria;078110;87050 +H765;San Basile;CS;Calabria;078111;87010 +H774;San Benedetto Ullano;CS;Calabria;078112;87040 +H806;San Cosmo Albanese;CS;Calabria;078113;87060 +H818;San Demetrio Corone;CS;Calabria;078114;87069 +H825;San Donato di Ninea;CS;Calabria;078115;87010 +H841;San Fili;CS;Calabria;078116;87037 +H877;Sangineto;CS;Calabria;078117;87020 +H881;San Giorgio Albanese;CS;Calabria;078118;87060 +H919;San Giovanni in Fiore;CS;Calabria;078119;87055 +H961;San Lorenzo Bellizzi;CS;Calabria;078120;87070 +H962;San Lorenzo del Vallo;CS;Calabria;078121;87040 +H971;San Lucido;CS;Calabria;078122;87038 +H981;San Marco Argentano;CS;Calabria;078123;87018 +H992;San Martino di Finita;CS;Calabria;078124;87010 +I060;San Nicola Arcella;CS;Calabria;078125;87020 +I108;San Pietro in Amantea;CS;Calabria;078126;87030 +I114;San Pietro in Guarano;CS;Calabria;078127;87047 +I165;San Sosti;CS;Calabria;078128;87010 +I171;Santa Caterina Albanese;CS;Calabria;078129;87010 +I183;Santa Domenica Talao;CS;Calabria;078130;87020 +I192;Sant'Agata di Esaro;CS;Calabria;078131;87010 +C717;Santa Maria del Cedro;CS;Calabria;078132;87020 +I309;Santa Sofia d'Epiro;CS;Calabria;078133;87048 +I359;Santo Stefano di Rogliano;CS;Calabria;078134;87056 +I388;San Vincenzo La Costa;CS;Calabria;078135;87030 +I423;Saracena;CS;Calabria;078136;87010 +I485;Scala Coeli;CS;Calabria;078137;87060 +I489;Scalea;CS;Calabria;078138;87029 +D290;Scigliano;CS;Calabria;078139;87057 +I642;Serra d'Aiello;CS;Calabria;078140;87030 +I895;Spezzano Albanese;CS;Calabria;078142;87019 +I896;Spezzano della Sila;CS;Calabria;078143;87058 +L055;Tarsia;CS;Calabria;078145;87040 +L124;Terranova da Sibari;CS;Calabria;078146;87010 +L134;Terravecchia;CS;Calabria;078147;87060 +L206;Torano Castello;CS;Calabria;078148;87010 +L305;Tortora;CS;Calabria;078149;87020 +L353;Trebisacce;CS;Calabria;078150;87075 +L524;Vaccarizzo Albanese;CS;Calabria;078152;87060 +L747;Verbicaro;CS;Calabria;078153;87020 +B903;Villapiana;CS;Calabria;078154;87076 +M202;Zumpano;CS;Calabria;078155;87040 +M385;Casali del Manco;CS;Calabria;078156; +M403;Corigliano-Rossano;CS;Calabria;078157; +A155;Albi;CZ;Calabria;079002;88055 +A255;Amaroni;CZ;Calabria;079003;88050 +A257;Amato;CZ;Calabria;079004;88040 +A272;Andali;CZ;Calabria;079005;88050 +A397;Argusto;CZ;Calabria;079007;88060 +A542;Badolato;CZ;Calabria;079008;88060 +A736;Belcastro;CZ;Calabria;079009;88050 +B002;Borgia;CZ;Calabria;079011;88021 +B085;Botricello;CZ;Calabria;079012;88070 +B717;Caraffa di Catanzaro;CZ;Calabria;079017;88050 +B758;Cardinale;CZ;Calabria;079018;88062 +B790;Carlopoli;CZ;Calabria;079020;88040 +C352;Catanzaro;CZ;Calabria;079023;88100 +C453;Cenadi;CZ;Calabria;079024;88067 +C472;Centrache;CZ;Calabria;079025;88067 +C542;Cerva;CZ;Calabria;079027;88050 +C616;Chiaravalle Centrale;CZ;Calabria;079029;88064 +C674;Cicala;CZ;Calabria;079030;88040 +C960;Conflenti;CZ;Calabria;079033;88040 +D049;Cortale;CZ;Calabria;079034;88020 +D181;Cropani;CZ;Calabria;079036;88051 +D218;Curinga;CZ;Calabria;079039;88022 +D257;Davoli;CZ;Calabria;079042;88060 +D261;Decollatura;CZ;Calabria;079043;88041 +D476;Falerna;CZ;Calabria;079047;88042 +D544;Feroleto Antico;CZ;Calabria;079048;88040 +D744;Fossato Serralta;CZ;Calabria;079052;88050 +D852;Gagliato;CZ;Calabria;079055;88060 +D932;Gasperina;CZ;Calabria;079056;88060 +E031;Gimigliano;CZ;Calabria;079058;88045 +E050;Girifalco;CZ;Calabria;079059;88024 +E068;Gizzeria;CZ;Calabria;079060;88040 +E239;Guardavalle;CZ;Calabria;079061;88065 +E328;Isca sullo Ionio;CZ;Calabria;079063;88060 +E274;Jacurso;CZ;Calabria;079065;88020 +E806;Magisano;CZ;Calabria;079068;88050 +E834;Maida;CZ;Calabria;079069;88025 +E923;Marcedusa;CZ;Calabria;079071;88050 +E925;Marcellinara;CZ;Calabria;079072;88044 +E990;Martirano;CZ;Calabria;079073;88040 +E991;Martirano Lombardo;CZ;Calabria;079074;88040 +F200;Miglierina;CZ;Calabria;079077;88040 +F432;Montauro;CZ;Calabria;079080;88060 +F586;Montepaone;CZ;Calabria;079081;88060 +F780;Motta Santa Lucia;CZ;Calabria;079083;88040 +F910;Nocera Terinese;CZ;Calabria;079087;88047 +G034;Olivadi;CZ;Calabria;079088;88067 +G272;Palermiti;CZ;Calabria;079089;88050 +G439;Pentone;CZ;Calabria;079092;88050 +G517;Petrizzi;CZ;Calabria;079094;88060 +G518;Petronà;CZ;Calabria;079095;88050 +D546;Pianopoli;CZ;Calabria;079096;88040 +G734;Platania;CZ;Calabria;079099;88040 +H846;San Floro;CZ;Calabria;079108;88021 +H976;San Mango d'Aquino;CZ;Calabria;079110;88040 +I093;San Pietro a Maida;CZ;Calabria;079114;88025 +I095;San Pietro Apostolo;CZ;Calabria;079115;88040 +I164;San Sostene;CZ;Calabria;079116;88060 +I170;Santa Caterina dello Ionio;CZ;Calabria;079117;88060 +I266;Sant'Andrea Apostolo dello Ionio;CZ;Calabria;079118;88060 +I393;San Vito sullo Ionio;CZ;Calabria;079122;88067 +I463;Satriano;CZ;Calabria;079123;88060 +I589;Sellia;CZ;Calabria;079126;88050 +I590;Sellia Marina;CZ;Calabria;079127;88050 +I655;Serrastretta;CZ;Calabria;079129;88040 +I671;Sersale;CZ;Calabria;079130;88054 +I704;Settingiano;CZ;Calabria;079131;88040 +I745;Simeri Crichi;CZ;Calabria;079133;88050 +I844;Sorbo San Basile;CZ;Calabria;079134;88050 +I872;Soverato;CZ;Calabria;079137;88068 +I874;Soveria Mannelli;CZ;Calabria;079138;88049 +I875;Soveria Simeri;CZ;Calabria;079139;88050 +I929;Squillace;CZ;Calabria;079142;88069 +I937;Stalettì;CZ;Calabria;079143;88069 +L070;Taverna;CZ;Calabria;079146;88055 +L177;Tiriolo;CZ;Calabria;079147;88056 +L240;Torre di Ruggiero;CZ;Calabria;079148;88060 +I322;Vallefiorita;CZ;Calabria;079151;88050 +M140;Zagarise;CZ;Calabria;079157;88050 +M208;Lamezia Terme;CZ;Calabria;079160;88046 +A065;Africo;RC;Calabria;080001;89030 +A077;Agnana Calabra;RC;Calabria;080002;89040 +A303;Anoia;RC;Calabria;080003;89020 +A314;Antonimina;RC;Calabria;080004;89040 +A385;Ardore;RC;Calabria;080005;89031 +A544;Bagaladi;RC;Calabria;080006;89060 +A552;Bagnara Calabra;RC;Calabria;080007;89011 +A780;Benestare;RC;Calabria;080008;89030 +A843;Bianco;RC;Calabria;080009;89032 +A897;Bivongi;RC;Calabria;080010;89040 +B097;Bova;RC;Calabria;080011;89033 +B098;Bovalino;RC;Calabria;080012;89034 +B099;Bova Marina;RC;Calabria;080013;89035 +B118;Brancaleone;RC;Calabria;080014;89036 +B234;Bruzzano Zeffirio;RC;Calabria;080015;89030 +B379;Calanna;RC;Calabria;080016;89050 +B481;Camini;RC;Calabria;080017;89040 +B516;Campo Calabro;RC;Calabria;080018;89052 +B591;Candidoni;RC;Calabria;080019;89020 +B617;Canolo;RC;Calabria;080020;89040 +B718;Caraffa del Bianco;RC;Calabria;080021;89030 +B756;Cardeto;RC;Calabria;080022;89060 +B766;Careri;RC;Calabria;080023;89030 +B966;Casignana;RC;Calabria;080024;89030 +C285;Caulonia;RC;Calabria;080025;89041 +C695;Ciminà;RC;Calabria;080026;89040 +C710;Cinquefrondi;RC;Calabria;080027;89021 +C747;Cittanova;RC;Calabria;080028;89022 +C954;Condofuri;RC;Calabria;080029;89030 +D089;Cosoleto;RC;Calabria;080030;89050 +D268;Delianuova;RC;Calabria;080031;89012 +D545;Feroleto della Chiesa;RC;Calabria;080032;89050 +D557;Ferruzzano;RC;Calabria;080033;89030 +D619;Fiumara;RC;Calabria;080034;89050 +D864;Galatro;RC;Calabria;080035;89054 +D975;Gerace;RC;Calabria;080036;89040 +E025;Giffone;RC;Calabria;080037;89020 +E041;Gioia Tauro;RC;Calabria;080038;89013 +E044;Gioiosa Ionica;RC;Calabria;080039;89042 +E212;Grotteria;RC;Calabria;080040;89043 +E402;Laganadi;RC;Calabria;080041;89050 +E479;Laureana di Borrello;RC;Calabria;080042;89023 +D976;Locri;RC;Calabria;080043;89044 +E873;Mammola;RC;Calabria;080044;89045 +E956;Marina di Gioiosa Ionica;RC;Calabria;080045;89046 +E968;Maropati;RC;Calabria;080046;89020 +E993;Martone;RC;Calabria;080047;89040 +F105;Melicuccà;RC;Calabria;080048;89020 +F106;Melicucco;RC;Calabria;080049;89020 +F112;Melito di Porto Salvo;RC;Calabria;080050;89063 +F301;Molochio;RC;Calabria;080051;89010 +F324;Monasterace;RC;Calabria;080052;89040 +D746;Montebello Jonico;RC;Calabria;080053; +F779;Motta San Giovanni;RC;Calabria;080054;89065 +G082;Oppido Mamertina;RC;Calabria;080055;89014 +G277;Palizzi;RC;Calabria;080056;89038 +G288;Palmi;RC;Calabria;080057;89015 +G394;Pazzano;RC;Calabria;080058;89040 +G729;Placanica;RC;Calabria;080059;89040 +G735;Platì;RC;Calabria;080060;89039 +G791;Polistena;RC;Calabria;080061;89024 +G905;Portigliola;RC;Calabria;080062;89040 +H224;Reggio di Calabria;RC;Calabria;080063; +H265;Riace;RC;Calabria;080064;89040 +H359;Rizziconi;RC;Calabria;080065;89016 +H408;Roccaforte del Greco;RC;Calabria;080066;89060 +H456;Roccella Ionica;RC;Calabria;080067;89047 +H489;Roghudi;RC;Calabria;080068;89060 +H558;Rosarno;RC;Calabria;080069;89025 +H013;Samo;RC;Calabria;080070;89030 +H889;San Giorgio Morgeto;RC;Calabria;080071;89017 +H903;San Giovanni di Gerace;RC;Calabria;080072;89040 +H959;San Lorenzo;RC;Calabria;080073;89069 +H970;San Luca;RC;Calabria;080074;89030 +I102;San Pietro di Caridà;RC;Calabria;080075;89020 +I132;San Procopio;RC;Calabria;080076;89020 +I139;San Roberto;RC;Calabria;080077;89050 +I176;Santa Cristina d'Aspromonte;RC;Calabria;080078;89056 +I198;Sant'Agata del Bianco;RC;Calabria;080079;89030 +I214;Sant'Alessio in Aspromonte;RC;Calabria;080080;89050 +I333;Sant'Eufemia d'Aspromonte;RC;Calabria;080081;89027 +I341;Sant'Ilario dello Ionio;RC;Calabria;080082;89040 +I371;Santo Stefano in Aspromonte;RC;Calabria;080083;89057 +I536;Scido;RC;Calabria;080084;89010 +I537;Scilla;RC;Calabria;080085;89058 +I600;Seminara;RC;Calabria;080086;89028 +I656;Serrata;RC;Calabria;080087;89020 +I725;Siderno;RC;Calabria;080088;89048 +I753;Sinopoli;RC;Calabria;080089;89020 +I936;Staiti;RC;Calabria;080090;89030 +I955;Stignano;RC;Calabria;080091;89040 +I956;Stilo;RC;Calabria;080092;89049 +L063;Taurianova;RC;Calabria;080093;89029 +L127;Terranova Sappo Minulio;RC;Calabria;080094;89010 +L673;Varapodio;RC;Calabria;080095;89010 +M018;Villa San Giovanni;RC;Calabria;080096;89018 +M277;San Ferdinando;RC;Calabria;080097;89026 +A176;Alcamo;TP;Sicilia;081001;91011 +B288;Buseto Palizzolo;TP;Sicilia;081002;91012 +B385;Calatafimi-Segesta;TP;Sicilia;081003;91013 +B521;Campobello di Mazara;TP;Sicilia;081004;91021 +C130;Castellammare del Golfo;TP;Sicilia;081005;91014 +C286;Castelvetrano;TP;Sicilia;081006;91022 +D234;Custonaci;TP;Sicilia;081007;91015 +D423;Erice;TP;Sicilia;081008;91016 +D518;Favignana;TP;Sicilia;081009;91023 +E023;Gibellina;TP;Sicilia;081010;91024 +E974;Marsala;TP;Sicilia;081011;91025 +F061;Mazara del Vallo;TP;Sicilia;081012;91026 +G208;Paceco;TP;Sicilia;081013;91027 +G315;Pantelleria;TP;Sicilia;081014;91017 +G347;Partanna;TP;Sicilia;081015;91028 +G767;Poggioreale;TP;Sicilia;081016;91020 +H688;Salaparuta;TP;Sicilia;081017;91020 +H700;Salemi;TP;Sicilia;081018;91018 +I291;Santa Ninfa;TP;Sicilia;081019;91029 +I407;San Vito Lo Capo;TP;Sicilia;081020;91010 +L331;Trapani;TP;Sicilia;081021;91100 +G319;Valderice;TP;Sicilia;081022;91019 +M081;Vita;TP;Sicilia;081023;91010 +M281;Petrosino;TP;Sicilia;081024;91020 +M432;Misiliscemi;TP;Sicilia;081025; +A195;Alia;PA;Sicilia;082001;90021 +A202;Alimena;PA;Sicilia;082002;90020 +A203;Aliminusa;PA;Sicilia;082003;90020 +A229;Altavilla Milicia;PA;Sicilia;082004;90010 +A239;Altofonte;PA;Sicilia;082005;90030 +A546;Bagheria;PA;Sicilia;082006;90011 +A592;Balestrate;PA;Sicilia;082007;90041 +A719;Baucina;PA;Sicilia;082008;90020 +A764;Belmonte Mezzagno;PA;Sicilia;082009;90031 +A882;Bisacquino;PA;Sicilia;082010;90032 +A946;Bolognetta;PA;Sicilia;082011;90030 +A958;Bompietro;PA;Sicilia;082012;90020 +A991;Borgetto;PA;Sicilia;082013;90042 +B315;Caccamo;PA;Sicilia;082014;90012 +B430;Caltavuturo;PA;Sicilia;082015;90022 +B533;Campofelice di Fitalia;PA;Sicilia;082016;90030 +B532;Campofelice di Roccella;PA;Sicilia;082017;90010 +B535;Campofiorito;PA;Sicilia;082018;90030 +B556;Camporeale;PA;Sicilia;082019;90043 +B645;Capaci;PA;Sicilia;082020;90040 +B780;Carini;PA;Sicilia;082021;90044 +C067;Castelbuono;PA;Sicilia;082022;90013 +C074;Casteldaccia;PA;Sicilia;082023;90014 +C135;Castellana Sicula;PA;Sicilia;082024;90020 +C344;Castronovo di Sicilia;PA;Sicilia;082025; +C420;Cefalà Diana;PA;Sicilia;082026;90030 +C421;Cefalù;PA;Sicilia;082027;90015 +C496;Cerda;PA;Sicilia;082028;90010 +C654;Chiusa Sclafani;PA;Sicilia;082029;90033 +C696;Ciminna;PA;Sicilia;082030;90023 +C708;Cinisi;PA;Sicilia;082031;90045 +C871;Collesano;PA;Sicilia;082032;90016 +C968;Contessa Entellina;PA;Sicilia;082033;90030 +D009;Corleone;PA;Sicilia;082034;90034 +D567;Ficarazzi;PA;Sicilia;082035;90010 +D907;Gangi;PA;Sicilia;082036;90024 +D977;Geraci Siculo;PA;Sicilia;082037;90010 +E013;Giardinello;PA;Sicilia;082038;90040 +E055;Giuliana;PA;Sicilia;082039;90030 +E074;Godrano;PA;Sicilia;082040;90030 +E149;Gratteri;PA;Sicilia;082041;90010 +E337;Isnello;PA;Sicilia;082042;90010 +E350;Isola delle Femmine;PA;Sicilia;082043;90040 +E459;Lascari;PA;Sicilia;082044;90010 +E541;Lercara Friddi;PA;Sicilia;082045;90025 +E957;Marineo;PA;Sicilia;082046;90035 +F184;Mezzojuso;PA;Sicilia;082047;90030 +F246;Misilmeri;PA;Sicilia;082048;90036 +F377;Monreale;PA;Sicilia;082049;90046 +F544;Montelepre;PA;Sicilia;082050;90040 +F553;Montemaggiore Belsito;PA;Sicilia;082051;90020 +G263;Palazzo Adriano;PA;Sicilia;082052;90030 +G273;Palermo;PA;Sicilia;082053;90100,90121-90129,90131-90149,90151 +G348;Partinico;PA;Sicilia;082054;90047 +G510;Petralia Soprana;PA;Sicilia;082055;90026 +G511;Petralia Sottana;PA;Sicilia;082056;90027 +G543;Piana degli Albanesi;PA;Sicilia;082057;90037 +G792;Polizzi Generosa;PA;Sicilia;082058;90028 +G797;Pollina;PA;Sicilia;082059;90010 +H070;Prizzi;PA;Sicilia;082060;90038 +H422;Roccamena;PA;Sicilia;082061;90040 +H428;Roccapalumba;PA;Sicilia;082062;90020 +H797;San Cipirello;PA;Sicilia;082063;90040 +H933;San Giuseppe Jato;PA;Sicilia;082064;90048 +I028;San Mauro Castelverde;PA;Sicilia;082065;90010 +I174;Santa Cristina Gela;PA;Sicilia;082066;90030 +I188;Santa Flavia;PA;Sicilia;082067;90017 +I534;Sciara;PA;Sicilia;082068;90020 +I541;Sclafani Bagni;PA;Sicilia;082069;90020 +L112;Termini Imerese;PA;Sicilia;082070;90018 +L131;Terrasini;PA;Sicilia;082071;90049 +L282;Torretta;PA;Sicilia;082072;90040 +L317;Trabia;PA;Sicilia;082073;90019 +L332;Trappeto;PA;Sicilia;082074;90040 +L519;Ustica;PA;Sicilia;082075;90010 +L603;Valledolmo;PA;Sicilia;082076;90029 +L740;Ventimiglia di Sicilia;PA;Sicilia;082077;90020 +L837;Vicari;PA;Sicilia;082078;90020 +L916;Villabate;PA;Sicilia;082079;90039 +L951;Villafrati;PA;Sicilia;082080;90030 +I538;Scillato;PA;Sicilia;082081;90020 +M268;Blufi;PA;Sicilia;082082;90020 +A177;Alcara li Fusi;ME;Sicilia;083001;98070 +A194;Alì;ME;Sicilia;083002;98020 +A201;Alì Terme;ME;Sicilia;083003;98021 +A313;Antillo;ME;Sicilia;083004;98030 +A638;Barcellona Pozzo di Gotto;ME;Sicilia;083005;98051 +A698;Basicò;ME;Sicilia;083006;98060 +B198;Brolo;ME;Sicilia;083007;98061 +B660;Capizzi;ME;Sicilia;083008;98031 +B666;Capo d'Orlando;ME;Sicilia;083009;98071 +B695;Capri Leone;ME;Sicilia;083010;98070 +B804;Caronia;ME;Sicilia;083011;98072 +B918;Casalvecchio Siculo;ME;Sicilia;083012;98032 +C094;Castel di Lucio;ME;Sicilia;083013;98070 +C051;Castell'Umberto;ME;Sicilia;083014;98070 +C210;Castelmola;ME;Sicilia;083015;98030 +C347;Castroreale;ME;Sicilia;083016;98053 +C568;Cesarò;ME;Sicilia;083017;98033 +C956;Condrò;ME;Sicilia;083018;98040 +D474;Falcone;ME;Sicilia;083019;98060 +D569;Ficarra;ME;Sicilia;083020;98062 +D622;Fiumedinisi;ME;Sicilia;083021;98022 +D635;Floresta;ME;Sicilia;083022;98030 +D661;Fondachelli-Fantina;ME;Sicilia;083023;98050 +D733;Forza d'Agrò;ME;Sicilia;083024;98030 +D765;Francavilla di Sicilia;ME;Sicilia;083025;98034 +D793;Frazzanò;ME;Sicilia;083026;98070 +D824;Furci Siculo;ME;Sicilia;083027;98023 +D825;Furnari;ME;Sicilia;083028;98054 +D844;Gaggi;ME;Sicilia;083029;98030 +D861;Galati Mamertino;ME;Sicilia;083030;98070 +D885;Gallodoro;ME;Sicilia;083031;98030 +E014;Giardini-Naxos;ME;Sicilia;083032;98035 +E043;Gioiosa Marea;ME;Sicilia;083033;98063 +E142;Graniti;ME;Sicilia;083034;98036 +E233;Gualtieri Sicaminò;ME;Sicilia;083035;98040 +E374;Itala;ME;Sicilia;083036;98025 +E523;Leni;ME;Sicilia;083037;98050 +E555;Letojanni;ME;Sicilia;083038;98037 +E571;Librizzi;ME;Sicilia;083039;98064 +E594;Limina;ME;Sicilia;083040;98030 +E606;Lipari;ME;Sicilia;083041;98055 +E674;Longi;ME;Sicilia;083042;98070 +E855;Malfa;ME;Sicilia;083043;98050 +E869;Malvagna;ME;Sicilia;083044;98030 +E876;Mandanici;ME;Sicilia;083045;98020 +F066;Mazzarrà Sant'Andrea;ME;Sicilia;083046;98056 +F147;Merì;ME;Sicilia;083047;98040 +F158;Messina;ME;Sicilia;083048;98100,98121-98168 +F206;Milazzo;ME;Sicilia;083049;98057 +F210;Militello Rosmarino;ME;Sicilia;083050;98070 +F242;Mirto;ME;Sicilia;083051;98070 +F251;Mistretta;ME;Sicilia;083052;98073 +F277;Moio Alcantara;ME;Sicilia;083053;98030 +F359;Monforte San Giorgio;ME;Sicilia;083054;98041 +F368;Mongiuffi Melia;ME;Sicilia;083055;98030 +F395;Montagnareale;ME;Sicilia;083056;98060 +F400;Montalbano Elicona;ME;Sicilia;083057;98065 +F772;Motta Camastra;ME;Sicilia;083058;98030 +F773;Motta d'Affermo;ME;Sicilia;083059;98070 +F848;Naso;ME;Sicilia;083060;98074 +F901;Nizza di Sicilia;ME;Sicilia;083061;98026 +F951;Novara di Sicilia;ME;Sicilia;083062;98058 +G036;Oliveri;ME;Sicilia;083063;98060 +G209;Pace del Mela;ME;Sicilia;083064;98042 +G234;Pagliara;ME;Sicilia;083065;98020 +G377;Patti;ME;Sicilia;083066;98066 +G522;Pettineo;ME;Sicilia;083067;98070 +G699;Piraino;ME;Sicilia;083068;98060 +H151;Raccuja;ME;Sicilia;083069;98067 +H228;Reitano;ME;Sicilia;083070;98070 +H405;Roccafiorita;ME;Sicilia;083071;98030 +H418;Roccalumera;ME;Sicilia;083072;98027 +H380;Roccavaldina;ME;Sicilia;083073;98040 +H455;Roccella Valdemone;ME;Sicilia;083074;98030 +H479;Rodì Milici;ME;Sicilia;083075;98059 +H519;Rometta;ME;Sicilia;083076;98043 +H842;San Filippo del Mela;ME;Sicilia;083077;98044 +H850;San Fratello;ME;Sicilia;083078;98075 +H982;San Marco d'Alunzio;ME;Sicilia;083079;98070 +I084;San Pier Niceto;ME;Sicilia;083080;98045 +I086;San Piero Patti;ME;Sicilia;083081;98068 +I147;San Salvatore di Fitalia;ME;Sicilia;083082;98070 +I184;Santa Domenica Vittoria;ME;Sicilia;083083;98030 +I199;Sant'Agata di Militello;ME;Sicilia;083084;98076 +I215;Sant'Alessio Siculo;ME;Sicilia;083085;98030 +I220;Santa Lucia del Mela;ME;Sicilia;083086;98046 +I254;Santa Marina Salina;ME;Sicilia;083087;98050 +I283;Sant'Angelo di Brolo;ME;Sicilia;083088;98060 +I311;Santa Teresa di Riva;ME;Sicilia;083089;98028 +I328;San Teodoro;ME;Sicilia;083090;98030 +I370;Santo Stefano di Camastra;ME;Sicilia;083091;98077 +I420;Saponara;ME;Sicilia;083092;98047 +I477;Savoca;ME;Sicilia;083093;98038 +I492;Scaletta Zanclea;ME;Sicilia;083094;98029 +I747;Sinagra;ME;Sicilia;083095;98069 +I881;Spadafora;ME;Sicilia;083096;98048 +L042;Taormina;ME;Sicilia;083097;98039 +L271;Torregrotta;ME;Sicilia;083098;98040 +L308;Tortorici;ME;Sicilia;083099;98078 +L431;Tripi - Abakainon;ME;Sicilia;083100; +L478;Tusa;ME;Sicilia;083101;98079 +L482;Ucria;ME;Sicilia;083102;98060 +L561;Valdina;ME;Sicilia;083103;98040 +L735;Venetico;ME;Sicilia;083104;98040 +L950;Villafranca Tirrena;ME;Sicilia;083105;98049 +M210;Terme Vigliatore;ME;Sicilia;083106;98050 +M211;Acquedolci;ME;Sicilia;083107;98070 +M286;Torrenova;ME;Sicilia;083108;98070 +A089;Agrigento;AG;Sicilia;084001;92100 +A181;Alessandria della Rocca;AG;Sicilia;084002;92010 +A351;Aragona;AG;Sicilia;084003;92021 +A896;Bivona;AG;Sicilia;084004;92010 +B275;Burgio;AG;Sicilia;084005;92010 +B377;Calamonaci;AG;Sicilia;084006;92010 +B427;Caltabellotta;AG;Sicilia;084007;92010 +B460;Camastra;AG;Sicilia;084008;92020 +B486;Cammarata;AG;Sicilia;084009;92022 +B520;Campobello di Licata;AG;Sicilia;084010;92023 +B602;Canicattì;AG;Sicilia;084011;92024 +C275;Casteltermini;AG;Sicilia;084012;92025 +C341;Castrofilippo;AG;Sicilia;084013;92020 +C356;Cattolica Eraclea;AG;Sicilia;084014;92011 +C668;Cianciana;AG;Sicilia;084015;92012 +C928;Comitini;AG;Sicilia;084016;92020 +D514;Favara;AG;Sicilia;084017;92026 +E209;Grotte;AG;Sicilia;084018;92020 +E390;Joppolo Giancaxio;AG;Sicilia;084019;92010 +E431;Lampedusa e Linosa;AG;Sicilia;084020;92010 +E573;Licata;AG;Sicilia;084021;92027 +E714;Lucca Sicula;AG;Sicilia;084022;92010 +F126;Menfi;AG;Sicilia;084023;92013 +F414;Montallegro;AG;Sicilia;084024;92010 +F655;Montevago;AG;Sicilia;084025;92010 +F845;Naro;AG;Sicilia;084026;92028 +G282;Palma di Montechiaro;AG;Sicilia;084027;92020 +F299;Porto Empedocle;AG;Sicilia;084028;92014 +H148;Racalmuto;AG;Sicilia;084029;92020 +H159;Raffadali;AG;Sicilia;084030;92015 +H194;Ravanusa;AG;Sicilia;084031;92029 +H205;Realmonte;AG;Sicilia;084032;92010 +H269;Ribera;AG;Sicilia;084033;92016 +H743;Sambuca di Sicilia;AG;Sicilia;084034;92017 +H778;San Biagio Platani;AG;Sicilia;084035;92020 +H914;San Giovanni Gemini;AG;Sicilia;084036;92020 +I185;Santa Elisabetta;AG;Sicilia;084037;92020 +I224;Santa Margherita di Belice;AG;Sicilia;084038;92018 +I290;Sant'Angelo Muxaro;AG;Sicilia;084039;92020 +I356;Santo Stefano Quisquina;AG;Sicilia;084040;92020 +I533;Sciacca;AG;Sicilia;084041;92019 +I723;Siculiana;AG;Sicilia;084042;92010 +L944;Villafranca Sicula;AG;Sicilia;084043;92020 +A049;Acquaviva Platani;CL;Sicilia;085001;93010 +A957;Bompensiere;CL;Sicilia;085002;93010 +B302;Butera;CL;Sicilia;085003;93011 +B429;Caltanissetta;CL;Sicilia;085004;93100 +B537;Campofranco;CL;Sicilia;085005;93010 +D267;Delia;CL;Sicilia;085006;93010 +D960;Gela;CL;Sicilia;085007;93012 +E953;Marianopoli;CL;Sicilia;085008;93010 +F065;Mazzarino;CL;Sicilia;085009;93013 +E618;Milena;CL;Sicilia;085010;93010 +F489;Montedoro;CL;Sicilia;085011;93010 +F830;Mussomeli;CL;Sicilia;085012;93014 +F899;Niscemi;CL;Sicilia;085013;93015 +H245;Resuttano;CL;Sicilia;085014;93010 +H281;Riesi;CL;Sicilia;085015;93016 +H792;San Cataldo;CL;Sicilia;085016;93017 +I169;Santa Caterina Villarmosa;CL;Sicilia;085017;93018 +I644;Serradifalco;CL;Sicilia;085018;93010 +I824;Sommatino;CL;Sicilia;085019;93019 +L016;Sutera;CL;Sicilia;085020;93010 +L609;Vallelunga Pratameno;CL;Sicilia;085021;93010 +L959;Villalba;CL;Sicilia;085022;93010 +A070;Agira;EN;Sicilia;086001;94011 +A098;Aidone;EN;Sicilia;086002;94010 +A478;Assoro;EN;Sicilia;086003;94010 +A676;Barrafranca;EN;Sicilia;086004;94012 +B381;Calascibetta;EN;Sicilia;086005;94010 +C353;Catenanuova;EN;Sicilia;086006;94010 +C471;Centuripe;EN;Sicilia;086007;94010 +C480;Cerami;EN;Sicilia;086008;94010 +C342;Enna;EN;Sicilia;086009;94100 +D849;Gagliano Castelferrato;EN;Sicilia;086010;94010 +E536;Leonforte;EN;Sicilia;086011;94013 +F892;Nicosia;EN;Sicilia;086012;94014 +F900;Nissoria;EN;Sicilia;086013;94010 +G580;Piazza Armerina;EN;Sicilia;086014;94015 +G624;Pietraperzia;EN;Sicilia;086015;94016 +H221;Regalbuto;EN;Sicilia;086016;94017 +I891;Sperlinga;EN;Sicilia;086017;94010 +L448;Troina;EN;Sicilia;086018;94018 +L583;Valguarnera Caropepe;EN;Sicilia;086019;94019 +M011;Villarosa;EN;Sicilia;086020;94010 +A025;Aci Bonaccorsi;CT;Sicilia;087001;95020 +A026;Aci Castello;CT;Sicilia;087002;95021 +A027;Aci Catena;CT;Sicilia;087003;95022 +A028;Acireale;CT;Sicilia;087004;95024 +A029;Aci Sant'Antonio;CT;Sicilia;087005;95025 +A056;Adrano;CT;Sicilia;087006;95031 +A766;Belpasso;CT;Sicilia;087007;95032 +A841;Biancavilla;CT;Sicilia;087008;95033 +B202;Bronte;CT;Sicilia;087009;95034 +B384;Calatabiano;CT;Sicilia;087010;95011 +B428;Caltagirone;CT;Sicilia;087011;95041 +B561;Camporotondo Etneo;CT;Sicilia;087012;95040 +C091;Castel di Iudica;CT;Sicilia;087013;95040 +C297;Castiglione di Sicilia;CT;Sicilia;087014;95012 +C351;Catania;CT;Sicilia;087015;95100,95121-95131 +D623;Fiumefreddo di Sicilia;CT;Sicilia;087016;95013 +E017;Giarre;CT;Sicilia;087017;95014 +E133;Grammichele;CT;Sicilia;087018;95042 +E156;Gravina di Catania;CT;Sicilia;087019;95030 +E578;Licodia Eubea;CT;Sicilia;087020;95040 +E602;Linguaglossa;CT;Sicilia;087021;95015 +E854;Maletto;CT;Sicilia;087022;95035 +F004;Mascali;CT;Sicilia;087023;95016 +F005;Mascalucia;CT;Sicilia;087024;95030 +F209;Militello in Val di Catania;CT;Sicilia;087025;95043 +F214;Milo;CT;Sicilia;087026;95010 +F217;Mineo;CT;Sicilia;087027;95044 +F231;Mirabella Imbaccari;CT;Sicilia;087028;95040 +F250;Misterbianco;CT;Sicilia;087029;95045 +F781;Motta Sant'Anastasia;CT;Sicilia;087030;95040 +F890;Nicolosi;CT;Sicilia;087031;95030 +G253;Palagonia;CT;Sicilia;087032;95046 +G371;Paternò;CT;Sicilia;087033;95047 +G402;Pedara;CT;Sicilia;087034;95030 +G597;Piedimonte Etneo;CT;Sicilia;087035;95017 +H154;Raddusa;CT;Sicilia;087036;95040 +H168;Ramacca;CT;Sicilia;087037;95040 +H175;Randazzo;CT;Sicilia;087038;95036 +H325;Riposto;CT;Sicilia;087039;95018 +H805;San Cono;CT;Sicilia;087040;95040 +H922;San Giovanni la Punta;CT;Sicilia;087041;95037 +H940;San Gregorio di Catania;CT;Sicilia;087042;95027 +I035;San Michele di Ganzaria;CT;Sicilia;087043;95040 +I098;San Pietro Clarenza;CT;Sicilia;087044;95030 +I202;Sant'Agata li Battiati;CT;Sicilia;087045;95030 +I216;Sant'Alfio;CT;Sicilia;087046;95010 +I240;Santa Maria di Licodia;CT;Sicilia;087047;95038 +I314;Santa Venerina;CT;Sicilia;087048;95010 +I548;Scordia;CT;Sicilia;087049;95048 +L355;Trecastagni;CT;Sicilia;087050;95039 +L369;Tremestieri Etneo;CT;Sicilia;087051;95030 +L658;Valverde;CT;Sicilia;087052;95028 +L828;Viagrande;CT;Sicilia;087053;95029 +M100;Vizzini;CT;Sicilia;087054;95049 +M139;Zafferana Etnea;CT;Sicilia;087055;95019 +M271;Mazzarrone;CT;Sicilia;087056;95040 +M283;Maniace;CT;Sicilia;087057;95030 +M287;Ragalna;CT;Sicilia;087058;95030 +A014;Acate;RG;Sicilia;088001;97011 +C612;Chiaramonte Gulfi;RG;Sicilia;088002;97012 +C927;Comiso;RG;Sicilia;088003;97013 +E016;Giarratana;RG;Sicilia;088004;97010 +E366;Ispica;RG;Sicilia;088005;97014 +F258;Modica;RG;Sicilia;088006;97015 +F610;Monterosso Almo;RG;Sicilia;088007;97010 +G953;Pozzallo;RG;Sicilia;088008;97016 +H163;Ragusa;RG;Sicilia;088009;97100 +I178;Santa Croce Camerina;RG;Sicilia;088010;97017 +I535;Scicli;RG;Sicilia;088011;97018 +M088;Vittoria;RG;Sicilia;088012;97019 +A494;Augusta;SR;Sicilia;089001;96011 +A522;Avola;SR;Sicilia;089002;96012 +B237;Buccheri;SR;Sicilia;089003;96010 +B287;Buscemi;SR;Sicilia;089004;96010 +B603;Canicattini Bagni;SR;Sicilia;089005;96010 +B787;Carlentini;SR;Sicilia;089006;96013 +C006;Cassaro;SR;Sicilia;089007;96010 +D540;Ferla;SR;Sicilia;089008;96010 +D636;Floridia;SR;Sicilia;089009;96014 +D768;Francofonte;SR;Sicilia;089010;96015 +E532;Lentini;SR;Sicilia;089011;96016 +F107;Melilli;SR;Sicilia;089012;96010 +F943;Noto;SR;Sicilia;089013;96017 +G211;Pachino;SR;Sicilia;089014;96018 +G267;Palazzolo Acreide;SR;Sicilia;089015;96010 +H574;Rosolini;SR;Sicilia;089016;96019 +I754;Siracusa;SR;Sicilia;089017;96100 +I785;Solarino;SR;Sicilia;089018;96010 +I864;Sortino;SR;Sicilia;089019;96010 +M257;Portopalo di Capo Passero;SR;Sicilia;089020;96010 +M279;Priolo Gargallo;SR;Sicilia;089021;96010 +A283;Andreis;PN;Friuli-Venezia Giulia;093001;33080 +A354;Arba;PN;Friuli-Venezia Giulia;093002;33090 +A516;Aviano;PN;Friuli-Venezia Giulia;093004;33081 +A530;Azzano Decimo;PN;Friuli-Venezia Giulia;093005;33082 +A640;Barcis;PN;Friuli-Venezia Giulia;093006;33080 +B215;Brugnera;PN;Friuli-Venezia Giulia;093007;33070 +B247;Budoia;PN;Friuli-Venezia Giulia;093008;33070 +B598;Caneva;PN;Friuli-Venezia Giulia;093009;33070 +B940;Casarsa della Delizia;PN;Friuli-Venezia Giulia;093010;33072 +C217;Castelnovo del Friuli;PN;Friuli-Venezia Giulia;093011;33090 +C385;Cavasso Nuovo;PN;Friuli-Venezia Giulia;093012;33092 +C640;Chions;PN;Friuli-Venezia Giulia;093013;33083 +C699;Cimolais;PN;Friuli-Venezia Giulia;093014;33080 +C790;Claut;PN;Friuli-Venezia Giulia;093015;33080 +C791;Clauzetto;PN;Friuli-Venezia Giulia;093016;33090 +C991;Cordenons;PN;Friuli-Venezia Giulia;093017;33084 +C993;Cordovado;PN;Friuli-Venezia Giulia;093018;33075 +D426;Erto e Casso;PN;Friuli-Venezia Giulia;093019;33080 +D487;Fanna;PN;Friuli-Venezia Giulia;093020;33092 +D621;Fiume Veneto;PN;Friuli-Venezia Giulia;093021;33080 +D670;Fontanafredda;PN;Friuli-Venezia Giulia;093022;33074 +D804;Frisanco;PN;Friuli-Venezia Giulia;093024;33080 +E889;Maniago;PN;Friuli-Venezia Giulia;093025;33085 +F089;Meduno;PN;Friuli-Venezia Giulia;093026;33092 +F596;Montereale Valcellina;PN;Friuli-Venezia Giulia;093027;33086 +F750;Morsano al Tagliamento;PN;Friuli-Venezia Giulia;093028;33075 +G353;Pasiano di Pordenone;PN;Friuli-Venezia Giulia;093029;33087 +G680;Pinzano al Tagliamento;PN;Friuli-Venezia Giulia;093030;33094 +G780;Polcenigo;PN;Friuli-Venezia Giulia;093031;33070 +G886;Porcia;PN;Friuli-Venezia Giulia;093032;33080 +G888;Pordenone;PN;Friuli-Venezia Giulia;093033;33170 +G994;Prata di Pordenone;PN;Friuli-Venezia Giulia;093034;33080 +H010;Pravisdomini;PN;Friuli-Venezia Giulia;093035;33076 +H609;Roveredo in Piano;PN;Friuli-Venezia Giulia;093036;33080 +H657;Sacile;PN;Friuli-Venezia Giulia;093037;33077 +H891;San Giorgio della Richinvelda;PN;Friuli-Venezia Giulia;093038;33095 +H999;San Martino al Tagliamento;PN;Friuli-Venezia Giulia;093039;33098 +I136;San Quirino;PN;Friuli-Venezia Giulia;093040;33080 +I403;San Vito al Tagliamento;PN;Friuli-Venezia Giulia;093041;33078 +I621;Sequals;PN;Friuli-Venezia Giulia;093042;33090 +I686;Sesto al Reghena;PN;Friuli-Venezia Giulia;093043;33079 +I904;Spilimbergo;PN;Friuli-Venezia Giulia;093044;33097 +L324;Tramonti di Sopra;PN;Friuli-Venezia Giulia;093045;33090 +L325;Tramonti di Sotto;PN;Friuli-Venezia Giulia;093046;33090 +L347;Travesio;PN;Friuli-Venezia Giulia;093047;33090 +M085;Vito d'Asio;PN;Friuli-Venezia Giulia;093049;33090 +M096;Vivaro;PN;Friuli-Venezia Giulia;093050;33099 +M190;Zoppola;PN;Friuli-Venezia Giulia;093051;33080 +M265;Vajont;PN;Friuli-Venezia Giulia;093052;33080 +M346;Valvasone Arzene;PN;Friuli-Venezia Giulia;093053;33098 +A051;Acquaviva d'Isernia;IS;Molise;094001;86080 +A080;Agnone;IS;Molise;094002;86081 +A567;Bagnoli del Trigno;IS;Molise;094003;86091 +A761;Belmonte del Sannio;IS;Molise;094004;86080 +B630;Cantalupo nel Sannio;IS;Molise;094005;86092 +B682;Capracotta;IS;Molise;094006;86082 +B810;Carovilli;IS;Molise;094007;86083 +B830;Carpinone;IS;Molise;094008;86093 +C082;Castel del Giudice;IS;Molise;094009;86080 +C246;Castelpetroso;IS;Molise;094010;86090 +C247;Castelpizzuto;IS;Molise;094011;86090 +C270;Castel San Vincenzo;IS;Molise;094012;86071 +C200;Castelverrino;IS;Molise;094013;86080 +C534;Cerro al Volturno;IS;Molise;094014;86072 +C620;Chiauci;IS;Molise;094015;86097 +C769;Civitanova del Sannio;IS;Molise;094016;86094 +C878;Colli a Volturno;IS;Molise;094017;86073 +C941;Conca Casale;IS;Molise;094018;86070 +D595;Filignano;IS;Molise;094019;86074 +D703;Forlì del Sannio;IS;Molise;094020;86084 +D715;Fornelli;IS;Molise;094021;86070 +D811;Frosolone;IS;Molise;094022;86095 +E335;Isernia;IS;Molise;094023;86170 +E669;Longano;IS;Molise;094024;86090 +E778;Macchia d'Isernia;IS;Molise;094025;86070 +E779;Macchiagodena;IS;Molise;094026;86096 +F239;Miranda;IS;Molise;094027;86080,86170 +F429;Montaquila;IS;Molise;094028;86070 +F580;Montenero Val Cocchiara;IS;Molise;094029;86080 +F601;Monteroduni;IS;Molise;094030;86075 +G486;Pesche;IS;Molise;094031;86090 +G495;Pescolanciano;IS;Molise;094032;86097 +G497;Pescopennataro;IS;Molise;094033;86080 +G523;Pettoranello del Molise;IS;Molise;094034;86090 +G606;Pietrabbondante;IS;Molise;094035;86085 +G727;Pizzone;IS;Molise;094036;86071 +B317;Poggio Sannita;IS;Molise;094037;86086 +G954;Pozzilli;IS;Molise;094038;86077 +H308;Rionero Sannitico;IS;Molise;094039;86087 +H420;Roccamandolfi;IS;Molise;094040;86092 +H445;Roccasicura;IS;Molise;094041;86080 +H458;Rocchetta a Volturno;IS;Molise;094042;86070 +I096;San Pietro Avellana;IS;Molise;094043;86088 +I189;Sant'Agapito;IS;Molise;094044;86070 +I238;Santa Maria del Molise;IS;Molise;094045;86096 +I282;Sant'Angelo del Pesco;IS;Molise;094046;86080 +B466;Sant'Elena Sannita;IS;Molise;094047;86095 +I507;Scapoli;IS;Molise;094048;86070 +I679;Sessano del Molise;IS;Molise;094049;86097 +I682;Sesto Campano;IS;Molise;094050;86078 +L696;Vastogirardi;IS;Molise;094051;86089 +L725;Venafro;IS;Molise;094052;86079 +A107;Ailoche;BI;Piemonte;096001;13861 +A280;Andorno Micca;BI;Piemonte;096002;13811 +A784;Benna;BI;Piemonte;096003;13871 +A859;Biella;BI;Piemonte;096004;13900 +A876;Bioglio;BI;Piemonte;096005;13841 +B058;Borriana;BI;Piemonte;096006;13872 +B229;Brusnengo;BI;Piemonte;096007;13862 +B417;Callabiana;BI;Piemonte;096008;13821 +B457;Camandona;BI;Piemonte;096009;13821 +B465;Camburzano;BI;Piemonte;096010;13891 +B586;Candelo;BI;Piemonte;096012;13878 +B708;Caprile;BI;Piemonte;096013;13864 +B933;Casapinta;BI;Piemonte;096014;13866 +C155;Castelletto Cervo;BI;Piemonte;096015;13851 +C363;Cavaglià;BI;Piemonte;096016;13881 +C532;Cerrione;BI;Piemonte;096018;13882 +C819;Coggiola;BI;Piemonte;096019;13863 +D094;Cossato;BI;Piemonte;096020;13836 +D165;Crevacuore;BI;Piemonte;096021;13864 +D219;Curino;BI;Piemonte;096023;13865 +D339;Donato;BI;Piemonte;096024;13893 +D350;Dorzano;BI;Piemonte;096025;13881 +D848;Gaglianico;BI;Piemonte;096026;13894 +E024;Gifflenga;BI;Piemonte;096027;13874 +E130;Graglia;BI;Piemonte;096028;13895 +E821;Magnano;BI;Piemonte;096030;13887 +F037;Massazza;BI;Piemonte;096031;13873 +F042;Masserano;BI;Piemonte;096032;13866 +F167;Mezzana Mortigliengo;BI;Piemonte;096033;13831 +F189;Miagliano;BI;Piemonte;096034;13816 +F369;Mongrando;BI;Piemonte;096035;13888 +F776;Mottalciata;BI;Piemonte;096037;13874 +F833;Muzzano;BI;Piemonte;096038;13895 +F878;Netro;BI;Piemonte;096039;13896 +F992;Occhieppo Inferiore;BI;Piemonte;096040;13897 +F993;Occhieppo Superiore;BI;Piemonte;096041;13898 +G521;Pettinengo;BI;Piemonte;096042;13843 +G577;Piatto;BI;Piemonte;096043;13844 +G594;Piedicavallo;BI;Piemonte;096044;13812 +G798;Pollone;BI;Piemonte;096046;13814 +G820;Ponderano;BI;Piemonte;096047;13875 +G927;Portula;BI;Piemonte;096048;13833 +G980;Pralungo;BI;Piemonte;096049;13899 +G974;Pray;BI;Piemonte;096050;13867 +H538;Ronco Biellese;BI;Piemonte;096053;13845 +H553;Roppolo;BI;Piemonte;096054;13883 +H561;Rosazza;BI;Piemonte;096055;13815 +H662;Sagliano Micca;BI;Piemonte;096056;13816 +H681;Sala Biellese;BI;Piemonte;096057;13884 +H726;Salussola;BI;Piemonte;096058;13885 +H821;Sandigliano;BI;Piemonte;096059;13876 +I847;Sordevolo;BI;Piemonte;096063;13817 +I868;Sostegno;BI;Piemonte;096064;13868 +I980;Strona;BI;Piemonte;096065;13823 +L075;Tavigliano;BI;Piemonte;096066;13811 +L116;Ternengo;BI;Piemonte;096067;13844 +L193;Tollegno;BI;Piemonte;096068;13818 +L239;Torrazzo;BI;Piemonte;096069;13884 +L556;Valdengo;BI;Piemonte;096071;13855 +L586;Vallanzengo;BI;Piemonte;096072;13847 +L620;Valle San Nicolao;BI;Piemonte;096074;13847 +L712;Veglio;BI;Piemonte;096075;13824 +L785;Verrone;BI;Piemonte;096076;13871 +L880;Vigliano Biellese;BI;Piemonte;096077;13856 +L933;Villa del Bosco;BI;Piemonte;096078;13868 +L978;Villanova Biellese;BI;Piemonte;096079;13877 +M098;Viverone;BI;Piemonte;096080;13886 +M179;Zimone;BI;Piemonte;096081;13887 +M196;Zubiena;BI;Piemonte;096082;13888 +M201;Zumaglia;BI;Piemonte;096083;13848 +M371;Lessona;BI;Piemonte;096085;13853 +M373;Campiglia Cervo;BI;Piemonte;096086;13812 +M414;Quaregna Cerreto;BI;Piemonte;096087; +M417;Valdilana;BI;Piemonte;096088; +A005;Abbadia Lariana;LC;Lombardia;097001;23821 +A112;Airuno;LC;Lombardia;097002;23881 +A301;Annone di Brianza;LC;Lombardia;097003;23841 +A594;Ballabio;LC;Lombardia;097004;23811 +A683;Barzago;LC;Lombardia;097005;23890 +A686;Barzanò;LC;Lombardia;097006;23891 +A687;Barzio;LC;Lombardia;097007;23816 +A745;Bellano;LC;Lombardia;097008;23822 +B081;Bosisio Parini;LC;Lombardia;097009;23842 +B194;Brivio;LC;Lombardia;097010;23883 +B261;Bulciago;LC;Lombardia;097011;23892 +B396;Calco;LC;Lombardia;097012;23885 +B423;Calolziocorte;LC;Lombardia;097013;23801 +B763;Carenno;LC;Lombardia;097014;23802 +B937;Casargo;LC;Lombardia;097015;23831 +B943;Casatenovo;LC;Lombardia;097016;23880 +B996;Cassago Brianza;LC;Lombardia;097017;23893 +C024;Cassina Valsassina;LC;Lombardia;097018;23817 +C187;Castello di Brianza;LC;Lombardia;097019;23884 +C521;Cernusco Lombardone;LC;Lombardia;097020;23870 +C563;Cesana Brianza;LC;Lombardia;097021;23861 +C752;Civate;LC;Lombardia;097022;23862 +C839;Colico;LC;Lombardia;097023;23823 +C851;Colle Brianza;LC;Lombardia;097024;23886 +D065;Cortenova;LC;Lombardia;097025;23813 +D112;Costa Masnaga;LC;Lombardia;097026;23845 +D131;Crandola Valsassina;LC;Lombardia;097027;23832 +D143;Cremella;LC;Lombardia;097028;23894 +D145;Cremeno;LC;Lombardia;097029;23814 +D280;Dervio;LC;Lombardia;097030;23824 +D327;Dolzago;LC;Lombardia;097031;23843 +D346;Dorio;LC;Lombardia;097032;23824 +D398;Ello;LC;Lombardia;097033;23848 +D428;Erve;LC;Lombardia;097034;23805 +D436;Esino Lario;LC;Lombardia;097035;23825 +D865;Galbiate;LC;Lombardia;097036;23851 +D913;Garbagnate Monastero;LC;Lombardia;097037;23846 +D926;Garlate;LC;Lombardia;097038;23852 +E287;Imbersago;LC;Lombardia;097039;23898 +E305;Introbio;LC;Lombardia;097040;23815 +E507;Lecco;LC;Lombardia;097042;23900 +E581;Lierna;LC;Lombardia;097043;23827 +E656;Lomagna;LC;Lombardia;097044;23871 +E858;Malgrate;LC;Lombardia;097045;23864 +E879;Mandello del Lario;LC;Lombardia;097046;23826 +E947;Margno;LC;Lombardia;097047;23832 +F133;Merate;LC;Lombardia;097048;23807 +F248;Missaglia;LC;Lombardia;097049;23873 +F265;Moggio;LC;Lombardia;097050;23817 +F304;Molteno;LC;Lombardia;097051;23847 +F561;Monte Marenzo;LC;Lombardia;097052;23804 +F657;Montevecchia;LC;Lombardia;097053;23874 +F674;Monticello Brianza;LC;Lombardia;097054;23876 +F758;Morterone;LC;Lombardia;097055;23811 +F887;Nibionno;LC;Lombardia;097056;23895 +G009;Oggiono;LC;Lombardia;097057;23848 +G026;Olgiate Molgora;LC;Lombardia;097058;23887 +G030;Olginate;LC;Lombardia;097059;23854 +G040;Oliveto Lario;LC;Lombardia;097060;23865 +G161;Osnago;LC;Lombardia;097061;23875 +G218;Paderno d'Adda;LC;Lombardia;097062;23877 +G241;Pagnona;LC;Lombardia;097063;23833 +G336;Parlasco;LC;Lombardia;097064;23837 +G368;Pasturo;LC;Lombardia;097065;23818 +G456;Perledo;LC;Lombardia;097067;23828 +G485;Pescate;LC;Lombardia;097068;23855 +H028;Premana;LC;Lombardia;097069;23834 +H063;Primaluna;LC;Lombardia;097070;23819 +G223;Robbiate;LC;Lombardia;097071;23899 +H486;Rogeno;LC;Lombardia;097072;23849 +I243;Santa Maria Hoè;LC;Lombardia;097074;23889 +I759;Sirone;LC;Lombardia;097075;23844 +I761;Sirtori;LC;Lombardia;097076;23896 +I994;Sueglio;LC;Lombardia;097077;23835 +I996;Suello;LC;Lombardia;097078;23867 +L022;Taceno;LC;Lombardia;097079;23837 +L581;Valgreghentino;LC;Lombardia;097082;23857 +L634;Valmadrera;LC;Lombardia;097083;23868 +L680;Varenna;LC;Lombardia;097084;23829 +L751;Vercurago;LC;Lombardia;097086;23808 +L866;Viganò;LC;Lombardia;097090;23897 +M337;Verderio;LC;Lombardia;097091;23879 +M348;La Valletta Brianza;LC;Lombardia;097092;23888 +M395;Valvarrone;LC;Lombardia;097093; +A004;Abbadia Cerreto;LO;Lombardia;098001;26834 +A811;Bertonico;LO;Lombardia;098002;26821 +A919;Boffalora d'Adda;LO;Lombardia;098003;26811 +A995;Borghetto Lodigiano;LO;Lombardia;098004;26812 +B017;Borgo San Giovanni;LO;Lombardia;098005;26851 +B141;Brembio;LO;Lombardia;098006;26822 +B887;Casaletto Lodigiano;LO;Lombardia;098008;26852 +B899;Casalmaiocco;LO;Lombardia;098009;26831 +B910;Casalpusterlengo;LO;Lombardia;098010;26841 +B961;Caselle Landi;LO;Lombardia;098011;26842 +B958;Caselle Lurani;LO;Lombardia;098012;26853 +C228;Castelnuovo Bocca d'Adda;LO;Lombardia;098013;26843 +C304;Castiglione d'Adda;LO;Lombardia;098014;26823 +C329;Castiraga Vidardo;LO;Lombardia;098015;26866 +C394;Cavenago d'Adda;LO;Lombardia;098017;26824 +C555;Cervignano d'Adda;LO;Lombardia;098018;26832 +C816;Codogno;LO;Lombardia;098019;26845 +C917;Comazzo;LO;Lombardia;098020;26833 +D021;Cornegliano Laudense;LO;Lombardia;098021;26854 +D028;Corno Giovine;LO;Lombardia;098022;26846 +D029;Cornovecchio;LO;Lombardia;098023;26842 +D068;Corte Palasio;LO;Lombardia;098024;26834 +D159;Crespiatica;LO;Lombardia;098025;26835 +D660;Fombio;LO;Lombardia;098026;26861 +D868;Galgagnano;LO;Lombardia;098027;26832 +E127;Graffignana;LO;Lombardia;098028;26813 +E238;Guardamiglio;LO;Lombardia;098029;26862 +E627;Livraga;LO;Lombardia;098030;26814 +E648;Lodi;LO;Lombardia;098031;26900 +E651;Lodi Vecchio;LO;Lombardia;098032;26855 +E777;Maccastorna;LO;Lombardia;098033;26843 +E840;Mairago;LO;Lombardia;098034;26825 +E852;Maleo;LO;Lombardia;098035;26847 +E994;Marudo;LO;Lombardia;098036;26866 +F028;Massalengo;LO;Lombardia;098037;26815 +F102;Meleti;LO;Lombardia;098038;26843 +F149;Merlino;LO;Lombardia;098039;26833 +F423;Montanaso Lombardo;LO;Lombardia;098040;26836 +F801;Mulazzano;LO;Lombardia;098041;26837 +G107;Orio Litta;LO;Lombardia;098042;26863 +G166;Ospedaletto Lodigiano;LO;Lombardia;098043;26864 +G171;Ossago Lodigiano;LO;Lombardia;098044;26816 +G096;Pieve Fissiraga;LO;Lombardia;098045;26854 +H701;Salerano sul Lambro;LO;Lombardia;098046;26857 +H844;San Fiorano;LO;Lombardia;098047;26848 +I012;San Martino in Strada;LO;Lombardia;098048;26817 +I140;San Rocco al Porto;LO;Lombardia;098049;26865 +I274;Sant'Angelo Lodigiano;LO;Lombardia;098050;26866 +I362;Santo Stefano Lodigiano;LO;Lombardia;098051;26849 +I561;Secugnago;LO;Lombardia;098052;26826 +I612;Senna Lodigiana;LO;Lombardia;098053;26856 +I815;Somaglia;LO;Lombardia;098054;26867 +I848;Sordio;LO;Lombardia;098055;26858 +F260;Tavazzano con Villavesco;LO;Lombardia;098056;26838 +L125;Terranova dei Passerini;LO;Lombardia;098057;26827 +L469;Turano Lodigiano;LO;Lombardia;098058;26828 +L572;Valera Fratta;LO;Lombardia;098059;26859 +L977;Villanova del Sillaro;LO;Lombardia;098060;26818 +M158;Zelo Buon Persico;LO;Lombardia;098061;26839 +M393;Castelgerundo;LO;Lombardia;098062; +A747;Bellaria-Igea Marina;RN;Emilia-Romagna;099001;47814 +C357;Cattolica;RN;Emilia-Romagna;099002;47841 +D004;Coriano;RN;Emilia-Romagna;099003;47853 +D961;Gemmano;RN;Emilia-Romagna;099004;47855 +F244;Misano Adriatico;RN;Emilia-Romagna;099005;47843 +F346;Mondaino;RN;Emilia-Romagna;099006;47836 +F502;Montefiore Conca;RN;Emilia-Romagna;099008;47834 +F523;Montegridolfo;RN;Emilia-Romagna;099009;47837 +F715;Morciano di Romagna;RN;Emilia-Romagna;099011;47833 +H274;Riccione;RN;Emilia-Romagna;099013;47838 +H294;Rimini;RN;Emilia-Romagna;099014;47900,47921-47924 +H724;Saludecio;RN;Emilia-Romagna;099015;47835 +H801;San Clemente;RN;Emilia-Romagna;099016;47832 +H921;San Giovanni in Marignano;RN;Emilia-Romagna;099017;47842 +I304;Santarcangelo di Romagna;RN;Emilia-Romagna;099018;47822 +L797;Verucchio;RN;Emilia-Romagna;099020;47826 +C080;Casteldelci;RN;Emilia-Romagna;099021;47861 +E838;Maiolo;RN;Emilia-Romagna;099022;47862 +F137;Novafeltria;RN;Emilia-Romagna;099023;47863 +G433;Pennabilli;RN;Emilia-Romagna;099024;47864 +H949;San Leo;RN;Emilia-Romagna;099025;47865 +I201;Sant'Agata Feltria;RN;Emilia-Romagna;099026;47866 +L034;Talamello;RN;Emilia-Romagna;099027;47867 +M324;Poggio Torriana;RN;Emilia-Romagna;099028;47824 +M368;Montescudo-Monte Colombo;RN;Emilia-Romagna;099029; +F478;Montecopiolo;RN;Emilia-Romagna;099030; +I460;Sassofeltrio;RN;Emilia-Romagna;099031; +B626;Cantagallo;PO;Toscana;100001;59025 +B794;Carmignano;PO;Toscana;100002;59015 +F572;Montemurlo;PO;Toscana;100003;59013 +G754;Poggio a Caiano;PO;Toscana;100004;59016 +G999;Prato;PO;Toscana;100005;59100 +L537;Vaiano;PO;Toscana;100006;59021 +L775;Vernio;PO;Toscana;100007;59024 +A772;Belvedere di Spinello;KR;Calabria;101001;88824 +B319;Caccuri;KR;Calabria;101002;88833 +B771;Carfizzi;KR;Calabria;101003;88817 +B857;Casabona;KR;Calabria;101004;88822 +B968;Castelsilano;KR;Calabria;101005;88834 +C501;Cerenzia;KR;Calabria;101006;88833 +C725;Cirò;KR;Calabria;101007;88813 +C726;Cirò Marina;KR;Calabria;101008;88811 +D123;Cotronei;KR;Calabria;101009;88836 +D122;Crotone;KR;Calabria;101010;88900 +D189;Crucoli;KR;Calabria;101011;88812 +D236;Cutro;KR;Calabria;101012;88842 +E339;Isola di Capo Rizzuto;KR;Calabria;101013;88841 +F108;Melissa;KR;Calabria;101014;88814 +F157;Mesoraca;KR;Calabria;101015;88838 +G278;Pallagorio;KR;Calabria;101016;88818 +G508;Petilia Policastro;KR;Calabria;101017;88837 +H383;Roccabernarda;KR;Calabria;101018;88835 +H403;Rocca di Neto;KR;Calabria;101019;88821 +I026;San Mauro Marchesato;KR;Calabria;101020;88831 +I057;San Nicola dell'Alto;KR;Calabria;101021;88817 +I308;Santa Severina;KR;Calabria;101022;88832 +I468;Savelli;KR;Calabria;101023;88825 +I494;Scandale;KR;Calabria;101024;88831 +I982;Strongoli;KR;Calabria;101025;88816 +L492;Umbriatico;KR;Calabria;101026;88823 +L802;Verzino;KR;Calabria;101027;88819 +A043;Acquaro;VV;Calabria;102001;89832 +A386;Arena;VV;Calabria;102002;89832 +B169;Briatico;VV;Calabria;102003;89817 +B197;Brognaturo;VV;Calabria;102004;89822 +B655;Capistrano;VV;Calabria;102005;89818 +C581;Cessaniti;VV;Calabria;102006;89816 +D253;Dasà;VV;Calabria;102007;89832 +D303;Dinami;VV;Calabria;102008;89833 +D364;Drapia;VV;Calabria;102009;89862 +D453;Fabrizia;VV;Calabria;102010;89823 +D587;Filadelfia;VV;Calabria;102011;89814 +D589;Filandari;VV;Calabria;102012;89841 +D596;Filogaso;VV;Calabria;102013;89843 +D762;Francavilla Angitola;VV;Calabria;102014;89815 +D767;Francica;VV;Calabria;102015;89851 +D988;Gerocarne;VV;Calabria;102016;89831 +E321;Jonadi;VV;Calabria;102017;89851 +E389;Joppolo;VV;Calabria;102018;89863 +E590;Limbadi;VV;Calabria;102019;89844 +E836;Maierato;VV;Calabria;102020;89843 +F207;Mileto;VV;Calabria;102021;89852 +F364;Mongiana;VV;Calabria;102022;89823 +F607;Monterosso Calabro;VV;Calabria;102023;89819 +F843;Nardodipace;VV;Calabria;102024;89824 +F893;Nicotera;VV;Calabria;102025;89844 +G335;Parghelia;VV;Calabria;102026;89861 +G722;Pizzo;VV;Calabria;102027;89812 +G728;Pizzoni;VV;Calabria;102028;89834 +G785;Polia;VV;Calabria;102029;89813 +H271;Ricadi;VV;Calabria;102030;89866 +H516;Rombiolo;VV;Calabria;102031;89841 +H785;San Calogero;VV;Calabria;102032;89842 +H807;San Costantino Calabro;VV;Calabria;102033;89851 +H941;San Gregorio d'Ippona;VV;Calabria;102034;89853 +I058;San Nicola da Crissa;VV;Calabria;102035;89821 +I350;Sant'Onofrio;VV;Calabria;102036;89843 +I639;Serra San Bruno;VV;Calabria;102037;89822 +I744;Simbario;VV;Calabria;102038;89822 +I853;Sorianello;VV;Calabria;102039;89831 +I854;Soriano Calabro;VV;Calabria;102040;89831 +I884;Spadola;VV;Calabria;102041;89822 +I905;Spilinga;VV;Calabria;102042;89864 +I945;Stefanaconi;VV;Calabria;102043;89843 +L452;Tropea;VV;Calabria;102044;89861 +L607;Vallelonga;VV;Calabria;102045;89821 +L699;Vazzano;VV;Calabria;102046;89834 +F537;Vibo Valentia;VV;Calabria;102047;89900 +M138;Zaccanopoli;VV;Calabria;102048;89867 +M143;Zambrone;VV;Calabria;102049;89868 +M204;Zungri;VV;Calabria;102050;89867 +A317;Antrona Schieranco;VB;Piemonte;103001;28841 +A325;Anzola d'Ossola;VB;Piemonte;103002;28877 +A409;Arizzano;VB;Piemonte;103003;28811 +A427;Arola;VB;Piemonte;103004;28899 +A497;Aurano;VB;Piemonte;103005;28812 +A534;Baceno;VB;Piemonte;103006;28861 +A610;Bannio Anzino;VB;Piemonte;103007;28871 +A725;Baveno;VB;Piemonte;103008;28831 +A733;Bee;VB;Piemonte;103009;28813 +A742;Belgirate;VB;Piemonte;103010;28832 +A834;Beura-Cardezza;VB;Piemonte;103011;28851 +A925;Bognanco;VB;Piemonte;103012;28842 +B207;Brovello-Carpugnino;VB;Piemonte;103013;28833 +B380;Calasca-Castiglione;VB;Piemonte;103014;28873 +B463;Cambiasca;VB;Piemonte;103015;28814 +B610;Cannero Riviera;VB;Piemonte;103016;28821 +B615;Cannobio;VB;Piemonte;103017;28822 +B694;Caprezzo;VB;Piemonte;103018;28815 +B876;Casale Corte Cerro;VB;Piemonte;103019;28881 +C478;Ceppo Morelli;VB;Piemonte;103021;28875 +C567;Cesara;VB;Piemonte;103022;28891 +D099;Cossogno;VB;Piemonte;103023;28801 +D134;Craveggia;VB;Piemonte;103024;28852 +D168;Crevoladossola;VB;Piemonte;103025;28865 +D177;Crodo;VB;Piemonte;103026;28862 +D332;Domodossola;VB;Piemonte;103028;28845 +D374;Druogno;VB;Piemonte;103029;28853 +D706;Formazza;VB;Piemonte;103031;28863 +D984;Germagno;VB;Piemonte;103032;28887 +E003;Ghiffa;VB;Piemonte;103033;28823 +E028;Gignese;VB;Piemonte;103034;28836 +E153;Gravellona Toce;VB;Piemonte;103035;28883 +E269;Gurro;VB;Piemonte;103036;28828 +E304;Intragna;VB;Piemonte;103037;28816 +E685;Loreglia;VB;Piemonte;103038;28893 +E790;Macugnaga;VB;Piemonte;103039;28876 +E795;Madonna del Sasso;VB;Piemonte;103040;28894 +E853;Malesco;VB;Piemonte;103041;28854 +F010;Masera;VB;Piemonte;103042;28855 +F048;Massiola;VB;Piemonte;103043;28895 +F146;Mergozzo;VB;Piemonte;103044;28802 +F192;Miazzina;VB;Piemonte;103045;28817 +F483;Montecrestese;VB;Piemonte;103046;28864 +F639;Montescheno;VB;Piemonte;103047;28843 +F932;Nonio;VB;Piemonte;103048;28891 +G007;Oggebbio;VB;Piemonte;103049;28824 +G062;Omegna;VB;Piemonte;103050;28887 +G117;Ornavasso;VB;Piemonte;103051;28877 +G280;Pallanzeno;VB;Piemonte;103052;28884 +G600;Piedimulera;VB;Piemonte;103053;28885 +G658;Pieve Vergonte;VB;Piemonte;103054;28886 +H030;Premeno;VB;Piemonte;103055;28818 +H033;Premia;VB;Piemonte;103056;28866 +H037;Premosello-Chiovenda;VB;Piemonte;103057;28803 +H106;Quarna Sopra;VB;Piemonte;103058;28898 +H107;Quarna Sotto;VB;Piemonte;103059;28896 +H203;Re;VB;Piemonte;103060;28856 +H777;San Bernardino Verbano;VB;Piemonte;103061;28804 +I249;Santa Maria Maggiore;VB;Piemonte;103062;28857 +I976;Stresa;VB;Piemonte;103064;28838 +L187;Toceno;VB;Piemonte;103065;28858 +L333;Trarego Viggiona;VB;Piemonte;103066;28826 +L336;Trasquera;VB;Piemonte;103067;28868 +L450;Trontano;VB;Piemonte;103068;28859 +L651;Valstrona;VB;Piemonte;103069;28897 +L666;Vanzone con San Carlo;VB;Piemonte;103070;28879 +L691;Varzo;VB;Piemonte;103071;28868 +L746;Verbania;VB;Piemonte;103072;28922 +L889;Vignone;VB;Piemonte;103074;28819 +L906;Villadossola;VB;Piemonte;103075;28844 +M042;Villette;VB;Piemonte;103076;28856 +M111;Vogogna;VB;Piemonte;103077;28805 +M370;Borgomezzavalle;VB;Piemonte;103078; +M404;Valle Cannobina;VB;Piemonte;103079; +A087;Agrate Brianza;MB;Lombardia;108001;20864 +A096;Aicurzio;MB;Lombardia;108002;20886 +A159;Albiate;MB;Lombardia;108003;20847 +A376;Arcore;MB;Lombardia;108004;20862 +A668;Barlassina;MB;Lombardia;108005;20825 +A759;Bellusco;MB;Lombardia;108006;20882 +A802;Bernareggio;MB;Lombardia;108007;20881 +A818;Besana in Brianza;MB;Lombardia;108008;20842 +A849;Biassono;MB;Lombardia;108009;20853 +B105;Bovisio-Masciago;MB;Lombardia;108010;20813 +B187;Briosco;MB;Lombardia;108011;20836 +B212;Brugherio;MB;Lombardia;108012;20861 +B272;Burago di Molgora;MB;Lombardia;108013;20875 +B501;Camparada;MB;Lombardia;108014;20857 +B729;Carate Brianza;MB;Lombardia;108015;20841 +B798;Carnate;MB;Lombardia;108016;20866 +C395;Cavenago di Brianza;MB;Lombardia;108017;20873 +C512;Ceriano Laghetto;MB;Lombardia;108018;20816 +C566;Cesano Maderno;MB;Lombardia;108019;20811 +C820;Cogliate;MB;Lombardia;108020;20815 +C952;Concorezzo;MB;Lombardia;108021;20863 +D038;Correzzana;MB;Lombardia;108022;20856 +D286;Desio;MB;Lombardia;108023;20832 +E063;Giussano;MB;Lombardia;108024;20833 +E504;Lazzate;MB;Lombardia;108025;20824 +E550;Lesmo;MB;Lombardia;108026;20855 +E591;Limbiate;MB;Lombardia;108027;20812 +E617;Lissone;MB;Lombardia;108028;20851 +E786;Macherio;MB;Lombardia;108029;20846 +F078;Meda;MB;Lombardia;108030;20821 +F165;Mezzago;MB;Lombardia;108031;20883 +F247;Misinto;MB;Lombardia;108032;20826 +F704;Monza;MB;Lombardia;108033;20900 +F797;Muggiò;MB;Lombardia;108034;20835 +F944;Nova Milanese;MB;Lombardia;108035;20834 +G116;Ornago;MB;Lombardia;108036;20876 +H233;Renate;MB;Lombardia;108037;20838 +H537;Ronco Briantino;MB;Lombardia;108038;20885 +I625;Seregno;MB;Lombardia;108039;20831 +I709;Seveso;MB;Lombardia;108040;20822 +I878;Sovico;MB;Lombardia;108041;20845 +I998;Sulbiate;MB;Lombardia;108042;20884 +L434;Triuggio;MB;Lombardia;108043;20844 +L511;Usmate Velate;MB;Lombardia;108044;20865 +L677;Varedo;MB;Lombardia;108045;20814 +L704;Vedano al Lambro;MB;Lombardia;108046;20854 +L709;Veduggio con Colzano;MB;Lombardia;108047;20837 +L744;Verano Brianza;MB;Lombardia;108048;20843 +M017;Villasanta;MB;Lombardia;108049;20852 +M052;Vimercate;MB;Lombardia;108050;20871 +B289;Busnago;MB;Lombardia;108051;20874 +B671;Caponago;MB;Lombardia;108052;20867 +D019;Cornate d'Adda;MB;Lombardia;108053;20872 +E530;Lentate sul Seveso;MB;Lombardia;108054;20823 +H529;Roncello;MB;Lombardia;108055;20877 +A233;Altidona;FM;Marche;109001;63824 +A252;Amandola;FM;Marche;109002;63857 +A760;Belmonte Piceno;FM;Marche;109003;63838 +B534;Campofilone;FM;Marche;109004;63828 +D477;Falerone;FM;Marche;109005;63837 +D542;Fermo;FM;Marche;109006;63900 +D760;Francavilla d'Ete;FM;Marche;109007;63816 +E208;Grottazzolina;FM;Marche;109008;63844 +E447;Lapedona;FM;Marche;109009;63823 +E807;Magliano di Tenna;FM;Marche;109010;63832 +F021;Massa Fermana;FM;Marche;109011;63834 +F379;Monsampietro Morico;FM;Marche;109012;63842 +F428;Montappone;FM;Marche;109013;63835 +F493;Montefalcone Appennino;FM;Marche;109014;63855 +F509;Montefortino;FM;Marche;109015;63858 +F517;Monte Giberto;FM;Marche;109016;63846 +F520;Montegiorgio;FM;Marche;109017;63833 +F522;Montegranaro;FM;Marche;109018;63812 +F536;Monteleone di Fermo;FM;Marche;109019;63841 +F549;Montelparo;FM;Marche;109020;63853 +F599;Monte Rinaldo;FM;Marche;109021;63852 +F614;Monterubbiano;FM;Marche;109022;63825 +F626;Monte San Pietrangeli;FM;Marche;109023;63815 +F653;Monte Urano;FM;Marche;109024;63813 +F664;Monte Vidon Combatte;FM;Marche;109025;63847 +F665;Monte Vidon Corrado;FM;Marche;109026;63836 +F697;Montottone;FM;Marche;109027;63843 +F722;Moresco;FM;Marche;109028;63826 +G137;Ortezzano;FM;Marche;109029;63851 +G403;Pedaso;FM;Marche;109030;63827 +G516;Petritoli;FM;Marche;109031;63848 +G873;Ponzano di Fermo;FM;Marche;109032;63845 +G920;Porto San Giorgio;FM;Marche;109033;63822 +G921;Porto Sant'Elpidio;FM;Marche;109034;63821 +H182;Rapagnano;FM;Marche;109035;63831 +I315;Santa Vittoria in Matenano;FM;Marche;109036;63854 +I324;Sant'Elpidio a Mare;FM;Marche;109037;63811 +C070;Servigliano;FM;Marche;109038;63839 +I774;Smerillo;FM;Marche;109039;63856 +L279;Torre San Patrizio;FM;Marche;109040;63814 +A285;Andria;BT;Puglia;110001;76123 +A669;Barletta;BT;Puglia;110002;76121 +A883;Bisceglie;BT;Puglia;110003;76011 +B619;Canosa di Puglia;BT;Puglia;110004;76012 +E946;Margherita di Savoia;BT;Puglia;110005;76016 +F220;Minervino Murge;BT;Puglia;110006;76013 +H839;San Ferdinando di Puglia;BT;Puglia;110007;76017 +I907;Spinazzola;BT;Puglia;110008;76014 +L328;Trani;BT;Puglia;110009;76125 +B915;Trinitapoli;BT;Puglia;110010;76015 +A192;Alghero;SS;Sardegna;112001;07041 +A287;Anela;SS;Sardegna;112002;07010 +A379;Ardara;SS;Sardegna;112003;07010 +A606;Banari;SS;Sardegna;112004;07040 +A781;Benetutti;SS;Sardegna;112005;07010 +A827;Bessude;SS;Sardegna;112006;07040 +A976;Bonnanaro;SS;Sardegna;112007;07043 +A977;Bono;SS;Sardegna;112008;07011 +A978;Bonorva;SS;Sardegna;112009;07012 +B064;Borutta;SS;Sardegna;112010;07040 +B094;Bottidda;SS;Sardegna;112011;07010 +B264;Bultei;SS;Sardegna;112012;07010 +B265;Bulzi;SS;Sardegna;112013;07030 +B276;Burgos;SS;Sardegna;112014;07010 +B772;Cargeghe;SS;Sardegna;112015;07030 +C272;Castelsardo;SS;Sardegna;112016;07031 +C600;Cheremule;SS;Sardegna;112017;07040 +C613;Chiaramonti;SS;Sardegna;112018;07030 +C818;Codrongianos;SS;Sardegna;112019;07040 +D100;Cossoine;SS;Sardegna;112020;07010 +M292;Erula;SS;Sardegna;112021;07030 +D441;Esporlatu;SS;Sardegna;112022;07010 +D637;Florinas;SS;Sardegna;112023;07030 +E019;Giave;SS;Sardegna;112024;07010 +E285;Illorai;SS;Sardegna;112025;07010 +E376;Ittireddu;SS;Sardegna;112026;07010 +E377;Ittiri;SS;Sardegna;112027;07044 +E401;Laerru;SS;Sardegna;112028;07030 +E902;Mara;SS;Sardegna;112029;07010 +E992;Martis;SS;Sardegna;112030;07030 +F542;Monteleone Rocca Doria;SS;Sardegna;112031;07010 +F721;Mores;SS;Sardegna;112032;07013 +F818;Muros;SS;Sardegna;112033;07030 +F975;Nughedu San Nicolò;SS;Sardegna;112034;07010 +F976;Nule;SS;Sardegna;112035;07010 +F977;Nulvi;SS;Sardegna;112036;07032 +G046;Olmedo;SS;Sardegna;112037;07040 +G156;Osilo;SS;Sardegna;112038;07033 +G178;Ossi;SS;Sardegna;112039;07045 +G203;Ozieri;SS;Sardegna;112040;07014 +G225;Padria;SS;Sardegna;112041;07015 +G376;Pattada;SS;Sardegna;112042;07016 +G450;Perfugas;SS;Sardegna;112043;07034 +G740;Ploaghe;SS;Sardegna;112044;07017 +G924;Porto Torres;SS;Sardegna;112045;07046 +G962;Pozzomaggiore;SS;Sardegna;112046;07018 +H095;Putifigari;SS;Sardegna;112047;07040 +H507;Romana;SS;Sardegna;112048;07010 +M284;Santa Maria Coghinas;SS;Sardegna;112049;07030 +I452;Sassari;SS;Sardegna;112050;07100 +I565;Sedini;SS;Sardegna;112051;07035 +I598;Semestene;SS;Sardegna;112052;07010 +I614;Sennori;SS;Sardegna;112053;07036 +I732;Siligo;SS;Sardegna;112054;07040 +I863;Sorso;SS;Sardegna;112055;07037 +M290;Stintino;SS;Sardegna;112056;07040 +M282;Tergu;SS;Sardegna;112057;07030 +L158;Thiesi;SS;Sardegna;112058;07047 +L180;Tissi;SS;Sardegna;112059;07040 +L235;Torralba;SS;Sardegna;112060;07048 +L464;Tula;SS;Sardegna;112061;07010 +L503;Uri;SS;Sardegna;112062;07040 +L509;Usini;SS;Sardegna;112063;07049 +L604;Valledoria;SS;Sardegna;112064;07039 +M259;Viddalba;SS;Sardegna;112065;07030 +L989;Villanova Monteleone;SS;Sardegna;112066;07019 +A069;Aggius;OT;Sardegna;113001;07020 +H848;Aglientu;OT;Sardegna;113002;07020 +A115;Alà dei Sardi;OT;Sardegna;113003;07020 +A453;Arzachena;OT;Sardegna;113004;07021 +M214;Badesi;OT;Sardegna;113005;07030 +A789;Berchidda;OT;Sardegna;113006;07022,08020 +B063;Bortigiadas;OT;Sardegna;113007;07030 +B246;Buddusò;OT;Sardegna;113008;07020 +B248;Budoni;OT;Sardegna;113009;08020 +B378;Calangianus;OT;Sardegna;113010;07023 +M274;Golfo Aranci;OT;Sardegna;113011;07020 +E425;La Maddalena;OT;Sardegna;113012;07024,09012 +M275;Loiri Porto San Paolo;OT;Sardegna;113013;07020 +E747;Luogosanto;OT;Sardegna;113014;07020 +E752;Luras;OT;Sardegna;113015;07025 +F667;Monti;OT;Sardegna;113016;07020 +G015;Olbia;OT;Sardegna;113017;07026 +G153;Oschiri;OT;Sardegna;113018;07027 +M301;Padru;OT;Sardegna;113019;07020 +G258;Palau;OT;Sardegna;113020;07020 +I329;San Teodoro;OT;Sardegna;113021; +I312;Santa Teresa Gallura;OT;Sardegna;113022;07028 +M276;Sant'Antonio di Gallura;OT;Sardegna;113023;07030 +L088;Telti;OT;Sardegna;113024;07020 +L093;Tempio Pausania;OT;Sardegna;113025;07029 +L428;Trinità d'Agultu e Vignola;OT;Sardegna;113026;07038 +A407;Aritzo;NU;Sardegna;114001;08031 +A492;Atzara;NU;Sardegna;114002;08030 +A503;Austis;NU;Sardegna;114003;08030 +A776;Belvì;NU;Sardegna;114004;08030 +A880;Birori;NU;Sardegna;114005;08010 +A895;Bitti;NU;Sardegna;114006;08021 +A948;Bolotana;NU;Sardegna;114007;08011 +B056;Borore;NU;Sardegna;114008;08016 +B062;Bortigali;NU;Sardegna;114009;08012 +D287;Desulo;NU;Sardegna;114010;08032 +D345;Dorgali;NU;Sardegna;114011;08022 +D376;Dualchi;NU;Sardegna;114012;08010 +D665;Fonni;NU;Sardegna;114013;08023 +D842;Gadoni;NU;Sardegna;114014;08030 +D888;Galtellì;NU;Sardegna;114015;08020 +D947;Gavoi;NU;Sardegna;114016;08020 +E323;Irgoli;NU;Sardegna;114017;08020 +E517;Lei;NU;Sardegna;114018;08010 +E646;Loculi;NU;Sardegna;114019;08020 +E647;Lodè;NU;Sardegna;114020;08020 +E649;Lodine;NU;Sardegna;114021;08020 +E736;Lula;NU;Sardegna;114022;08020 +E788;Macomer;NU;Sardegna;114023;08015 +E874;Mamoiada;NU;Sardegna;114024;08024 +F073;Meana Sardo;NU;Sardegna;114025;08030 +F933;Noragugume;NU;Sardegna;114026;08010 +F979;Nuoro;NU;Sardegna;114027;08100 +G031;Oliena;NU;Sardegna;114028;08025 +G044;Ollolai;NU;Sardegna;114029;08020 +G058;Olzai;NU;Sardegna;114030;08020 +G064;Onanì;NU;Sardegna;114031;08020 +G070;Onifai;NU;Sardegna;114032;08020 +G071;Oniferi;NU;Sardegna;114033;08020 +G084;Orani;NU;Sardegna;114034;08026 +G097;Orgosolo;NU;Sardegna;114035;08027 +G119;Orosei;NU;Sardegna;114036;08028 +G120;Orotelli;NU;Sardegna;114037;08020 +G146;Ortueri;NU;Sardegna;114038;08036 +G147;Orune;NU;Sardegna;114039;08020 +G154;Osidda;NU;Sardegna;114040;08020 +G191;Ottana;NU;Sardegna;114041;08020 +G201;Ovodda;NU;Sardegna;114042;08020 +G929;Posada;NU;Sardegna;114043;08020 +I448;Sarule;NU;Sardegna;114044;08020 +I707;Seulo;NU;Sardegna;114045;08030 +I730;Silanus;NU;Sardegna;114046;08017 +I748;Sindia;NU;Sardegna;114047;08018 +I751;Siniscola;NU;Sardegna;114048;08029 +I851;Sorgono;NU;Sardegna;114049;08038 +L153;Teti;NU;Sardegna;114050;08030 +L160;Tiana;NU;Sardegna;114051;08020 +L202;Tonara;NU;Sardegna;114052;08039 +L231;Torpè;NU;Sardegna;114053;08020 +A007;Abbasanta;OR;Sardegna;115001;09071 +A097;Aidomaggiore;OR;Sardegna;115002;09070 +A126;Albagiara;OR;Sardegna;115003;09090 +A180;Ales;OR;Sardegna;115004;09091 +A204;Allai;OR;Sardegna;115005;09080 +A357;Arborea;OR;Sardegna;115006;09092 +A380;Ardauli;OR;Sardegna;115007;09081 +A477;Assolo;OR;Sardegna;115008;09080 +A480;Asuni;OR;Sardegna;115009;09080 +A614;Baradili;OR;Sardegna;115010;09090 +A621;Baratili San Pietro;OR;Sardegna;115011;09070 +A655;Baressa;OR;Sardegna;115012;09090 +A721;Bauladu;OR;Sardegna;115013;09070 +A856;Bidonì;OR;Sardegna;115014;09080 +A960;Bonarcado;OR;Sardegna;115015;09070 +B055;Boroneddu;OR;Sardegna;115016;09080 +B068;Bosa;OR;Sardegna;115017;08013 +B281;Busachi;OR;Sardegna;115018;09082 +B314;Cabras;OR;Sardegna;115019;09072 +D200;Cuglieri;OR;Sardegna;115020;09073 +D214;Curcuris;OR;Sardegna;115021;09090 +D640;Flussio;OR;Sardegna;115022;08010 +D695;Fordongianus;OR;Sardegna;115023;09083 +E004;Ghilarza;OR;Sardegna;115024;09074 +E087;Gonnoscodina;OR;Sardegna;115025;09090 +D585;Gonnosnò;OR;Sardegna;115026;09090 +E088;Gonnostramatza;OR;Sardegna;115027;09093 +E400;Laconi;OR;Sardegna;115028;08034 +E825;Magomadas;OR;Sardegna;115029;08010 +E972;Marrubiu;OR;Sardegna;115030;09094 +F050;Masullas;OR;Sardegna;115031;09090 +F208;Milis;OR;Sardegna;115032;09070 +F261;Modolo;OR;Sardegna;115033;08019 +F270;Mogorella;OR;Sardegna;115034;09080 +F272;Mogoro;OR;Sardegna;115035;09095 +F698;Montresta;OR;Sardegna;115036;08010 +F727;Morgongiori;OR;Sardegna;115037;09090 +F840;Narbolia;OR;Sardegna;115038;09070 +F867;Neoneli;OR;Sardegna;115039;09080 +F934;Norbello;OR;Sardegna;115040;09070 +F974;Nughedu Santa Vittoria;OR;Sardegna;115041;09080 +F980;Nurachi;OR;Sardegna;115042;09070 +F985;Nureci;OR;Sardegna;115043;09080 +G043;Ollastra;OR;Sardegna;115044;09088 +G113;Oristano;OR;Sardegna;115045;09170 +G286;Palmas Arborea;OR;Sardegna;115046;09090 +G379;Pau;OR;Sardegna;115047;09090 +G384;Paulilatino;OR;Sardegna;115048;09070 +G817;Pompu;OR;Sardegna;115049;09093 +H301;Riola Sardo;OR;Sardegna;115050;09070 +F271;Ruinas;OR;Sardegna;115051;09085 +H661;Sagama;OR;Sardegna;115052;08010 +H756;Samugheo;OR;Sardegna;115053;09086 +A368;San Nicolò d'Arcidano;OR;Sardegna;115054;09097 +I384;San Vero Milis;OR;Sardegna;115055;09070 +I205;Santa Giusta;OR;Sardegna;115056;09096 +I374;Santu Lussurgiu;OR;Sardegna;115057;09075 +I503;Scano di Montiferro;OR;Sardegna;115058;09078 +I564;Sedilo;OR;Sardegna;115059;09076 +I605;Seneghe;OR;Sardegna;115060;09070 +I609;Senis;OR;Sardegna;115061;09080 +I613;Sennariolo;OR;Sardegna;115062;09078 +I717;Siamaggiore;OR;Sardegna;115063;09070 +I718;Siamanna;OR;Sardegna;115064;09080 +I721;Siapiccia;OR;Sardegna;115065;09080 +I742;Simala;OR;Sardegna;115066;09090 +I743;Simaxis;OR;Sardegna;115067;09088 +I749;Sini;OR;Sardegna;115068;09090 +I757;Siris;OR;Sardegna;115069;09090 +I778;Soddì;OR;Sardegna;115070;09080 +I791;Solarussa;OR;Sardegna;115071;09077 +I861;Sorradile;OR;Sardegna;115072;09080 +L006;Suni;OR;Sardegna;115073;08010 +L023;Tadasuni;OR;Sardegna;115074;09080 +L122;Terralba;OR;Sardegna;115075;09098 +L172;Tinnura;OR;Sardegna;115076;08010 +L321;Tramatza;OR;Sardegna;115077;09070 +L393;Tresnuraghes;OR;Sardegna;115078;09079 +L488;Ulà Tirso;OR;Sardegna;115079;09080 +L496;Uras;OR;Sardegna;115080;09099 +L508;Usellus;OR;Sardegna;115081;09090 +I298;Villa Sant'Antonio;OR;Sardegna;115082;09080 +A609;Villa Verde;OR;Sardegna;115083;09090 +L991;Villanova Truschedu;OR;Sardegna;115084;09084 +M030;Villaurbana;OR;Sardegna;115085;09080 +M153;Zeddiani;OR;Sardegna;115086;09070 +M168;Zerfaliu;OR;Sardegna;115087;09070 +A454;Arzana;OG;Sardegna;116001;08040 +A663;Bari Sardo;OG;Sardegna;116002;08042 +A722;Baunei;OG;Sardegna;116003;08040 +M285;Cardedu;OG;Sardegna;116004;08040 +D395;Elini;OG;Sardegna;116005;08040 +D859;Gairo;OG;Sardegna;116006;08040 +E049;Girasole;OG;Sardegna;116007;08040 +E283;Ilbono;OG;Sardegna;116008;08040 +E387;Jerzu;OG;Sardegna;116009;08044 +E441;Lanusei;OG;Sardegna;116010;08045 +E644;Loceri;OG;Sardegna;116011;08040 +E700;Lotzorai;OG;Sardegna;116012;08040 +G158;Osini;OG;Sardegna;116013;08040 +G445;Perdasdefogu;OG;Sardegna;116014;08046 +L036;Talana;OG;Sardegna;116015;08040 +L140;Tertenia;OG;Sardegna;116016;08047 +A355;Tortolì;OG;Sardegna;116017;08048 +L423;Triei;OG;Sardegna;116018;08040 +L489;Ulassai;OG;Sardegna;116019;08040 +L506;Urzulei;OG;Sardegna;116020;08040 +L514;Ussassai;OG;Sardegna;116021;08040 +L953;Villagrande Strisaili;OG;Sardegna;116022;08049 +I706;Seui;OG;Sardegna;116023;08037 +A359;Arbus;VS;Sardegna;117001;09031 +A681;Barumini;VS;Sardegna;117002;09021 +C882;Collinas;VS;Sardegna;117003;09020 +D827;Furtei;VS;Sardegna;117004;09040 +D970;Genuri;VS;Sardegna;117005;09020 +D997;Gesturi;VS;Sardegna;117006;09020 +E085;Gonnosfanadiga;VS;Sardegna;117007;09035 +E270;Guspini;VS;Sardegna;117008;09036 +E464;Las Plassas;VS;Sardegna;117009;09020 +E742;Lunamatrona;VS;Sardegna;117010;09022 +G207;Pabillonis;VS;Sardegna;117011;09030 +G382;Pauli Arbarei;VS;Sardegna;117012;09020 +H738;Samassi;VS;Sardegna;117013;09030 +H856;San Gavino Monreale;VS;Sardegna;117014;09037 +H974;Sanluri;VS;Sardegna;117015;09025 +I428;Sardara;VS;Sardegna;117016;09030 +I570;Segariu;VS;Sardegna;117017;09040 +I647;Serramanna;VS;Sardegna;117018;09038 +I667;Serrenti;VS;Sardegna;117019;09027 +I705;Setzu;VS;Sardegna;117020;09029 +I724;Siddi;VS;Sardegna;117021;09020 +L463;Tuili;VS;Sardegna;117022;09029 +L473;Turri;VS;Sardegna;117023;09020 +L513;Ussaramanna;VS;Sardegna;117024;09020 +L924;Villacidro;VS;Sardegna;117025;09039 +L966;Villamar;VS;Sardegna;117026;09020 +L986;Villanovaforru;VS;Sardegna;117027;09020 +L987;Villanovafranca;VS;Sardegna;117028;09020 +A419;Armungia;CA;Sardegna;118001;09040 +A474;Assemini;CA;Sardegna;118002;09032 +A597;Ballao;CA;Sardegna;118003;09040 +A677;Barrali;CA;Sardegna;118004;09040 +B274;Burcei;CA;Sardegna;118005;09040 +B354;Cagliari;CA;Sardegna;118006;09100,09121-09131,09134 +B675;Capoterra;CA;Sardegna;118007;09012 +M288;Castiadas;CA;Sardegna;118008;09040 +D259;Decimomannu;CA;Sardegna;118009;09033 +D260;Decimoputzu;CA;Sardegna;118010;09010 +D323;Dolianova;CA;Sardegna;118011;09041 +D333;Domus de Maria;CA;Sardegna;118012;09010 +D344;Donori;CA;Sardegna;118013;09040 +D399;Elmas;CA;Sardegna;118014;09030 +D430;Escalaplano;CA;Sardegna;118015;08043 +D431;Escolca;CA;Sardegna;118016;08030 +D443;Esterzili;CA;Sardegna;118017;08030 +D968;Genoni;CA;Sardegna;118018;08030 +D982;Gergei;CA;Sardegna;118019;08030 +D994;Gesico;CA;Sardegna;118020;09040 +E084;Goni;CA;Sardegna;118021;09040 +E234;Guamaggiore;CA;Sardegna;118022;09040 +E252;Guasila;CA;Sardegna;118023;09040 +E336;Isili;CA;Sardegna;118024;08033 +E877;Mandas;CA;Sardegna;118025;09040 +E903;Maracalagonis;CA;Sardegna;118026;09040 +F333;Monastir;CA;Sardegna;118027;09023 +F383;Monserrato;CA;Sardegna;118028;09042 +F808;Muravera;CA;Sardegna;118029;09043 +F981;Nuragus;CA;Sardegna;118030;08030 +F982;Nurallao;CA;Sardegna;118031;08030 +F983;Nuraminis;CA;Sardegna;118032;09024 +F986;Nurri;CA;Sardegna;118033;08035 +G122;Orroli;CA;Sardegna;118034;08030 +G133;Ortacesus;CA;Sardegna;118035;09040 +G669;Pimentel;CA;Sardegna;118036;09020 +H088;Pula;CA;Sardegna;118037;09010 +H118;Quartu Sant'Elena;CA;Sardegna;118038;09045 +H119;Quartucciu;CA;Sardegna;118039;09044 +H659;Sadali;CA;Sardegna;118040;08030 +H739;Samatzai;CA;Sardegna;118041;09020 +H766;San Basilio;CA;Sardegna;118042;09040 +G383;San Nicolò Gerrei;CA;Sardegna;118043;09040 +I166;San Sperate;CA;Sardegna;118044;09026 +I402;San Vito;CA;Sardegna;118045;09040 +I271;Sant'Andrea Frius;CA;Sardegna;118046;09040 +I443;Sarroch;CA;Sardegna;118047;09018 +I580;Selargius;CA;Sardegna;118048;09047 +I582;Selegas;CA;Sardegna;118049;09040 +I615;Senorbì;CA;Sardegna;118050;09040 +I624;Serdiana;CA;Sardegna;118051;09040 +I668;Serri;CA;Sardegna;118052;08030 +I695;Sestu;CA;Sardegna;118053;09028 +I699;Settimo San Pietro;CA;Sardegna;118054;09040 +I734;Siliqua;CA;Sardegna;118056;09010 +I735;Silius;CA;Sardegna;118057;09040 +I752;Sinnai;CA;Sardegna;118058;09048 +I765;Siurgus Donigala;CA;Sardegna;118059;09040 +I797;Soleminis;CA;Sardegna;118060;09040 +I995;Suelli;CA;Sardegna;118061;09040 +L512;Ussana;CA;Sardegna;118063;09020 +L521;Uta;CA;Sardegna;118064;09010 +L613;Vallermosa;CA;Sardegna;118065;09010 +I118;Villa San Pietro;CA;Sardegna;118066;09010 +L992;Villanova Tulo;CA;Sardegna;118067;08030 +L998;Villaputzu;CA;Sardegna;118068;09040 +M016;Villasalto;CA;Sardegna;118069;09040 +B738;Villasimius;CA;Sardegna;118070;09049 +M025;Villasor;CA;Sardegna;118071;09034 +M026;Villaspeciosa;CA;Sardegna;118072;09010 +B250;Buggerru;CI;Sardegna;119001;09010 +B383;Calasetta;CI;Sardegna;119002;09011 +B745;Carbonia;CI;Sardegna;119003;09013 +B789;Carloforte;CI;Sardegna;119004;09014 +D334;Domusnovas;CI;Sardegna;119005;09015 +D639;Fluminimaggiore;CI;Sardegna;119006;09010 +E022;Giba;CI;Sardegna;119007;09010 +E086;Gonnesa;CI;Sardegna;119008;09010 +E281;Iglesias;CI;Sardegna;119009;09016 +M270;Masainas;CI;Sardegna;119010;09010 +F822;Musei;CI;Sardegna;119011;09010 +F841;Narcao;CI;Sardegna;119012;09010 +F991;Nuxis;CI;Sardegna;119013;09010 +G446;Perdaxius;CI;Sardegna;119014;09010 +M291;Piscinas;CI;Sardegna;119015;09010 +G922;Portoscuso;CI;Sardegna;119016;09010 +G287;San Giovanni Suergiu;CI;Sardegna;119017;09010 +I182;Santadi;CI;Sardegna;119018;09010 +M209;Sant'Anna Arresi;CI;Sardegna;119019;09010 +I294;Sant'Antioco;CI;Sardegna;119020;09017 +L337;Tratalias;CI;Sardegna;119021;09010 +L968;Villamassargia;CI;Sardegna;119022;09010 +M278;Villaperuccio;CI;Sardegna;119023;09010 +L154;Teulada;CI;Sardegna;119024;09019 diff --git a/src/Khaemhat.Fiscal.Italy/Data/province.csv b/src/Khaemhat.Fiscal.Italy/Data/province.csv new file mode 100644 index 0000000..1a6808a --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/Data/province.csv @@ -0,0 +1,111 @@ +sigla;denominazione;regione +AG;Agrigento;Sicilia +AL;Alessandria;Piemonte +AN;Ancona;Marche +AO;Valle d'Aosta/Vallée d'Aoste;Valle d'Aosta/Vallée d'Aoste +AP;Ascoli Piceno;Marche +AQ;L'Aquila;Abruzzo +AR;Arezzo;Toscana +AT;Asti;Piemonte +AV;Avellino;Campania +BA;Bari;Puglia +BG;Bergamo;Lombardia +BI;Biella;Piemonte +BL;Belluno;Veneto +BN;Benevento;Campania +BO;Bologna;Emilia-Romagna +BR;Brindisi;Puglia +BS;Brescia;Lombardia +BT;Barletta-Andria-Trani;Puglia +BZ;Bolzano/Bozen;Trentino-Alto Adige/Südtirol +CA;Cagliari;Sardegna +CB;Campobasso;Molise +CE;Caserta;Campania +CH;Chieti;Abruzzo +CI;Sulcis Iglesiente;Sardegna +CL;Caltanissetta;Sicilia +CN;Cuneo;Piemonte +CO;Como;Lombardia +CR;Cremona;Lombardia +CS;Cosenza;Calabria +CT;Catania;Sicilia +CZ;Catanzaro;Calabria +EN;Enna;Sicilia +FC;Forlì-Cesena;Emilia-Romagna +FE;Ferrara;Emilia-Romagna +FG;Foggia;Puglia +FI;Firenze;Toscana +FM;Fermo;Marche +FR;Frosinone;Lazio +GE;Genova;Liguria +GO;Gorizia;Friuli-Venezia Giulia +GR;Grosseto;Toscana +IM;Imperia;Liguria +IS;Isernia;Molise +KR;Crotone;Calabria +LC;Lecco;Lombardia +LE;Lecce;Puglia +LI;Livorno;Toscana +LO;Lodi;Lombardia +LT;Latina;Lazio +LU;Lucca;Toscana +MB;Monza e della Brianza;Lombardia +MC;Macerata;Marche +ME;Messina;Sicilia +MI;Milano;Lombardia +MN;Mantova;Lombardia +MO;Modena;Emilia-Romagna +MS;Massa-Carrara;Toscana +MT;Matera;Basilicata +NA;Napoli;Campania +NO;Novara;Piemonte +NU;Nuoro;Sardegna +OG;Ogliastra;Sardegna +OR;Oristano;Sardegna +OT;Gallura Nord-Est Sardegna;Sardegna +PA;Palermo;Sicilia +PC;Piacenza;Emilia-Romagna +PD;Padova;Veneto +PE;Pescara;Abruzzo +PG;Perugia;Umbria +PI;Pisa;Toscana +PN;Pordenone;Friuli-Venezia Giulia +PO;Prato;Toscana +PR;Parma;Emilia-Romagna +PT;Pistoia;Toscana +PU;Pesaro e Urbino;Marche +PV;Pavia;Lombardia +PZ;Potenza;Basilicata +RA;Ravenna;Emilia-Romagna +RC;Reggio Calabria;Calabria +RE;Reggio nell'Emilia;Emilia-Romagna +RG;Ragusa;Sicilia +RI;Rieti;Lazio +RM;Roma;Lazio +RN;Rimini;Emilia-Romagna +RO;Rovigo;Veneto +SA;Salerno;Campania +SI;Siena;Toscana +SO;Sondrio;Lombardia +SP;La Spezia;Liguria +SR;Siracusa;Sicilia +SS;Sassari;Sardegna +SV;Savona;Liguria +TA;Taranto;Puglia +TE;Teramo;Abruzzo +TN;Trento;Trentino-Alto Adige/Südtirol +TO;Torino;Piemonte +TP;Trapani;Sicilia +TR;Terni;Umbria +TS;Trieste;Friuli-Venezia Giulia +TV;Treviso;Veneto +UD;Udine;Friuli-Venezia Giulia +VA;Varese;Lombardia +VB;Verbano-Cusio-Ossola;Piemonte +VC;Vercelli;Piemonte +VE;Venezia;Veneto +VI;Vicenza;Veneto +VR;Verona;Veneto +VS;Medio Campidano;Sardegna +VT;Viterbo;Lazio +VV;Vibo Valentia;Calabria diff --git a/src/Khaemhat.Fiscal.Italy/FatturaPaCodeLists.cs b/src/Khaemhat.Fiscal.Italy/FatturaPaCodeLists.cs new file mode 100644 index 0000000..2f9806d --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/FatturaPaCodeLists.cs @@ -0,0 +1,198 @@ +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy; + +/// +/// The code lists of the FatturaPA technical specifications of the Agenzia delle Entrate (SPEC §11.9). Descriptions +/// follow the official tables, shortened where the official text runs to several lines. +/// +/// +/// is the version checked at each release (ADR 0025): 1.9 (in force from 1 April 2025) +/// added TD29 and redefined TD20; 1.9.1 (published 31 March 2026, in force from 15 May 2026) changed no code list. +/// +public static class FatturaPaCodeLists +{ + /// The version of the technical specifications that this pack follows. + public const string SpecVersion = "1.9.1"; + + /// The date from which is in force. + public static readonly DateOnly SpecInForceFrom = new(2026, 5, 15); + + /// Transmission formats (FormatoTrasmissione). + public static CodeList TransmissionFormats { get; } = new("TransmissionFormats", + [ + new("FPA12", "Fattura verso pubbliche amministrazioni"), + new("FPR12", "Fattura verso privati"), + new("FSM10", "Fattura semplificata"), + ]); + + /// Document types (TipoDocumento). + public static CodeList DocumentTypes { get; } = new("DocumentTypes", + [ + new("TD01", "Fattura"), + new("TD02", "Acconto/anticipo su fattura"), + new("TD03", "Acconto/anticipo su parcella"), + new("TD04", "Nota di credito"), + new("TD05", "Nota di debito"), + new("TD06", "Parcella"), + new("TD07", "Fattura semplificata"), + new("TD08", "Nota di credito semplificata"), + new("TD09", "Nota di debito semplificata"), + new("TD16", "Integrazione fattura reverse charge interno"), + new("TD17", "Integrazione/autofattura per acquisto servizi dall'estero"), + new("TD18", "Integrazione per acquisto di beni intracomunitari"), + new("TD19", "Integrazione/autofattura per acquisto di beni ex art. 17 c. 2 DPR 633/72"), + new("TD20", "Autofattura per regolarizzazione e integrazione delle fatture (art. 6 c. 8 e 9-bis D.Lgs. 471/97 o art. 46 c. 5 DL 331/93)"), + new("TD21", "Autofattura per splafonamento"), + new("TD22", "Estrazione beni da deposito IVA"), + new("TD23", "Estrazione beni da deposito IVA con versamento dell'IVA"), + new("TD24", "Fattura differita di cui all'art. 21 c. 4 lett. a) DPR 633/72"), + new("TD25", "Fattura differita di cui all'art. 21 c. 4 terzo periodo lett. b) DPR 633/72"), + new("TD26", "Cessione di beni ammortizzabili e per passaggi interni (art. 36 DPR 633/72)"), + new("TD27", "Fattura per autoconsumo o per cessioni gratuite senza rivalsa"), + new("TD28", "Acquisti da San Marino con IVA (fattura cartacea)"), + new("TD29", "Comunicazione per omessa o irregolare fatturazione (art. 6 c. 8 D.Lgs. 471/97)"), + ]); + + /// Document types accepted only in the simplified format FSM10. + public static IReadOnlySet SimplifiedDocumentTypes { get; } = new HashSet(StringComparer.Ordinal) { "TD07", "TD08", "TD09" }; + + /// Payment methods (ModalitaPagamento). + public static CodeList PaymentMethods { get; } = new("PaymentMethods", + [ + new("MP01", "Contanti"), + new("MP02", "Assegno"), + new("MP03", "Assegno circolare"), + new("MP04", "Contanti presso Tesoreria"), + new("MP05", "Bonifico"), + new("MP06", "Vaglia cambiario"), + new("MP07", "Bollettino bancario"), + new("MP08", "Carta di pagamento"), + new("MP09", "RID"), + new("MP10", "RID utenze"), + new("MP11", "RID veloce"), + new("MP12", "RIBA"), + new("MP13", "MAV"), + new("MP14", "Quietanza erario"), + new("MP15", "Giroconto su conti di contabilità speciale"), + new("MP16", "Domiciliazione bancaria"), + new("MP17", "Domiciliazione postale"), + new("MP18", "Bollettino di c/c postale"), + new("MP19", "SEPA Direct Debit"), + new("MP20", "SEPA Direct Debit CORE"), + new("MP21", "SEPA Direct Debit B2B"), + new("MP22", "Trattenuta su somme già riscosse"), + new("MP23", "PagoPA"), + ]); + + /// Payment conditions (CondizioniPagamento). + public static CodeList PaymentConditions { get; } = new("PaymentConditions", + [ + new("TP01", "Pagamento a rate"), + new("TP02", "Pagamento completo"), + new("TP03", "Anticipo"), + ]); + + /// Tax regimes of the seller (RegimeFiscale); RF03 no longer exists. + public static CodeList TaxRegimes { get; } = new("TaxRegimes", + [ + new("RF01", "Ordinario"), + new("RF02", "Contribuenti minimi (art. 1 c. 96-117 L. 244/2007)"), + new("RF03", "Nuove iniziative produttive (abrogato)", Obsolete: true), + new("RF04", "Agricoltura e attività connesse e pesca (artt. 34 e 34-bis DPR 633/72)"), + new("RF05", "Vendita sali e tabacchi (art. 74 c. 1 DPR 633/72)"), + new("RF06", "Commercio dei fiammiferi (art. 74 c. 1 DPR 633/72)"), + new("RF07", "Editoria (art. 74 c. 1 DPR 633/72)"), + new("RF08", "Gestione di servizi di telefonia pubblica (art. 74 c. 1 DPR 633/72)"), + new("RF09", "Rivendita di documenti di trasporto pubblico e di sosta (art. 74 c. 1 DPR 633/72)"), + new("RF10", "Intrattenimenti, giochi e altre attività di cui alla tariffa allegata al DPR 640/72 (art. 74 c. 6 DPR 633/72)"), + new("RF11", "Agenzie di viaggi e turismo (art. 74-ter DPR 633/72)"), + new("RF12", "Agriturismo (art. 5 c. 2 L. 413/91)"), + new("RF13", "Vendite a domicilio (art. 25-bis c. 6 DPR 600/73)"), + new("RF14", "Rivendita di beni usati, oggetti d'arte, d'antiquariato o da collezione (art. 36 DL 41/95)"), + new("RF15", "Agenzie di vendite all'asta di oggetti d'arte, antiquariato o da collezione (art. 40-bis DL 41/95)"), + new("RF16", "IVA per cassa P.A. (art. 6 c. 5 DPR 633/72)"), + new("RF17", "IVA per cassa (art. 32-bis DL 83/2012)"), + new("RF18", "Altro"), + new("RF19", "Regime forfettario (art. 1 c. 54-89 L. 190/2014)"), + ]); + + /// Withholding types (TipoRitenuta). + public static CodeList WithholdingTypes { get; } = new("WithholdingTypes", + [ + new("RT01", "Ritenuta persone fisiche"), + new("RT02", "Ritenuta persone giuridiche"), + new("RT03", "Contributo INPS"), + new("RT04", "Contributo ENASARCO"), + new("RT05", "Contributo ENPAM"), + new("RT06", "Altro contributo previdenziale"), + ]); + + /// Payment reasons of the withholding (CausalePagamento, as in the CU form). + public static CodeList WithholdingReasons { get; } = new("WithholdingReasons", + [ + new("A", "Prestazioni di lavoro autonomo rientranti nell'esercizio di arte o professione abituale"), + new("B", "Utilizzazione economica, da parte dell'autore o dell'inventore, di opere dell'ingegno"), + new("C", "Utili derivanti da contratti di associazione in partecipazione e cointeressenza (solo apporto di lavoro)"), + new("D", "Utili spettanti ai soci promotori e ai soci fondatori delle società di capitali"), + new("E", "Levata di protesti cambiari da parte dei segretari comunali"), + new("G", "Indennità corrisposte per la cessazione di attività sportiva professionale"), + new("H", "Indennità corrisposte per la cessazione dei rapporti di agenzia"), + new("I", "Indennità corrisposte per la cessazione da funzioni notarili"), + new("L", "Utilizzazione economica di opere dell'ingegno da parte di soggetto diverso dall'autore"), + new("L1", "Redditi da utilizzazione economica di opere dell'ingegno acquisiti a titolo oneroso"), + new("M", "Prestazioni di lavoro autonomo non esercitate abitualmente"), + new("M1", "Redditi derivanti dall'assunzione di obblighi di fare, non fare o permettere"), + new("M2", "Prestazioni di lavoro autonomo non esercitate abitualmente con obbligo di iscrizione alla Gestione Separata ENPAPI"), + new("N", "Indennità di trasferta, rimborsi forfetari, premi e compensi nell'esercizio diretto di attività sportive dilettantistiche"), + new("O", "Prestazioni di lavoro autonomo non esercitate abitualmente, senza obbligo di iscrizione alla gestione separata"), + new("O1", "Redditi da obblighi di fare, non fare o permettere, senza obbligo di iscrizione alla gestione separata"), + new("P", "Compensi a soggetti non residenti privi di stabile organizzazione per l'uso di attrezzature"), + new("Q", "Provvigioni ad agente o rappresentante di commercio monomandatario"), + new("R", "Provvigioni ad agente o rappresentante di commercio plurimandatario"), + new("S", "Provvigioni a commissionario"), + new("T", "Provvigioni a mediatore"), + new("U", "Provvigioni a procacciatore di affari"), + new("V", "Provvigioni a incaricato per le vendite a domicilio o porta a porta"), + new("V1", "Redditi derivanti da attività commerciali non esercitate abitualmente"), + new("V2", "Prestazioni non esercitate abitualmente rese dagli incaricati alla vendita diretta a domicilio"), + new("W", "Corrispettivi per prestazioni relative a contratti d'appalto (art. 25-ter DPR 600/73)"), + new("X", "Canoni corrisposti nel 2004 da società o enti residenti (art. 26-quater DPR 600/73)"), + new("Y", "Canoni corrisposti dal 2005 da società o enti residenti (art. 26-quater DPR 600/73)"), + new("Z", "Titolo diverso dai precedenti (sostituito da ZO)", Obsolete: true), + new("ZO", "Titolo diverso dai precedenti"), + ]); + + /// Social security funds (TipoCassa). + public static CodeList SocialSecurityFunds { get; } = new("SocialSecurityFunds", + [ + new("TC01", "Cassa nazionale previdenza e assistenza avvocati e procuratori legali"), + new("TC02", "Cassa previdenza dottori commercialisti"), + new("TC03", "Cassa previdenza e assistenza geometri"), + new("TC04", "Cassa nazionale previdenza e assistenza ingegneri e architetti liberi professionisti"), + new("TC05", "Cassa nazionale del notariato"), + new("TC06", "Cassa nazionale previdenza e assistenza ragionieri e periti commerciali"), + new("TC07", "Ente nazionale assistenza agenti e rappresentanti di commercio (ENASARCO)"), + new("TC08", "Ente nazionale previdenza e assistenza consulenti del lavoro (ENPACL)"), + new("TC09", "Ente nazionale previdenza e assistenza medici (ENPAM)"), + new("TC10", "Ente nazionale previdenza e assistenza farmacisti (ENPAF)"), + new("TC11", "Ente nazionale previdenza e assistenza veterinari (ENPAV)"), + new("TC12", "Ente nazionale previdenza e assistenza impiegati dell'agricoltura (ENPAIA)"), + new("TC13", "Fondo previdenza impiegati imprese di spedizione e agenzie marittime"), + new("TC14", "Istituto nazionale previdenza giornalisti italiani (INPGI)"), + new("TC15", "Opera nazionale assistenza orfani sanitari italiani (ONAOSI)"), + new("TC16", "Cassa autonoma assistenza integrativa giornalisti italiani (CASAGIT)"), + new("TC17", "Ente previdenza periti industriali e periti industriali laureati (EPPI)"), + new("TC18", "Ente previdenza e assistenza pluricategoriale (EPAP)"), + new("TC19", "Ente nazionale previdenza e assistenza biologi (ENPAB)"), + new("TC20", "Ente nazionale previdenza e assistenza professione infermieristica (ENPAPI)"), + new("TC21", "Ente nazionale previdenza e assistenza psicologi (ENPAP)"), + new("TC22", "INPS"), + ]); + + /// Recipient code for consumers and companies without a channel. + public const string RecipientCodeNone = "0000000"; + + /// Recipient code for foreign customers. + public const string RecipientCodeForeign = "XXXXXXX"; +} diff --git a/src/Khaemhat.Fiscal.Italy/ItalianBaseTables.cs b/src/Khaemhat.Fiscal.Italy/ItalianBaseTables.cs new file mode 100644 index 0000000..1b7b629 --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/ItalianBaseTables.cs @@ -0,0 +1,70 @@ +using Khaemhat.Core.Tables; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy; + +/// +/// The Italian rows of the base tables (SPEC §14): payment methods with the FatturaPA codes MP, the usual payment terms +/// (rimessa diretta, bonifico, RiBa at 30/60/90 days end of month) and the document types with their SDI type TD. +/// +public sealed class ItalianBaseTables : IBaseTablesTemplate +{ + private static readonly InstallmentTemplate Now = new(0, false, 100m); + + /// + public IReadOnlyList PaymentMethods { get; } = + [ + new("CONT", "Contanti", "MP01", false), + new("ASS", "Assegno", "MP02", false), + new("BON", "Bonifico bancario", "MP05", true), + new("CARTA", "Carta di pagamento", "MP08", false), + new("RIBA", "Ricevuta bancaria (RiBa)", "MP12", true), + new("MAV", "MAV", "MP13", true), + new("DOM", "Domiciliazione bancaria", "MP16", true), + new("SDD", "Addebito diretto SEPA (SDD Core)", "MP20", true), + new("SDDB", "Addebito diretto SEPA B2B", "MP21", true), + new("PAGOPA", "PagoPA", "MP23", false), + ]; + + /// + public IReadOnlyList PaymentTerms { get; } = + [ + new("RD", "Rimessa diretta", "BON", "TP02", [Now]), + new("CONT", "Contanti alla consegna", "CONT", "TP02", [Now]), + new("ANT", "Pagamento anticipato", "BON", "TP03", [Now]), + new("BB30", "Bonifico 30 gg data fattura", "BON", "TP02", [new(30, false, 100m)]), + new("BB30FM", "Bonifico 30 gg fine mese", "BON", "TP02", [new(30, true, 100m)]), + new("BB60FM", "Bonifico 60 gg fine mese", "BON", "TP02", [new(60, true, 100m)]), + new("BB3060FM", "Bonifico 30-60 gg fine mese", "BON", "TP01", [new(30, true, 50m), new(60, true, 50m)]), + new("RB30FM", "RiBa 30 gg fine mese", "RIBA", "TP02", [new(30, true, 100m)]), + new("RB60FM", "RiBa 60 gg fine mese", "RIBA", "TP02", [new(60, true, 100m)]), + new("RB3060FM", "RiBa 30-60 gg fine mese", "RIBA", "TP01", [new(30, true, 50m), new(60, true, 50m)]), + new("RB306090", "RiBa 30-60-90 gg fine mese", "RIBA", "TP01", [new(30, true, 33.33m), new(60, true, 33.33m), new(90, true, 33.34m)]), + new("SDD30", "Addebito SEPA 30 gg data fattura", "SDD", "TP02", [new(30, false, 100m)]), + ]; + + /// + public IReadOnlyList DocumentTypes { get; } = + [ + new("PRE", "Preventivo", NumeratorKind.Quotation, "PRE", null, null), + new("OC", "Ordine cliente", NumeratorKind.SalesOrder, "ORD", null, null), + new("DDT", "Documento di trasporto", NumeratorKind.DeliveryNote, "DDT", "SCA", null), + new("FI", "Fattura immediata", NumeratorKind.SalesInvoice, "FAT", null, "TD01"), + new("FA", "Fattura accompagnatoria", NumeratorKind.SalesInvoice, "FAT", "SCA", "TD01"), + new("FD", "Fattura differita", NumeratorKind.SalesInvoice, "FAT", null, "TD24"), + new("FACC", "Fattura di acconto", NumeratorKind.SalesInvoice, "FAT", null, "TD02"), + new("NC", "Nota di credito", NumeratorKind.SalesInvoice, "FAT", null, "TD04"), + new("ND", "Nota di debito", NumeratorKind.SalesInvoice, "FAT", null, "TD05"), + new("PAR", "Parcella", NumeratorKind.SalesInvoice, "FAT", null, "TD06"), + new("PF", "Fattura pro forma", NumeratorKind.Other, "PRF", null, null), + new("AF16", "Integrazione reverse charge interno", NumeratorKind.SalesInvoice, "AUT", null, "TD16"), + new("AF17", "Integrazione acquisto servizi dall'estero", NumeratorKind.SalesInvoice, "AUT", null, "TD17"), + new("AF18", "Integrazione acquisto beni intracomunitari", NumeratorKind.SalesInvoice, "AUT", null, "TD18"), + new("AF19", "Integrazione acquisto beni art. 17 c.2", NumeratorKind.SalesInvoice, "AUT", null, "TD19"), + new("OF", "Ordine fornitore", NumeratorKind.PurchaseOrder, "ORF", null, null), + new("DDTF", "DDT fornitore (carico)", NumeratorKind.Inventory, null, "CAR", null), + new("FF", "Fattura fornitore", NumeratorKind.PurchaseInvoice, "PRA", null, null), + new("NCF", "Nota di credito fornitore", NumeratorKind.PurchaseInvoice, "PRA", null, null), + new("MM", "Movimento di magazzino", NumeratorKind.Inventory, "MAG", null, null), + ]; +} diff --git a/src/Khaemhat.Fiscal.Italy/ItalianFiscalCalendar.cs b/src/Khaemhat.Fiscal.Italy/ItalianFiscalCalendar.cs new file mode 100644 index 0000000..0048a24 --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/ItalianFiscalCalendar.cs @@ -0,0 +1,112 @@ +using Khaemhat.Core.Tax; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy; + +/// +/// Italian VAT deadlines (wiki Fiscalità italiana, "Scadenze e regole principali"): +/// +/// monthly VAT by the 16th of the next month; +/// quarterly VAT by the 16th of the second month after the quarter, with 1% interest; the fourth quarter is paid +/// with the annual balance by 16 March; +/// payments due from 1 to 20 August move to 20 August (art. 3-quater DL 16/2012); +/// a deadline on a Saturday, Sunday or public holiday moves to the next working day (art. 7 DL 70/2011). +/// +/// +public sealed class ItalianFiscalCalendar : IFiscalCalendar +{ + /// Interest on quarterly VAT, in percent. + public const decimal QuarterlyInterestRate = 1m; + + /// + public DateOnly VatPaymentDue(TaxPeriod period) + { + ArgumentNullException.ThrowIfNull(period); + DateOnly due; + if (period.Periodicity == VatPeriodicity.Monthly) + { + due = new DateOnly(period.Year, period.Number, 16).AddMonths(1); + } + else if (period.Number == 4) + { + due = new DateOnly(period.Year + 1, 3, 16); + } + else + { + due = new DateOnly(period.End.Year, period.End.Month, 16).AddMonths(2); + } + + if (due.Month == 8 && due.Day <= 20) + { + due = new DateOnly(due.Year, 8, 20); + } + + return NextWorkingDay(due); + } + + /// + public decimal VatInterestRate(VatPeriodicity periodicity) => + periodicity == VatPeriodicity.Quarterly ? QuarterlyInterestRate : 0m; + + /// + public bool IsNonWorkingDay(DateOnly day) => + day.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday || IsPublicHoliday(day); + + /// + public DateOnly NextWorkingDay(DateOnly day) + { + while (IsNonWorkingDay(day)) + { + day = day.AddDays(1); + } + + return day; + } + + /// Whether a day is an Italian national public holiday. + /// The day. + /// for a holiday. + public static bool IsPublicHoliday(DateOnly date) + { + switch ((date.Month, date.Day)) + { + case (1, 1): // Capodanno + case (1, 6): // Epifania + case (4, 25): // Liberazione + case (5, 1): // Festa del lavoro + case (6, 2): // Festa della Repubblica + case (8, 15): // Ferragosto + case (11, 1): // Ognissanti + case (12, 8): // Immacolata + case (12, 25): // Natale + case (12, 26): // Santo Stefano + return true; + case (10, 4) when date.Year >= 2026: // San Francesco, national holiday again from 2026 + return true; + default: + return date == EasterSunday(date.Year).AddDays(1); // Lunedì dell'Angelo + } + } + + /// Easter Sunday of a year (Gregorian calendar, anonymous algorithm). + /// The year. + /// The date. + public static DateOnly EasterSunday(int year) + { + var a = year % 19; + var b = year / 100; + var c = year % 100; + var d = b / 4; + var e = b % 4; + var f = (b + 8) / 25; + var g = (b - f + 1) / 3; + var h = ((19 * a) + b - d - g + 15) % 30; + var i = c / 4; + var k = c % 4; + var l = (32 + (2 * e) + (2 * i) - h - k) % 7; + var m = (a + (11 * h) + (22 * l)) / 451; + var month = (h + l - (7 * m) + 114) / 31; + var day = ((h + l - (7 * m) + 114) % 31) + 1; + return new DateOnly(year, month, day); + } +} diff --git a/src/Khaemhat.Fiscal.Italy/ItalianIdentifiers.cs b/src/Khaemhat.Fiscal.Italy/ItalianIdentifiers.cs new file mode 100644 index 0000000..7955f2a --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/ItalianIdentifiers.cs @@ -0,0 +1,355 @@ +using System.Globalization; +using System.Text; +using Khaemhat.Core.Validation; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy; + +/// +/// Italian VAT numbers (partita IVA): 11 digits, the last a Luhn-like check digit; the first seven (the taxpayer +/// number) cannot be all zeros. +/// +public static class ItalianVatNumberValidator +{ + /// The number without spaces and without the IT prefix. + /// The number as typed. + /// The compact number. + public static string Normalize(string? vatNumber) + { + var compact = string.Concat((vatNumber ?? string.Empty).Where(c => !char.IsWhiteSpace(c) && c != '.' && c != '-')).ToUpperInvariant(); + return compact.StartsWith("IT", StringComparison.Ordinal) ? compact[2..] : compact; + } + + /// Whether a VAT number is valid. + /// The number, with or without prefix. + /// when valid. + public static bool IsValid(string? vatNumber) + { + var value = Normalize(vatNumber); + if (value.Length != 11 || !value.All(char.IsAsciiDigit) || value.StartsWith("0000000", StringComparison.Ordinal)) + { + return false; + } + + return CheckDigit(value[..10]) == value[10] - '0'; + } + + /// The check digit for the first ten digits. + /// Ten digits. + /// The check digit. + public static int CheckDigit(string digits) + { + ArgumentNullException.ThrowIfNull(digits); + var sum = 0; + for (var i = 0; i < digits.Length; i++) + { + var d = digits[i] - '0'; + if (i % 2 == 1) + { + d *= 2; + if (d > 9) + { + d -= 9; + } + } + + sum += d; + } + + return (10 - (sum % 10)) % 10; + } +} + +/// +/// Italian personal tax codes (codice fiscale, DM 23/12/1976): 16 characters for people, with the omocodia +/// substitutions accepted; companies use their 11-digit number. +/// +public static class FiscalCodeValidator +{ + /// Letters that replace digits in omocodic codes: L=0, M=1... V=9. + internal const string OmocodiaLetters = "LMNPQRSTUV"; + + /// Month letters: A=January... T=December. + internal const string MonthLetters = "ABCDEHLMPRST"; + + // Positions (0-based) that hold digits, possibly replaced by omocodia letters. + private static readonly int[] DigitPositions = [6, 7, 9, 10, 12, 13, 14]; + + // Values of characters in odd positions (1st, 3rd... 1-based) for the check character. + private static readonly int[] OddValues = [1, 0, 5, 7, 9, 13, 15, 17, 19, 21, 2, 4, 18, 20, 11, 3, 6, 8, 12, 14, 16, 10, 22, 25, 24, 23]; + + /// The code without spaces, in capitals. + /// The code as typed. + /// The compact code. + public static string Normalize(string? code) => + string.Concat((code ?? string.Empty).Where(c => !char.IsWhiteSpace(c))).ToUpperInvariant(); + + /// Whether a tax code is valid: a 16-character personal code or an 11-digit company code. + /// The code. + /// when valid. + public static bool IsValid(string? code) + { + var value = Normalize(code); + return value.Length == 11 ? ItalianVatNumberValidator.IsValid(value) : IsValidPersonal(value); + } + + /// Whether a 16-character personal code is valid. + /// The code. + /// when valid. + public static bool IsValidPersonal(string? code) + { + var value = Normalize(code); + if (value.Length != 16 || !value.All(char.IsAsciiLetterOrDigit)) + { + return false; + } + + for (var i = 0; i < 16; i++) + { + var isDigitPosition = Array.IndexOf(DigitPositions, i) >= 0; + var c = value[i]; + var ok = isDigitPosition + ? char.IsAsciiDigit(c) || OmocodiaLetters.Contains(c, StringComparison.Ordinal) + : char.IsAsciiLetterUpper(c); + if (!ok) + { + return false; + } + } + + var plain = RemoveOmocodia(value); + var day = int.Parse(plain.AsSpan(9, 2), CultureInfo.InvariantCulture); + return MonthLetters.Contains(value[8], StringComparison.Ordinal) + && day is (>= 1 and <= 31) or (>= 41 and <= 71) + && CheckCharacter(value[..15]) == value[15]; + } + + /// The check character of the first 15 characters. + /// The first 15 characters, in capitals. + /// The check character. + public static char CheckCharacter(string first15) + { + ArgumentNullException.ThrowIfNull(first15); + var sum = 0; + for (var i = 0; i < first15.Length; i++) + { + var c = first15[i]; + var index = char.IsAsciiDigit(c) ? c - '0' : c - 'A'; + sum += i % 2 == 0 ? OddValues[index] : index; + } + + return (char)('A' + (sum % 26)); + } + + /// The code with omocodia letters turned back into digits. + /// A 16-character code. + /// The code with digits in the digit positions. + public static string RemoveOmocodia(string code) + { + ArgumentNullException.ThrowIfNull(code); + var chars = code.ToCharArray(); + foreach (var p in DigitPositions) + { + var i = OmocodiaLetters.IndexOf(chars[p], StringComparison.Ordinal); + if (i >= 0) + { + chars[p] = (char)('0' + i); + } + } + + return new string(chars); + } +} + +/// Computes and decodes Italian personal tax codes. +public static class FiscalCodeCalculator +{ + /// The personal tax code of a person. + /// Surname, name, birth date, sex and cadastral code of the birth place. + /// The 16-character code. + public static string Compute(PersonalTaxCodeData data) + { + ArgumentNullException.ThrowIfNull(data); + var place = FiscalCodeValidator.Normalize(data.BirthPlaceCode); + if (place.Length != 4 || !char.IsAsciiLetterUpper(place[0]) || !place[1..].All(char.IsAsciiDigit)) + { + throw new ArgumentException("The birth place code must be a letter and three digits, such as H501.", nameof(data)); + } + + var day = data.BirthDate.Day + (data.Sex == PersonSex.Female ? 40 : 0); + var first15 = string.Concat( + SurnamePart(data.Surname), + NamePart(data.GivenName), + (data.BirthDate.Year % 100).ToString("00", CultureInfo.InvariantCulture), + FiscalCodeValidator.MonthLetters[data.BirthDate.Month - 1].ToString(), + day.ToString("00", CultureInfo.InvariantCulture), + place); + return first15 + FiscalCodeValidator.CheckCharacter(first15); + } + + /// Reads birth date, sex and place from a personal code. + /// The code. + /// The reference date: a two-digit year after it belongs to the previous century. + /// The data, or for an invalid code. + public static PersonalTaxCodeInfo? Decode(string? code, DateOnly today) + { + if (!FiscalCodeValidator.IsValidPersonal(code)) + { + return null; + } + + var plain = FiscalCodeValidator.RemoveOmocodia(FiscalCodeValidator.Normalize(code)); + var yy = int.Parse(plain.AsSpan(6, 2), CultureInfo.InvariantCulture); + var month = FiscalCodeValidator.MonthLetters.IndexOf(plain[8], StringComparison.Ordinal) + 1; + var day = int.Parse(plain.AsSpan(9, 2), CultureInfo.InvariantCulture); + var sex = day > 40 ? PersonSex.Female : PersonSex.Male; + day = day > 40 ? day - 40 : day; + var year = (today.Year / 100 * 100) + yy; + if (year > today.Year) + { + year -= 100; + } + + return day <= DateTime.DaysInMonth(year, month) + ? new PersonalTaxCodeInfo(new DateOnly(year, month, day), sex, plain[11..15]) + : null; + } + + private static string SurnamePart(string surname) + { + var (consonants, vowels) = Split(surname); + return (consonants + vowels + "XXX")[..3]; + } + + private static string NamePart(string name) + { + var (consonants, vowels) = Split(name); + return consonants.Length >= 4 + ? string.Concat(consonants[0], consonants[2], consonants[3]) + : (consonants + vowels + "XXX")[..3]; + } + + private static (string Consonants, string Vowels) Split(string text) + { + var letters = Letters(text); + return ( + string.Concat(letters.Where(c => !"AEIOU".Contains(c, StringComparison.Ordinal))), + string.Concat(letters.Where(c => "AEIOU".Contains(c, StringComparison.Ordinal)))); + } + + // Letters A-Z only: accents dropped (È -> E), apostrophes and spaces ignored. + private static string Letters(string text) + { + var decomposed = (text ?? string.Empty).Normalize(NormalizationForm.FormD).ToUpperInvariant(); + return string.Concat(decomposed.Where(char.IsAsciiLetterUpper)); + } +} + +/// +/// E-invoice recipient codes (codice destinatario): 7 characters for businesses, 6 for public administrations (IPA +/// office code), 0000000 for consumers and businesses without a channel, XXXXXXX abroad. +/// +public static class SdiRecipientCodeValidator +{ + private const string Field = "RecipientCode"; + + /// The rules a recipient code breaks. + /// The code. + /// The kind of customer. + /// Errors and warnings. + public static IReadOnlyList Check(string? code, RecipientKind kind) + { + var value = FiscalCodeValidator.Normalize(code); + if (value.Length == 0) + { + return kind == RecipientKind.PublicAdministration ? [new(Field, "fiscal.recipient.required")] : []; + } + + if (!value.All(char.IsAsciiLetterOrDigit)) + { + return [new(Field, "fiscal.recipient.characters")]; + } + + return kind switch + { + RecipientKind.PublicAdministration when value.Length != 6 => [new(Field, "fiscal.recipient.pa-length")], + RecipientKind.Foreign when value != FatturaPaCodeLists.RecipientCodeForeign => [new(Field, "fiscal.recipient.foreign")], + RecipientKind.Consumer when value != FatturaPaCodeLists.RecipientCodeNone => [new(Field, "fiscal.recipient.consumer", FiscalProblemSeverity.Warning)], + RecipientKind.Business when value.Length != 7 => [new(Field, "fiscal.recipient.business-length")], + RecipientKind.Business when value == FatturaPaCodeLists.RecipientCodeForeign => [new(Field, "fiscal.recipient.foreign-code-domestic")], + _ => [], + }; + } +} + +/// The Italian tax identifiers as a pack feature. +public sealed class ItalianTaxIdentifierRules : ITaxIdentifierRules +{ + /// + public string NormalizeVatNumber(string? vatNumber) => ItalianVatNumberValidator.Normalize(vatNumber); + + /// + public bool IsValidVatNumber(string? vatNumber) => ItalianVatNumberValidator.IsValid(vatNumber); + + /// + public bool IsValidTaxCode(string? taxCode) => FiscalCodeValidator.IsValid(taxCode); + + /// + public string ComputePersonalTaxCode(PersonalTaxCodeData data) => FiscalCodeCalculator.Compute(data); + + /// + public PersonalTaxCodeInfo? DecodePersonalTaxCode(string? taxCode, DateOnly today) => FiscalCodeCalculator.Decode(taxCode, today); + + /// + public IReadOnlyList CheckRecipientCode(string? recipientCode, RecipientKind kind) => + SdiRecipientCodeValidator.Check(recipientCode, kind); + + /// + public string? DefaultRecipientCode(RecipientKind kind) => kind switch + { + RecipientKind.Foreign => FatturaPaCodeLists.RecipientCodeForeign, + RecipientKind.PublicAdministration => null, + _ => FatturaPaCodeLists.RecipientCodeNone, + }; +} + +/// +/// Italian banks by ABI code, to fill bank name, BIC and CAB from an Italian IBAN +/// (IT + check + CIN + ABI + CAB + account). +/// +public sealed class ItalianBankDirectory : IBankDirectory +{ + private readonly Dictionary _byAbi; + + /// Creates the directory. + /// The banks, one per ABI code. + public ItalianBankDirectory(IEnumerable banks) + { + ArgumentNullException.ThrowIfNull(banks); + _byAbi = banks.GroupBy(b => b.BankCode, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First(), StringComparer.Ordinal); + } + + /// How many banks the directory knows. + public int Count => _byAbi.Count; + + /// ABI and CAB of an Italian IBAN. + /// The IBAN. + /// The codes, or for an invalid or foreign IBAN. + public static (string Abi, string Cab)? CodesOf(string? iban) + { + var value = IbanValidator.Normalize(iban); + return IbanValidator.IsValid(value) && value.StartsWith("IT", StringComparison.Ordinal) + ? (value[5..10], value[10..15]) + : null; + } + + /// + 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/ItalianPlaces.cs b/src/Khaemhat.Fiscal.Italy/ItalianPlaces.cs new file mode 100644 index 0000000..fd059a4 --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/ItalianPlaces.cs @@ -0,0 +1,43 @@ +using Khaemhat.Fiscal.Abstractions; +using Khaemhat.Infrastructure.Files; + +namespace Khaemhat.Fiscal.Italy; + +/// +/// The Italian provinces and municipalities from the ISTAT list of municipality codes (ADR 0028): abbreviation, name and +/// region of the 110 provinces, and cadastral code, name, province, region and ISTAT code of every municipality, with +/// the postal codes of GeoNames where they match (about 98% of the municipalities). The files are rebuilt with +/// tools/Khaemhat.PlacesTool and read once, the first time they are needed. +/// +public sealed class ItalianPlaces : IPlaceDirectory +{ + /// The source of the embedded files. + public const string ListSource = + "ISTAT, Codici statistici delle unità amministrative territoriali, 26/02/2026 (CC BY 4.0); CAP: GeoNames, www.geonames.org (CC BY 4.0)"; + + private readonly Lazy> _provinces = new(ReadProvinces); + private readonly Lazy> _municipalities = new(ReadMunicipalities); + + /// + public string Source => ListSource; + + /// + public IReadOnlyList Provinces => _provinces.Value; + + /// + public IReadOnlyList Municipalities => _municipalities.Value; + + private static IReadOnlyList ReadProvinces() => + [.. Read("province.csv").Select(l => new ProvinceTemplate(l[0], l[1], l[2]))]; + + private static IReadOnlyList ReadMunicipalities() => + [.. Read("comuni.csv").Select(l => new MunicipalityTemplate(l[0], l[1], l[2], l[3], l[4], l.Count > 5 && l[5].Length > 0 ? l[5] : null))]; + + private static List> Read(string file) + { + using var stream = typeof(ItalianPlaces).Assembly.GetManifestResourceStream("Khaemhat.Fiscal.Italy.Data." + file) + ?? throw new InvalidOperationException($"The file {file} is missing from the assembly."); + using var reader = new StreamReader(stream); + return [.. CsvReader.Parse(reader.ReadToEnd(), ';').Skip(1)]; + } +} diff --git a/src/Khaemhat.Fiscal.Italy/ItalianRules.cs b/src/Khaemhat.Fiscal.Italy/ItalianRules.cs new file mode 100644 index 0000000..5d17e25 --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/ItalianRules.cs @@ -0,0 +1,145 @@ +using Khaemhat.Core.Tax; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy; + +/// The FatturaPA format: version of the specifications and code lists (writer and reader arrive in M9). +public sealed class FatturaPaFormat : IEInvoiceFormat +{ + /// + public string Name => "FatturaPA"; + + /// + public string SpecVersion => FatturaPaCodeLists.SpecVersion; + + /// + public CodeList TransmissionFormats => FatturaPaCodeLists.TransmissionFormats; + + /// + public CodeList DocumentTypes => FatturaPaCodeLists.DocumentTypes; + + /// + public CodeList PaymentMethods => FatturaPaCodeLists.PaymentMethods; + + /// + public CodeList PaymentConditions => FatturaPaCodeLists.PaymentConditions; + + /// + public CodeList TaxRegimes => FatturaPaCodeLists.TaxRegimes; +} + +/// +/// Italian withholding taxes: fees of professionals (20% on the whole fee, F24 1040), commissions of agents (23% on 50%, +/// or on 20% for agents with employees, F24 1038) and the 4% of condominiums (F24 1019). +/// +public sealed class WithholdingRulesIt : IWithholdingRules +{ + private readonly ItalianTaxEngine _engine = new(); + + /// + public IReadOnlyList Kinds { get; } = + [ + new("PROF", "Lavoro autonomo professionale", 20m, 100m, "1040", "RT01", "A"), + new("OCC", "Lavoro autonomo occasionale", 20m, 100m, "1040", "RT01", "M"), + new("AGEN", "Provvigioni ad agenti e rappresentanti", 23m, 50m, "1038", "RT01", "R"), + new("AGEND", "Provvigioni ad agenti con dipendenti o terzi", 23m, 20m, "1038", "RT01", "R"), + new("COND", "Ritenuta del condominio sugli appalti", 4m, 100m, "1019", "RT01", "W"), + ]; + + /// + public CodeList InvoiceTypes => FatturaPaCodeLists.WithholdingTypes; + + /// + public CodeList PaymentReasons => FatturaPaCodeLists.WithholdingReasons; + + /// + public CodeList SocialSecurityFunds => FatturaPaCodeLists.SocialSecurityFunds; + + /// + public decimal Compute(decimal amount, WithholdingKind kind) + { + ArgumentNullException.ThrowIfNull(kind); + return _engine.Round(amount * kind.TaxableBasePercent / 100m * kind.Rate / 100m); + } +} + +/// Italian depreciation rules (DM 31/12/1988 coefficients arrive with the asset register, M10). +public sealed class FixedAssetRulesIt : IFixedAssetRules +{ + private readonly ItalianTaxEngine _engine = new(); + + /// + public decimal FirstYearFactor => 0.5m; + + /// + public decimal LowValueThreshold => 516.46m; + + /// + public decimal PassengerCarCostLimit => 18_075.99m; + + /// + public decimal YearlyDepreciation(decimal cost, decimal ratePercent, bool firstYear, decimal alreadyDepreciated) + { + var remaining = Math.Max(0m, cost - alreadyDepreciated); + var amount = _engine.Round(cost * ratePercent / 100m * (firstYear ? FirstYearFactor : 1m)); + return Math.Min(amount, remaining); + } +} + +/// The F24 payment codes Khaemhat proposes (the file export arrives with the VAT settlement, M7). +public sealed class F24Exporter : ITaxPaymentFormExporter +{ + /// + public string FormName => "F24"; + + /// + public IReadOnlyList Codes { get; } = BuildCodes(); + + /// + public string VatCode(TaxPeriod period) + { + ArgumentNullException.ThrowIfNull(period); + return period.Periodicity == VatPeriodicity.Monthly + ? (6000 + period.Number).ToString(System.Globalization.CultureInfo.InvariantCulture) + : (6030 + period.Number).ToString(System.Globalization.CultureInfo.InvariantCulture); + } + + /// + public string VatAdvanceCode(VatPeriodicity periodicity) => periodicity == VatPeriodicity.Monthly ? "6013" : "6035"; + + /// + public string StampDutyCode(int quarter) + { + ArgumentOutOfRangeException.ThrowIfLessThan(quarter, 1); + ArgumentOutOfRangeException.ThrowIfGreaterThan(quarter, 4); + return (2520 + quarter).ToString(System.Globalization.CultureInfo.InvariantCulture); + } + + private static List BuildCodes() + { + string[] months = ["gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre"]; + var codes = new List(); + for (var m = 1; m <= 12; m++) + { + codes.Add(new((6000 + m).ToString(System.Globalization.CultureInfo.InvariantCulture), "Versamento IVA mensile " + months[m - 1])); + } + + codes.Add(new("6013", "Versamento acconto IVA mensile")); + for (var q = 1; q <= 4; q++) + { + codes.Add(new((6030 + q).ToString(System.Globalization.CultureInfo.InvariantCulture), $"Versamento IVA trimestrale {q}° trimestre")); + } + + codes.Add(new("6035", "Versamento IVA acconto trimestrali")); + codes.Add(new("6099", "Versamento IVA sulla base della dichiarazione annuale")); + codes.Add(new("1040", "Ritenute su redditi di lavoro autonomo")); + codes.Add(new("1038", "Ritenute su provvigioni")); + codes.Add(new("1019", "Ritenute del 4% operate dal condominio a titolo di acconto IRPEF")); + for (var q = 1; q <= 4; q++) + { + codes.Add(new((2520 + q).ToString(System.Globalization.CultureInfo.InvariantCulture), $"Imposta di bollo sulle fatture elettroniche, {q}° trimestre")); + } + + return codes; + } +} diff --git a/src/Khaemhat.Fiscal.Italy/ItalianTaxCodeCatalog.cs b/src/Khaemhat.Fiscal.Italy/ItalianTaxCodeCatalog.cs new file mode 100644 index 0000000..d87d0fa --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/ItalianTaxCodeCatalog.cs @@ -0,0 +1,108 @@ +using Khaemhat.Core.Tax; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy; + +/// The Italian VAT natures, the base tax codes of SPEC §14 and the rules of a tax code (mockup 076). +public sealed class ItalianTaxCodeCatalog : ITaxCodeCatalog +{ + /// The rates of Italian VAT in percent (ordinary and reduced). + public static IReadOnlySet StandardRates { get; } = new HashSet { 0m, 4m, 5m, 10m, 22m }; + + /// + public CodeList Natures => VatNatures.All; + + /// + public IReadOnlyList BaseCodes { get; } = + [ + new("22", "IVA 22%", 22m), + new("10", "IVA 10%", 10m), + new("5", "IVA 5%", 5m), + new("4", "IVA 4%", 4m), + new("22SP", "IVA 22% scissione dei pagamenti", 22m, Exigibility: TaxExigibility.SplitPayment, LegalReference: "Art. 17-ter DPR 633/72"), + new("10SP", "IVA 10% scissione dei pagamenti", 10m, Exigibility: TaxExigibility.SplitPayment, LegalReference: "Art. 17-ter DPR 633/72"), + new("22I50", "IVA 22% indetraibile al 50%", 22m, NonDeductiblePercent: 50m), + new("22I100", "IVA 22% indetraibile", 22m, NonDeductiblePercent: 100m), + new("ESC15", "Escluso art. 15", 0m, "N1", LegalReference: "Art. 15 DPR 633/72"), + new("FC7", "Non soggetto artt. 7-7 septies", 0m, "N2.1", LegalReference: "Artt. 7-7-septies DPR 633/72"), + new("NS", "Non soggetto, altri casi", 0m, "N2.2", LegalReference: "Art. 2 DPR 633/72"), + new("FORF", "Operazione in regime forfettario", 0m, "N2.2", LegalReference: "Art. 1 c. 54-89 L. 190/2014"), + new("NI8", "Non imponibile art. 8 (esportazioni)", 0m, "N3.1", LegalReference: "Art. 8 c. 1 lett. a) DPR 633/72"), + new("NI41", "Non imponibile art. 41 (cessioni intracomunitarie)", 0m, "N3.2", LegalReference: "Art. 41 DL 331/93"), + new("NI71", "Non imponibile art. 71 (San Marino)", 0m, "N3.3", LegalReference: "Art. 71 DPR 633/72"), + new("NI8C", "Non imponibile art. 8 c. 1 lett. c) (dichiarazione d'intento)", 0m, "N3.5", LegalReference: "Art. 8 c. 1 lett. c) DPR 633/72"), + new("ESE10", "Esente art. 10", 0m, "N4", LegalReference: "Art. 10 DPR 633/72"), + new("RC74", "Inversione contabile, rottami", 0m, "N6.1", LegalReference: "Art. 74 c. 7 e 8 DPR 633/72"), + new("RC17O", "Inversione contabile, oro e argento", 0m, "N6.2", LegalReference: "Art. 17 c. 5 DPR 633/72"), + new("RC17A", "Inversione contabile, subappalto edile", 0m, "N6.3", LegalReference: "Art. 17 c. 6 lett. a) DPR 633/72"), + new("RC17F", "Inversione contabile, cessione di fabbricati", 0m, "N6.4", LegalReference: "Art. 17 c. 6 lett. a-bis) DPR 633/72"), + new("RC17B", "Inversione contabile, telefoni cellulari", 0m, "N6.5", LegalReference: "Art. 17 c. 6 lett. b) DPR 633/72"), + new("RC17C", "Inversione contabile, prodotti elettronici", 0m, "N6.6", LegalReference: "Art. 17 c. 6 lett. c) DPR 633/72"), + new("RC17E", "Inversione contabile, comparto edile e settori connessi", 0m, "N6.7", LegalReference: "Art. 17 c. 6 lett. a-ter) DPR 633/72"), + new("RC17N", "Inversione contabile, settore energetico", 0m, "N6.8", LegalReference: "Art. 17 c. 6 lett. d-bis), d-ter), d-quater) DPR 633/72"), + new("RC17", "Inversione contabile, altri casi", 0m, "N6.9", LegalReference: "Art. 17 DPR 633/72"), + ]; + + /// + public TaxCodeKind KindOf(decimal rate, string? nature) => + string.IsNullOrWhiteSpace(nature) ? TaxCodeKind.Taxable : VatNatures.KindOf(nature); + + /// + public IReadOnlyList Validate(TaxCodeDefinition code) + { + ArgumentNullException.ThrowIfNull(code); + var problems = new List(); + var nature = string.IsNullOrWhiteSpace(code.Nature) ? null : code.Nature.Trim(); + + if (code.Rate is < 0m or > 100m) + { + problems.Add(new(nameof(code.Rate), "fiscal.tax.rate-range")); + } + else if (!StandardRates.Contains(code.Rate)) + { + // Compensation rates of the agricultural regime are legal but rare: a warning, not an error. + problems.Add(new(nameof(code.Rate), "fiscal.tax.rate-unusual", FiscalProblemSeverity.Warning)); + } + + if (nature is null) + { + if (code.Rate == 0m) + { + problems.Add(new(nameof(code.Nature), "fiscal.tax.nature-required")); + } + } + else if (Natures.Find(nature) is not { } entry) + { + problems.Add(new(nameof(code.Nature), "fiscal.tax.nature-unknown")); + } + else if (entry.Obsolete) + { + problems.Add(new(nameof(code.Nature), "fiscal.tax.nature-obsolete")); + } + else if (code.Rate != 0m) + { + problems.Add(new(nameof(code.Nature), "fiscal.tax.nature-with-rate")); + } + else if (string.IsNullOrWhiteSpace(code.LegalReference)) + { + problems.Add(new(nameof(code.LegalReference), "fiscal.tax.legal-reference-missing", FiscalProblemSeverity.Warning)); + } + + if (code.Exigibility == TaxExigibility.SplitPayment && code.Rate == 0m) + { + problems.Add(new(nameof(code.Exigibility), "fiscal.tax.split-needs-rate")); + } + + if (code.Exigibility != TaxExigibility.Immediate && VatNatures.IsReverseCharge(nature)) + { + problems.Add(new(nameof(code.Exigibility), "fiscal.tax.reverse-charge-immediate")); + } + + if (code.NonDeductiblePercent is < 0m or > 100m) + { + problems.Add(new(nameof(code.NonDeductiblePercent), "fiscal.tax.non-deductible-range")); + } + + return problems; + } +} diff --git a/src/Khaemhat.Fiscal.Italy/ItalianTaxEngine.cs b/src/Khaemhat.Fiscal.Italy/ItalianTaxEngine.cs new file mode 100644 index 0000000..4eed665 --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/ItalianTaxEngine.cs @@ -0,0 +1,56 @@ +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy; + +/// +/// Italian VAT arithmetic: amounts to the cent, halves away from zero; the tax of the summary is computed on the total +/// taxable of each line, as the FatturaPA DatiRiepilogo requires (tolerance of one cent on rows). +/// +public sealed class ItalianTaxEngine : ITaxEngine +{ + /// The stamp duty on invoices without VAT (art. 13 of the tariff of DPR 642/72). + public const decimal StampDutyAmount = 2.00m; + + /// The amount without VAT above which the stamp duty is due. + public const decimal StampDutyThreshold = 77.47m; + + /// + public decimal Round(decimal amount) => Math.Round(amount, 2, MidpointRounding.AwayFromZero); + + /// + public decimal ComputeTax(decimal taxable, decimal rate) => Round(taxable * rate / 100m); + + /// + public IReadOnlyList Summarize(IEnumerable amounts) + { + ArgumentNullException.ThrowIfNull(amounts); + return + [ + .. amounts + .GroupBy(a => (a.Rate, Nature: Normalize(a.Nature), a.Exigibility, a.NonDeductiblePercent)) + .Select(g => + { + var taxable = Round(g.Sum(a => a.Amount)); + var tax = ComputeTax(taxable, g.Key.Rate); + return new TaxSummaryLine(g.Key.Rate, g.Key.Nature, g.Key.Exigibility, g.Key.NonDeductiblePercent, + taxable, tax, Round(tax * g.Key.NonDeductiblePercent / 100m)); + }) + .OrderByDescending(l => l.Rate) + .ThenBy(l => l.Nature, StringComparer.Ordinal) + .ThenBy(l => l.Exigibility) + .ThenBy(l => l.NonDeductiblePercent), + ]; + } + + /// + public StampDutyAssessment AssessStampDuty(IEnumerable summary) + { + ArgumentNullException.ThrowIfNull(summary); + var exempt = Round(summary.Where(l => l.Rate == 0m && VatNatures.CountsForStampDuty(l.Nature)).Sum(l => l.Taxable)); + var required = exempt > StampDutyThreshold; + return new StampDutyAssessment(required, required ? StampDutyAmount : 0m, exempt, StampDutyThreshold); + } + + private static string? Normalize(string? nature) => + string.IsNullOrWhiteSpace(nature) ? null : nature.Trim().ToUpperInvariant(); +} diff --git a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs new file mode 100644 index 0000000..ab9137c --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs @@ -0,0 +1,46 @@ +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy; + +/// +/// The Italian fiscal pack (SPEC §1.10, ADR 0007, ADR 0025): chosen for companies whose company_profile.country +/// is IT. Registered only by the composition root of Khaemhat.Web. +/// +public sealed class ItalyFiscalPack : FiscalPackBase +{ + /// The version of the Italian base data and code lists. + public const string Version = "IT 2026.3"; + + /// Creates the pack with every feature this version delivers. + public ItalyFiscalPack() + { + AddFeature(new FatturaPaFormat()); + AddFeature(new WithholdingRulesIt()); + AddFeature(new FixedAssetRulesIt()); + AddFeature(new F24Exporter()); + AddFeature(new ItalianTaxIdentifierRules()); + AddFeature(new ItalianBaseTables()); + AddFeature(new ItalianPlaces()); + + // ABI and CAB are read from every Italian IBAN; bank names and BICs arrive with the ABI list (ADR 0026). + AddFeature(new ItalianBankDirectory([])); + } + + /// + public override string CountryCode => "IT"; + + /// + public override string Name => "Italia"; + + /// + public override string DataVersion => Version; + + /// + public override ITaxCodeCatalog TaxCodes { get; } = new ItalianTaxCodeCatalog(); + + /// + public override ITaxEngine TaxEngine { get; } = new ItalianTaxEngine(); + + /// + public override IFiscalCalendar Calendar { get; } = new ItalianFiscalCalendar(); +} diff --git a/src/Khaemhat.Fiscal.Italy/Khaemhat.Fiscal.Italy.csproj b/src/Khaemhat.Fiscal.Italy/Khaemhat.Fiscal.Italy.csproj index 7933469..a03d77e 100644 --- a/src/Khaemhat.Fiscal.Italy/Khaemhat.Fiscal.Italy.csproj +++ b/src/Khaemhat.Fiscal.Italy/Khaemhat.Fiscal.Italy.csproj @@ -4,6 +4,11 @@ Khaemhat.Fiscal.Italy + + + + + diff --git a/src/Khaemhat.Fiscal.Italy/VatNatures.cs b/src/Khaemhat.Fiscal.Italy/VatNatures.cs new file mode 100644 index 0000000..d1b8060 --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/VatNatures.cs @@ -0,0 +1,79 @@ +using Khaemhat.Core.Tax; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy; + +/// +/// The VAT natures of the FatturaPA specifications (Natura, N1-N7). Since 2021 the generic codes N2, N3 and N6 +/// are no longer accepted: only their sub-codes. +/// +public static class VatNatures +{ + /// Every nature, obsolete ones included. + public static CodeList All { get; } = new("VatNatures", + [ + new("N1", "Escluse ex art. 15 DPR 633/72"), + new("N2", "Non soggette", Obsolete: true), + new("N2.1", "Non soggette ad IVA ai sensi degli artt. da 7 a 7-septies DPR 633/72"), + new("N2.2", "Non soggette - altri casi"), + new("N3", "Non imponibili", Obsolete: true), + new("N3.1", "Non imponibili - esportazioni"), + new("N3.2", "Non imponibili - cessioni intracomunitarie"), + new("N3.3", "Non imponibili - cessioni verso San Marino"), + new("N3.4", "Non imponibili - operazioni assimilate alle cessioni all'esportazione"), + new("N3.5", "Non imponibili - a seguito di dichiarazioni d'intento"), + new("N3.6", "Non imponibili - altre operazioni che non concorrono alla formazione del plafond"), + new("N4", "Esenti"), + new("N5", "Regime del margine / IVA non esposta in fattura"), + new("N6", "Inversione contabile", Obsolete: true), + new("N6.1", "Inversione contabile - cessione di rottami e altri materiali di recupero"), + new("N6.2", "Inversione contabile - cessione di oro e argento ai sensi della L. 7/2000 nonché di oreficeria usata ad OPO"), + new("N6.3", "Inversione contabile - subappalto nel settore edile"), + new("N6.4", "Inversione contabile - cessione di fabbricati"), + new("N6.5", "Inversione contabile - cessione di telefoni cellulari"), + new("N6.6", "Inversione contabile - cessione di prodotti elettronici"), + new("N6.7", "Inversione contabile - prestazioni comparto edile e settori connessi"), + new("N6.8", "Inversione contabile - operazioni settore energetico"), + new("N6.9", "Inversione contabile - altri casi"), + new("N7", "IVA assolta in altro stato UE (art. 7-octies e art. 74-sexies DPR 633/72)"), + ]); + + // Natures whose amounts count toward the stamp duty threshold: exports (N3.1), intra-EU supplies (N3.2), San Marino + // (N3.3), operations assimilated to exports (N3.4), reverse charge (N6.x) and VAT paid in another EU state (N7) are + // exempt from stamp duty (art. 15 of the table attached to DPR 642/72 and the Agenzia's guidance). + private static readonly HashSet StampDutyNatures = new(StringComparer.OrdinalIgnoreCase) + { + "N1", "N2.1", "N2.2", "N3.5", "N3.6", "N4", "N5", + }; + + /// The kind of operation a nature describes; no nature means a taxable operation. + /// The nature code. + /// The kind. + public static TaxCodeKind KindOf(string? nature) + { + var code = nature?.Trim().ToUpperInvariant() ?? string.Empty; + return code switch + { + "" => TaxCodeKind.Taxable, + "N1" => TaxCodeKind.Excluded, + "N4" => TaxCodeKind.Exempt, + "N5" => TaxCodeKind.Margin, + "N7" => TaxCodeKind.OtherEuVat, + _ when code.StartsWith("N2", StringComparison.Ordinal) => TaxCodeKind.NotSubject, + _ when code.StartsWith("N3", StringComparison.Ordinal) => TaxCodeKind.NonTaxable, + _ when code.StartsWith("N6", StringComparison.Ordinal) => TaxCodeKind.ReverseCharge, + _ => throw new ArgumentException($"Unknown VAT nature '{nature}'.", nameof(nature)), + }; + } + + /// Whether an amount with this nature counts toward the stamp duty threshold. + /// The nature code. + /// when the stamp duty rule counts it. + public static bool CountsForStampDuty(string? nature) => nature is not null && StampDutyNatures.Contains(nature.Trim()); + + /// Whether the nature is a reverse charge one (N6.x). + /// The nature code. + /// for reverse charge. + public static bool IsReverseCharge(string? nature) => + nature is not null && nature.Trim().StartsWith("N6", StringComparison.OrdinalIgnoreCase); +} diff --git a/src/Khaemhat.Infrastructure/Files/CsvReader.cs b/src/Khaemhat.Infrastructure/Files/CsvReader.cs new file mode 100644 index 0000000..4a6306c --- /dev/null +++ b/src/Khaemhat.Infrastructure/Files/CsvReader.cs @@ -0,0 +1,124 @@ +using System.Text; + +namespace Khaemhat.Infrastructure.Files; + +/// +/// Reads CSV files written by or by spreadsheets (RFC 4180): quoted fields with doubled quotes, +/// line breaks inside quotes, an optional UTF-8 byte order mark. The separator is guessed from the first line +/// (;, , or tab) unless given. +/// +public static class CsvReader +{ + /// The separators tried, in order of preference. + private static readonly char[] Separators = [';', ',', '\t']; + + /// Reads every row of a text. + /// The content. + /// The separator, or to guess it. + /// The rows; empty lines are skipped. + public static IReadOnlyList> Parse(string text, char? separator = null) + { + ArgumentNullException.ThrowIfNull(text); + if (text.Length > 0 && text[0] == '') + { + text = text[1..]; + } + + var sep = separator ?? Guess(text); + var rows = new List>(); + var row = new List(); + var field = new StringBuilder(); + var quoted = false; + var fieldStarted = false; + + for (var i = 0; i < text.Length; i++) + { + var c = text[i]; + if (quoted) + { + if (c == '"') + { + if (i + 1 < text.Length && text[i + 1] == '"') + { + field.Append('"'); + i++; + } + else + { + quoted = false; + } + } + else + { + field.Append(c); + } + + continue; + } + + if (c == '"' && field.Length == 0) + { + quoted = true; + fieldStarted = true; + } + else if (c == sep) + { + row.Add(field.ToString()); + field.Clear(); + fieldStarted = true; + } + else if (c is '\r' or '\n') + { + if (c == '\r' && i + 1 < text.Length && text[i + 1] == '\n') + { + i++; + } + + EndRow(); + } + else + { + field.Append(c); + fieldStarted = true; + } + } + + EndRow(); + return rows; + + void EndRow() + { + if (fieldStarted || field.Length > 0 || row.Count > 0) + { + row.Add(field.ToString()); + if (row.Count > 1 || row[0].Length > 0) + { + rows.Add(row); + } + } + + row = []; + field.Clear(); + fieldStarted = false; + } + } + + /// Reads a stream as UTF-8 (the byte order mark is optional). + /// The stream. + /// The separator, or to guess it. + /// Cancellation. + /// The rows. + public static async Task>> ReadAsync(Stream content, char? separator = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(content); + using var reader = new StreamReader(content, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, leaveOpen: true); + return Parse(await reader.ReadToEndAsync(cancellationToken).ConfigureAwait(false), separator); + } + + private static char Guess(string text) + { + var end = text.IndexOfAny(['\r', '\n']); + var first = end < 0 ? text : text[..end]; + return Separators.OrderByDescending(s => first.Count(c => c == s)).First(); + } +} diff --git a/src/Khaemhat.Infrastructure/Files/XlsxReader.cs b/src/Khaemhat.Infrastructure/Files/XlsxReader.cs new file mode 100644 index 0000000..cb15e4f --- /dev/null +++ b/src/Khaemhat.Infrastructure/Files/XlsxReader.cs @@ -0,0 +1,414 @@ +using System.Globalization; +using System.IO.Compression; +using System.Xml; + +namespace Khaemhat.Infrastructure.Files; + +/// A spreadsheet that cannot be read: not an Office Open XML workbook, damaged, or too large. +public sealed class XlsxReadException : Exception +{ + /// Creates the exception. + public XlsxReadException() + { + } + + /// Creates the exception. + /// What went wrong. + public XlsxReadException(string message) + : base(message) + { + } + + /// Creates the exception. + /// What went wrong. + /// The cause. + public XlsxReadException(string message, Exception innerException) + : base(message, innerException) + { + } +} + +/// +/// Reads the first sheet of an Office Open XML workbook (.xlsx, SPEC §12.12) with and +/// : shared, inline and formula strings, numbers as written in the file (invariant culture), +/// booleans as true/false, and numbers with a date format as ISO dates (yyyy-MM-dd). Empty cells in +/// the middle of a row are kept by their column letter; empty rows are skipped. Formulas are not computed: the cached +/// value saved by the spreadsheet is read. +/// +public static class XlsxReader +{ + /// The largest uncompressed part read, against archives that expand to fill the memory. + public const long MaxPartBytes = 256L * 1024 * 1024; + + private const string RelationshipNamespace = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; + + // The built-in number formats that show a date (ECMA-376 §18.8.30). + private static readonly HashSet DateFormats = [14, 15, 16, 17, 18, 19, 20, 21, 22, 27, 30, 36, 45, 46, 47, 50, 57]; + + private static readonly DateTime Epoch = new(1899, 12, 30, 0, 0, 0, DateTimeKind.Unspecified); + + /// Reads the rows of the first sheet. + /// The workbook; it is copied to memory when not seekable. + /// Cancellation. + /// The rows, each with its cells from column A. + /// The file is not a readable workbook. + public static async Task>> ReadAsync(Stream content, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(content); + var source = content; + MemoryStream? copy = null; + if (!content.CanSeek) + { + copy = new MemoryStream(); + await content.CopyToAsync(copy, cancellationToken).ConfigureAwait(false); + copy.Position = 0; + source = copy; + } + + try + { + using var zip = new ZipArchive(source, ZipArchiveMode.Read, leaveOpen: true); + var sheetPath = FirstSheetPath(zip); + var strings = SharedStrings(zip); + var dateStyles = DateStyles(zip); + var sheet = zip.GetEntry(sheetPath) ?? throw new XlsxReadException("The first sheet is missing: " + sheetPath); + return ReadSheet(sheet, strings, dateStyles, cancellationToken); + } + catch (InvalidDataException ex) + { + throw new XlsxReadException("Not a workbook.", ex); + } + catch (XmlException ex) + { + throw new XlsxReadException("A part of the workbook is not valid XML.", ex); + } + finally + { + if (copy is not null) + { + await copy.DisposeAsync().ConfigureAwait(false); + } + } + } + + /// The zero-based column of a cell reference such as AB12. + /// The reference. + /// The column, or -1 when the reference has no letters. + public static int ColumnOf(string? reference) + { + if (string.IsNullOrEmpty(reference)) + { + return -1; + } + + var column = 0; + var letters = 0; + foreach (var c in reference) + { + if (!char.IsAsciiLetter(c)) + { + break; + } + + column = (column * 26) + (char.ToUpperInvariant(c) - 'A' + 1); + letters++; + } + + return letters == 0 ? -1 : column - 1; + } + + private static XmlReader Open(ZipArchiveEntry entry) + { + if (entry.Length > MaxPartBytes) + { + throw new XlsxReadException("A part of the workbook is too large: " + entry.FullName); + } + + return XmlReader.Create(entry.Open(), new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null, IgnoreWhitespace = false }); + } + + private static string FirstSheetPath(ZipArchive zip) + { + var workbook = zip.GetEntry("xl/workbook.xml") ?? throw new XlsxReadException("xl/workbook.xml is missing."); + string? relationship = null; + using (var reader = Open(workbook)) + { + while (reader.Read()) + { + if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "sheet") + { + relationship = reader.GetAttribute("id", RelationshipNamespace); + break; + } + } + } + + if (relationship is null) + { + throw new XlsxReadException("The workbook has no sheet."); + } + + var rels = zip.GetEntry("xl/_rels/workbook.xml.rels"); + if (rels is not null) + { + using var reader = Open(rels); + while (reader.Read()) + { + if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "Relationship" && reader.GetAttribute("Id") == relationship + && reader.GetAttribute("Target") is { } target) + { + target = target.Replace('\\', '/'); + return target.StartsWith('/') ? target.TrimStart('/') : "xl/" + target; + } + } + } + + return "xl/worksheets/sheet1.xml"; + } + + private static List SharedStrings(ZipArchive zip) + { + var strings = new List(); + var entry = zip.GetEntry("xl/sharedStrings.xml"); + if (entry is null) + { + return strings; + } + + using var reader = Open(entry); + while (reader.Read()) + { + if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "si") + { + strings.Add(ReadText(reader)); + } + } + + return strings; + } + + // The concatenated of an or element, without the phonetic runs; the reader ends on its end tag. + private static string ReadText(XmlReader reader) + { + if (reader.IsEmptyElement) + { + return string.Empty; + } + + var depth = reader.Depth; + var text = new System.Text.StringBuilder(); + var skip = -1; + while (reader.Read() && !(reader.NodeType == XmlNodeType.EndElement && reader.Depth == depth)) + { + if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "rPh" && !reader.IsEmptyElement) + { + skip = reader.Depth; + } + else if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == skip) + { + skip = -1; + } + else if (skip < 0 && reader.NodeType == XmlNodeType.Element && reader.LocalName == "t" && !reader.IsEmptyElement) + { + text.Append(reader.ReadElementContentAsString()); + if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == depth) + { + break; + } + } + } + + return text.ToString(); + } + + // The indexes of the cell styles (cellXfs) whose number format shows a date. + private static HashSet DateStyles(ZipArchive zip) + { + var styles = new HashSet(); + var entry = zip.GetEntry("xl/styles.xml"); + if (entry is null) + { + return styles; + } + + var custom = new HashSet(); + using var reader = Open(entry); + var inCellXfs = false; + var index = 0; + while (reader.Read()) + { + if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "numFmt" + && int.TryParse(reader.GetAttribute("numFmtId"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var id) + && IsDateFormat(reader.GetAttribute("formatCode"))) + { + custom.Add(id); + } + else if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "cellXfs") + { + inCellXfs = !reader.IsEmptyElement; + } + else if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "cellXfs") + { + inCellXfs = false; + } + else if (inCellXfs && reader.NodeType == XmlNodeType.Element && reader.LocalName == "xf") + { + if (int.TryParse(reader.GetAttribute("numFmtId"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var format) + && (DateFormats.Contains(format) || custom.Contains(format))) + { + styles.Add(index); + } + + index++; + } + } + + return styles; + } + + // A custom format shows a date when, outside quoted text and brackets, it has a day, month or year code. + private static bool IsDateFormat(string? code) + { + if (string.IsNullOrEmpty(code)) + { + return false; + } + + var quoted = false; + var bracket = false; + foreach (var c in code) + { + switch (c) + { + case '"': + quoted = !quoted; + break; + case '[' when !quoted: + bracket = true; + break; + case ']' when !quoted: + bracket = false; + break; + case 'd' or 'D' or 'y' or 'Y' or 'm' or 'M' when !quoted && !bracket: + return true; + } + } + + return false; + } + + private static List> ReadSheet(ZipArchiveEntry sheet, List strings, HashSet dateStyles, CancellationToken cancellationToken) + { + var rows = new List>(); + using var reader = Open(sheet); + List? row = null; + while (reader.Read()) + { + if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "row") + { + cancellationToken.ThrowIfCancellationRequested(); + row = []; + if (reader.IsEmptyElement) + { + row = null; + } + } + else if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "row" && row is not null) + { + while (row.Count > 0 && row[^1].Length == 0) + { + row.RemoveAt(row.Count - 1); + } + + if (row.Count > 0) + { + rows.Add(row); + } + + row = null; + } + else if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "c" && row is not null) + { + var column = ColumnOf(reader.GetAttribute("r")); + var type = reader.GetAttribute("t"); + var style = int.TryParse(reader.GetAttribute("s"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var s) ? s : -1; + var value = reader.IsEmptyElement ? string.Empty : ReadCell(reader, type, strings, dateStyles.Contains(style)); + if (column < 0) + { + column = row.Count; + } + + while (row.Count < column) + { + row.Add(string.Empty); + } + + if (row.Count == column) + { + row.Add(value); + } + else + { + row[column] = value; + } + } + } + + return rows; + } + + // The value of a element; the reader ends on its end tag. + private static string ReadCell(XmlReader reader, string? type, List strings, bool date) + { + var depth = reader.Depth; + string? raw = null; + string? inline = null; + while (reader.Read() && !(reader.NodeType == XmlNodeType.EndElement && reader.Depth == depth)) + { + if (reader.NodeType != XmlNodeType.Element) + { + continue; + } + + if (reader.LocalName == "v" && !reader.IsEmptyElement) + { + raw = reader.ReadElementContentAsString(); + if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == depth) + { + break; + } + } + else if (reader.LocalName == "is") + { + inline = ReadText(reader); + } + } + + return type switch + { + "inlineStr" => inline ?? string.Empty, + "s" => int.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out var index) && index >= 0 && index < strings.Count ? strings[index] : string.Empty, + "b" => raw == "1" ? "true" : "false", + "str" or "e" => raw ?? string.Empty, + _ => Number(raw, date), + }; + } + + private static string Number(string? raw, bool date) + { + if (string.IsNullOrEmpty(raw)) + { + return string.Empty; + } + + if (date && double.TryParse(raw, NumberStyles.Float, CultureInfo.InvariantCulture, out var serial) && serial is > 0 and < 2958466) + { + var day = Epoch.AddDays(Math.Floor(serial)); + return day.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); + } + + return decimal.TryParse(raw, NumberStyles.Float, CultureInfo.InvariantCulture, out var number) + ? number.ToString(CultureInfo.InvariantCulture) + : raw; + } +} diff --git a/src/Khaemhat.Infrastructure/Http/EcbRatesClient.cs b/src/Khaemhat.Infrastructure/Http/EcbRatesClient.cs new file mode 100644 index 0000000..c0a1613 --- /dev/null +++ b/src/Khaemhat.Infrastructure/Http/EcbRatesClient.cs @@ -0,0 +1,99 @@ +using System.Globalization; +using System.Xml; +using System.Xml.Linq; + +namespace Khaemhat.Infrastructure.Http; + +/// A reference rate of the European Central Bank: units of the currency for one euro. +/// The currency (ISO 4217). +/// The day of the rate. +/// Units of the currency for one euro. +public sealed record EcbRate(string Currency, DateOnly Date, decimal Rate); + +/// +/// The euro foreign exchange reference rates of the European Central Bank (SPEC §11.1, §11.12), published on working +/// days around 16:00 CET as an XML file (eurofxref-daily.xml, or the last 90 days in eurofxref-hist-90d.xml). +/// +public sealed class EcbRatesClient +{ + /// The address of the reference rates. + public static readonly Uri DefaultBaseAddress = new("https://www.ecb.europa.eu/stats/eurofxref/"); + + private const string Namespace = "http://www.ecb.int/vocabulary/2002-08-01/eurofxref"; + + private readonly HttpClient _http; + + /// Creates the client. + /// The HTTP client (its base address defaults to ). + public EcbRatesClient(HttpClient http) + { + ArgumentNullException.ThrowIfNull(http); + _http = http; + _http.BaseAddress ??= DefaultBaseAddress; + } + + /// Reads the rates of the last working day, or of the last 90 days. + /// Whether to read the last 90 days (to fill gaps after a stop). + /// Cancellation. + /// The rates. + /// The service did not answer. + /// The answer is not the expected XML. + public async Task> GetAsync(bool last90Days = false, CancellationToken cancellationToken = default) + { + var path = new Uri(last90Days ? "eurofxref-hist-90d.xml" : "eurofxref-daily.xml", UriKind.Relative); + using var response = await _http.GetAsync(path, cancellationToken).ConfigureAwait(false); + response.EnsureSuccessStatusCode(); + var content = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + await using (content.ConfigureAwait(false)) + { + return await ParseAsync(content, cancellationToken).ConfigureAwait(false); + } + } + + /// Reads the ECB XML. + /// The XML. + /// Cancellation. + /// The rates. + /// The XML is not the ECB format. + public static async Task> ParseAsync(Stream xml, CancellationToken cancellationToken = default) + { + XDocument document; + try + { + var settings = new XmlReaderSettings { Async = true, DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null }; + using var reader = XmlReader.Create(xml, settings); + document = await XDocument.LoadAsync(reader, LoadOptions.None, cancellationToken).ConfigureAwait(false); + } + catch (XmlException ex) + { + throw new FormatException("The ECB answer is not XML.", ex); + } + + XNamespace ns = Namespace; + var rates = new List(); + foreach (var day in document.Descendants(ns + "Cube").Where(c => c.Attribute("time") is not null)) + { + if (!DateOnly.TryParseExact(day.Attribute("time")!.Value, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date)) + { + throw new FormatException("The ECB answer has a date that cannot be read."); + } + + foreach (var cube in day.Elements(ns + "Cube")) + { + var currency = cube.Attribute("currency")?.Value; + var text = cube.Attribute("rate")?.Value; + if (currency is { Length: 3 } && decimal.TryParse(text, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var rate) && rate > 0) + { + rates.Add(new EcbRate(currency, date, rate)); + } + } + } + + if (rates.Count == 0) + { + throw new FormatException("The ECB answer has no rates."); + } + + return rates; + } +} diff --git a/src/Khaemhat.Infrastructure/Http/ViesClient.cs b/src/Khaemhat.Infrastructure/Http/ViesClient.cs new file mode 100644 index 0000000..2ff4066 --- /dev/null +++ b/src/Khaemhat.Infrastructure/Http/ViesClient.cs @@ -0,0 +1,168 @@ +using System.Globalization; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Khaemhat.Infrastructure.Http; + +/// The outcome of a VIES check. +public enum ViesStatus +{ + /// The number is registered for intra-EU operations. + Valid = 0, + + /// The number is not registered (or not active for intra-EU operations). + Invalid = 1, + + /// The service or the member state could not answer; try again later. + Unavailable = 2, + + /// The request was refused as malformed (unknown country, wrong characters). + InvalidInput = 3, +} + +/// The answer of VIES, as saved on the party (SPEC §11.2). +/// The outcome. +/// The member state code asked (Greece is EL). +/// The number asked, without prefix. +/// When VIES answered (or when the call failed), UTC. +/// The registered name, when the member state shares it. +/// The registered address, when shared. +/// The VIES error code for and . +public sealed record ViesResult( + ViesStatus Status, + string CountryCode, + string VatNumber, + DateTimeOffset CheckedAt, + string? Name, + string? Address, + string? Error); + +/// +/// Checks EU VAT numbers with the VIES REST service of the European Commission +/// (GET /taxation_customs/vies/rest-api/ms/{country}/vat/{number}). Network errors and timeouts become +/// : a check that could not be made is never reported as invalid. +/// +public sealed class ViesClient +{ + /// The public service address. + public static readonly Uri DefaultBaseAddress = new("https://ec.europa.eu/taxation_customs/vies/rest-api/"); + + private static readonly HashSet MemberStates = new(StringComparer.Ordinal) + { + "AT", "BE", "BG", "CY", "CZ", "DE", "DK", "EE", "EL", "ES", "FI", "FR", "HR", "HU", "IE", "IT", "LT", "LU", + "LV", "MT", "NL", "PL", "PT", "RO", "SE", "SI", "SK", "XI", + }; + + private readonly HttpClient _http; + private readonly TimeProvider _time; + + /// Creates the client. + /// The HTTP client; its base address defaults to . + /// The clock. + public ViesClient(HttpClient http, TimeProvider time) + { + ArgumentNullException.ThrowIfNull(http); + ArgumentNullException.ThrowIfNull(time); + _http = http; + _http.BaseAddress ??= DefaultBaseAddress; + _time = time; + } + + /// The VIES member state code for an ISO country code (Greece: GR becomes EL). + /// ISO 3166-1 alpha-2 code. + /// The VIES code, or outside the EU. + public static string? MemberStateCode(string? isoCountryCode) + { + var code = isoCountryCode?.Trim().ToUpperInvariant(); + code = code == "GR" ? "EL" : code; + return code is not null && MemberStates.Contains(code) ? code : null; + } + + /// Checks a VAT number. + /// ISO or VIES country code. + /// The number, with or without the country prefix. + /// Cancels the call. + /// The outcome. + public async Task CheckAsync(string countryCode, string vatNumber, CancellationToken cancellationToken) + { + var state = MemberStateCode(countryCode); + var number = string.Concat((vatNumber ?? string.Empty).Where(char.IsAsciiLetterOrDigit)).ToUpperInvariant(); + if (state is not null && number.StartsWith(state, StringComparison.Ordinal)) + { + number = number[state.Length..]; + } + + if (state is null || number.Length == 0) + { + return new ViesResult(ViesStatus.InvalidInput, countryCode ?? string.Empty, number, _time.GetUtcNow(), null, null, "INVALID_INPUT"); + } + + try + { + using var response = await _http.GetAsync(new Uri($"ms/{state}/vat/{Uri.EscapeDataString(number)}", UriKind.Relative), cancellationToken).ConfigureAwait(false); + if (!response.IsSuccessStatusCode) + { + var status = (int)response.StatusCode; + return Failed(state, number, status is >= 400 and < 500 && status != 429 ? ViesStatus.InvalidInput : ViesStatus.Unavailable, + "HTTP_" + status.ToString(CultureInfo.InvariantCulture)); + } + + var answer = await response.Content.ReadFromJsonAsync(cancellationToken).ConfigureAwait(false); + if (answer is null) + { + return Failed(state, number, ViesStatus.Unavailable, "EMPTY_RESPONSE"); + } + + var error = answer.UserError; + if (answer.IsValid) + { + return new ViesResult(ViesStatus.Valid, state, number, answer.RequestDate ?? _time.GetUtcNow(), Clean(answer.Name), Clean(answer.Address), null); + } + + return error is null or "VALID" or "INVALID" + ? new ViesResult(ViesStatus.Invalid, state, number, answer.RequestDate ?? _time.GetUtcNow(), null, null, null) + : Failed(state, number, error == "INVALID_INPUT" ? ViesStatus.InvalidInput : ViesStatus.Unavailable, error); + } + catch (HttpRequestException ex) + { + return Failed(state, number, ViesStatus.Unavailable, ex.HttpRequestError.ToString()); + } + catch (TaskCanceledException) when (!cancellationToken.IsCancellationRequested) + { + return Failed(state, number, ViesStatus.Unavailable, "TIMEOUT"); + } + catch (JsonException) + { + return Failed(state, number, ViesStatus.Unavailable, "BAD_RESPONSE"); + } + } + + private ViesResult Failed(string state, string number, ViesStatus status, string error) => + new(status, state, number, _time.GetUtcNow(), null, null, error); + + // Member states that do not share the data answer with "---". + private static string? Clean(string? value) + { + var text = value?.Trim(); + return string.IsNullOrEmpty(text) || text == "---" ? null : text; + } + + private sealed class ViesAnswer + { + [JsonPropertyName("isValid")] + public bool IsValid { get; set; } + + [JsonPropertyName("requestDate")] + public DateTimeOffset? RequestDate { get; set; } + + [JsonPropertyName("userError")] + public string? UserError { get; set; } + + [JsonPropertyName("name")] + public string? Name { get; set; } + + [JsonPropertyName("address")] + public string? Address { get; set; } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor b/src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor new file mode 100644 index 0000000..f4cde79 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor @@ -0,0 +1,233 @@ +@page "/amministrazione/import-export" +@attribute [Authorize] +@using Khaemhat.Application.ImportExport +@inject ShellSession Session +@inject ImportService Imports +@inject ToastService Toasts +@inject DialogService Dialogs +@inject IJSRuntime JS + +@* The guided import and export (SPEC §11.7, §12.12, mockup 077, ADR 0031): entity and file, mapping of the columns, + check of every row as if typed in its record, import of the rows without errors; on the side, the export with the + same columns and the empty templates. *@ + + +@if (Session.Company is null) +{ +

@T["ImportExport.NoCompany"]

+} +else if (Targets.Count == 0) +{ +
+ +

@T["Pages.AccessDenied.Title"]

+

@T["ImportExport.NoTargets"]

+
+} +else +{ +
+
+ + +
+ + @if (IsRecordTarget) + { + + + } + else if (IsPrices) + { + + } + @if (IsParties) + { + + + } +
+ + + @T["ImportExport.FileHint"] +
+
+
+ + +

@T["ImportExport.Export.Lead"]

+
+ @foreach (var format in Formats) + { + + } +
+
+ + +
+
+
+ +
+ @if (_file is null) + { + +

@T["ImportExport.Formats.Lead"]

+
    +
  • @T["ImportExport.Formats.Csv"]
  • +
  • @T["ImportExport.Formats.Xlsx"]
  • +
  • @T["ImportExport.Formats.Json"]
  • +
+ @if (!Target.CanApply) + { +
@T.Format("ImportExport.Formats.CheckOnly", CheckOnlyMilestone)
+ } +

@T.Format("ImportExport.Formats.Columns", TargetName(Target.Key))

+
+ @foreach (var field in Target.Fields) + { + @field.Key@RequiredMark(field) + } +
+
+ } + else if (_step == 1) + { + + + + + + +

@T["ImportExport.Mapping.Lead"]

+ @if (MissingRequired.Count > 0) + { +
@T.Format("ImportExport.Mapping.RequiredMissing", string.Join(", ", MissingRequired))
+ } + @if (_file.Sections is { Count: > 0 } sections) + { +
@T.Format("ImportExport.Mapping.Sections", SectionsText(sections))
+ } + + + + + + + + + + @for (var i = 0; i < _file.Headers.Count; i++) + { + var column = i; + + + + + + } + +
@T["ImportExport.Mapping.Header"]@T["ImportExport.Mapping.Sample"]@T["ImportExport.Mapping.Field"]
@_file.Headers[column]@Sample(column) + +
+
+
+ } + else if (_preview is { } preview) + { + + +
+ + +
+ @if (_report is null) + { + + } + + @if (_report is null) + { + + } + else + { + + } +
+ + @if (_report is { } report) + { +
+ + @T["ImportExport.Done.Title"] · @T.Format("ImportExport.Done.Lead", TargetName(report.Target), report.Created, report.Updated, report.Skipped, report.Failed) +
+ } + else if (!preview.CanApply) + { +
@T.Format("ImportExport.Formats.CheckOnly", CheckOnlyMilestone)
+ } + @if (VisibleRows.Count == 0) + { +

@T["ImportExport.Preview.NoRows"]

+ } + else + { +
+ + + + + + @foreach (var key in PreviewFields) + { + + } + + + + @foreach (var row in VisibleRows) + { + var cells = CellsOf(row.Line); + + + + @foreach (var key in PreviewFields) + { + + } + + } + +
@T["ImportExport.Preview.Line"]@T["ImportExport.Preview.Outcome"]@FieldName(key)
@row.Line + @OutcomeText(row) + @foreach (var message in row.Messages) + { + @MessageText(message) + } + @CellOf(row, cells, key)
+
+ } +
+
+ } +
+
+} diff --git a/src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor.cs b/src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor.cs new file mode 100644 index 0000000..57ac76f --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor.cs @@ -0,0 +1,391 @@ +using Khaemhat.Application.ImportExport; +using Khaemhat.Application.Security; +using Khaemhat.Web.Shell; +using Khaemhat.Web.Ui; +using Microsoft.AspNetCore.Components.Forms; +using Microsoft.JSInterop; + +namespace Khaemhat.Web.Components.Pages.Admin; + +/// The state and the actions of the guided import and export (mockup 077). +public partial class ImportExportPage +{ + /// The largest file accepted, in megabytes. + public const int MaxMegabytes = 25; + + private const int MaxPreviewRows = 500; + private const int MaxPreviewFields = 6; + + private static readonly TransferFormat[] Formats = [TransferFormat.Csv, TransferFormat.Xlsx, TransferFormat.Json]; + + private ImportOptions _options = new(); + private string _targetKey = "clienti"; + private TransferFormat _format = TransferFormat.Csv; + private ImportFile? _file; + private long _fileBytes; + private string?[] _mapping = []; + private Dictionary _rows = []; + private ImportPreview? _preview; + private ImportReport? _report; + private bool _onlyProblems; + private bool _busy; + private int _step; + + private IReadOnlyList Targets => + [.. Imports.Targets.Where(t => Session.Permissions.Allows(t.Permission) || Session.Permissions.Allows(t.ExportPermission))]; + + private IImportTarget Target => Targets.FirstOrDefault(t => t.Key == _targetKey) ?? Targets[0]; + + private bool IsParties => Target is PartiesImportTarget; + + private bool IsRecordTarget => Target is PartiesImportTarget or ItemsImportTarget; + + private bool IsPrices => Target is PricesImportTarget; + + private bool CanExport => Target.CanExport && Session.Permissions.Flags.CanExport && Session.Permissions.Allows(Target.ExportPermission); + + private string? ExportHint => !Target.CanExport ? T["ImportExport.Export.Nothing"] : !Session.Permissions.Flags.CanExport ? T["ImportExport.Export.NotAllowed"] : null; + + private string CheckOnlyMilestone => Target is ChartOfAccountsImportTarget ? "M7" : "M6"; + + private IReadOnlyList> TargetChoices => [.. Targets.Select(t => new KhOption(t.Key, TargetName(t.Key)))]; + + private IReadOnlyList> ExistingChoices => + [.. Enum.GetValues().Select(v => new KhOption(v, T["ImportExport.ExistingChoices." + v]))]; + + private IReadOnlyList> MissingChoices => + [.. Enum.GetValues().Select(v => new KhOption(v, T["ImportExport.MissingChoices." + v]))]; + + private IReadOnlyList Steps + { + get + { + var preview = _preview; + return + [ + new(T["ImportExport.Steps.Origin"], _file is { } file + ? T.Format("ImportExport.Steps.OriginDetail", file.Name, file.Count.ToString("N0", T.Culture), Size(_fileBytes)) + : T["ImportExport.Steps.OriginEmpty"]), + new(T["ImportExport.Steps.Mapping"], _file is { } mapped + ? T.Format("ImportExport.Steps.MappingDetail", _mapping.Count(m => m is not null), mapped.Headers.Count) + : T["ImportExport.Steps.MappingEmpty"]), + new(T["ImportExport.Steps.Check"], preview is null + ? T["ImportExport.Steps.CheckEmpty"] + : T.Format("ImportExport.Steps.CheckDetail", Number(preview.Rows.Count - preview.Errors - preview.Warnings), Number(preview.Warnings), Number(preview.Errors))), + new(T["ImportExport.Steps.Import"], _report is { } report + ? T.Format("ImportExport.Steps.ImportDone", Number(report.Created), Number(report.Updated)) + : preview is null ? T["ImportExport.Steps.ImportEmpty"] + : preview.CanApply ? T.Format("ImportExport.Steps.ImportReady", Number(preview.Importable)) + : T["ImportExport.Steps.ImportCheckOnly"]), + ]; + } + } + + private IReadOnlyList MissingRequired => + [.. Target.Fields.Where(f => f.Required && !_mapping.Contains(f.Key)).Select(f => FieldName(f.Key))]; + + // The first mapped columns, then the columns that have a remark somewhere, so that every remark is next to its cell. + private IReadOnlyList PreviewFields + { + get + { + var mapped = Target.Fields.Select(f => f.Key).Where(k => _mapping.Contains(k)).ToList(); + var remarked = AllRows.SelectMany(r => r.Messages).Select(m => m.Field).ToHashSet(StringComparer.Ordinal); + var shown = mapped.Take(MaxPreviewFields).ToHashSet(StringComparer.Ordinal); + shown.UnionWith(mapped.Where(remarked.Contains).Take(MaxPreviewFields)); + return [.. mapped.Where(shown.Contains)]; + } + } + + private bool HasProblems => (_report?.Rows ?? _preview?.Rows ?? []).Any(r => r.Messages.Count > 0); + + private IReadOnlyList AllRows => _report?.Rows ?? _preview?.Rows ?? []; + + private IReadOnlyList VisibleRows => + [.. AllRows.Where(r => !_onlyProblems || r.Messages.Count > 0).Take(MaxPreviewRows)]; + + private string PreviewTitle + { + get + { + var total = AllRows.Count(r => !_onlyProblems || r.Messages.Count > 0); + return total > MaxPreviewRows + ? T.Format("ImportExport.Preview.Subtitle", Number(MaxPreviewRows), Number(total)) + : T.Format("ImportExport.Preview.SubtitleAll", Number(total)); + } + } + + private string TargetName(string key) => T["ImportExport.Targets." + key]; + + private string FieldName(string key) => T.Contains("ImportExport.Fields." + key) ? T["ImportExport.Fields." + key] : key; + + private static string RequiredMark(ImportField field) => field.Required ? " *" : string.Empty; + + private static string FormatName(TransferFormat format) => format.ToString().ToUpperInvariant(); + + private string Number(int value) => value.ToString("N0", T.Culture); + + private string Size(long bytes) => bytes >= 1024 * 1024 + ? (bytes / 1024d / 1024d).ToString("0.0", T.Culture) + " MB" + : Math.Max(1, (bytes + 512) / 1024).ToString(T.Culture) + " KB"; + + private string ImportLabel(int rows) => rows == 1 ? T["ImportExport.Preview.ImportOne"] : T.Format("ImportExport.Preview.Import", Number(rows)); + + private string SectionsText(IReadOnlyDictionary sections) => + string.Join(", ", sections.Select(s => s.Key + " (" + Number(s.Value) + ")")); + + private string? Sample(int column) => _file is { Count: > 0 } file && column < file.Rows[0].Count ? file.Rows[0][column] : null; + + private IReadOnlyDictionary? CellsOf(int line) => _rows.TryGetValue(line, out var row) ? row.Values : null; + + // The cell of the file, or the value the check proposes for it (the city from the postal code). + private static string? CellOf(ImportRowResult row, IReadOnlyDictionary? cells, string key) => + cells?.GetValueOrDefault(key) ?? row.Messages.FirstOrDefault(m => m.Field == key && m.IsWarning && m.Value is not null)?.Value; + + private static string? RowClass(ImportRowResult row) => row.Outcome switch + { + ImportOutcome.Error => "kh-import-err", + ImportOutcome.Warning => "kh-import-warn", + _ => null, + }; + + private static string? CellClass(ImportRowResult row, string key) => + row.Messages.FirstOrDefault(m => m.Field == key) is { } message ? (message.IsWarning ? "kh-import-cell-warn" : "kh-import-cell-err") : null; + + private static KhTone ToneOf(ImportRowResult row) => row.Outcome switch + { + ImportOutcome.Error => KhTone.Error, + ImportOutcome.Warning => KhTone.Warning, + _ => row.Action == ImportAction.Skip ? KhTone.Neutral : KhTone.Ok, + }; + + private string OutcomeText(ImportRowResult row) => row.Outcome switch + { + ImportOutcome.Error => T["ImportExport.Preview.Error"], + ImportOutcome.Warning when row.Messages.Count == 1 => T["ImportExport.Preview.Warning"], + ImportOutcome.Warning => T.Format("ImportExport.Preview.Warnings", row.Messages.Count), + _ => T["ImportExport.Preview." + row.Action], + }; + + private string MessageText(ImportMessage message) + { + var text = !T.Contains(message.Code) ? message.Code + : message.Value is null ? T[message.Code] + : T.Format(message.Code, message.Value); + return message.Field.Length == 0 ? text : T.Format("ImportExport.MessageField", FieldName(message.Field), text); + } + + private void Reset() + { + _file = null; + _fileBytes = 0; + _mapping = []; + _rows = []; + _preview = null; + _report = null; + _onlyProblems = false; + _step = 0; + } + + private Task SetTargetAsync(string? key) + { + _targetKey = key ?? Targets[0].Key; + _options = new ImportOptions(); + if (_file is { } file) + { + _mapping = [.. ImportService.SuggestMapping(Target, file.Headers)]; + _preview = null; + _report = null; + _step = 1; + } + + return Task.CompletedTask; + } + + private void SetExisting(ExistingCodeAction value) => _options = _options with { Existing = value }; + + private void SetMissing(MissingCodeAction value) => _options = _options with { Missing = value }; + + private void SetVerifyVat(bool value) => _options = _options with { VerifyVat = value }; + + private void SetFillFromPostalCode(bool value) => _options = _options with { FillFromPostalCode = value }; + + private void SetMapping(int column, string? key) + { + var field = string.IsNullOrEmpty(key) ? null : key; + if (field is not null) + { + // A field goes to one column only: the column that had it loses it. + for (var i = 0; i < _mapping.Length; i++) + { + if (i != column && _mapping[i] == field) + { + _mapping[i] = null; + } + } + } + + _mapping[column] = field; + _preview = null; + } + + private void ChangeFile() => Reset(); + + private void BackToMapping() + { + _preview = null; + _report = null; + _step = 1; + } + + private async Task ReadAsync(InputFileChangeEventArgs e) + { + Reset(); + if (e.File.Size > MaxMegabytes * 1024L * 1024L) + { + Toasts.Show(ToastKind.Error, e.File.Name, T.Format("ImportExport.TooLarge", MaxMegabytes)); + return; + } + + _busy = true; + try + { + await using var source = e.File.OpenReadStream(MaxMegabytes * 1024L * 1024L); + var file = await ImportFileReader.ReadAsync(e.File.Name, source); + _file = file; + _fileBytes = e.File.Size; + _mapping = [.. ImportService.SuggestMapping(Target, file.Headers)]; + _step = 1; + } + catch (ImportFileException ex) + { + Toasts.Show(ToastKind.Error, e.File.Name, T[ex.Code]); + } + catch (IOException ex) + { + Toasts.Show(ToastKind.Error, e.File.Name, ex.Message); + } + finally + { + _busy = false; + } + } + + private async Task CheckAsync() + { + if (Session.Actor is not { } actor || Session.Company is not { } company || _file is not { } file) + { + return; + } + + _busy = true; + try + { + _rows = ImportService.Rows(file, _mapping).ToDictionary(r => r.Line); + _preview = await Imports.PreviewAsync(actor, company.Code, Target.Key, file, _mapping, _options); + _report = null; + _onlyProblems = _preview.Errors + _preview.Warnings > 0 && _preview.Rows.Count > MaxPreviewRows; + _step = 2; + } + catch (AccessDeniedException) + { + Toasts.Show(ToastKind.Error, T["Pages.AccessDenied.Title"], T["ImportExport.NoTargets"]); + } + finally + { + _busy = false; + } + } + + private async Task ImportAsync() + { + if (Session.Actor is not { } actor || Session.Company is not { } company || _file is not { } file || _preview is not { } preview) + { + return; + } + + if (!await Dialogs.ConfirmAsync(new(ImportLabel(preview.Importable), T.Format("ImportExport.Preview.Confirm", Number(preview.Importable)), + ImportLabel(preview.Importable), T["Common.Cancel"]))) + { + return; + } + + _busy = true; + try + { + _report = await Imports.ImportAsync(actor, company.Code, Target.Key, file, _mapping, _options); + _onlyProblems = _report.Rows.Any(r => r.Messages.Count > 0); + _step = 3; + Toasts.Show(ToastKind.Success, T.Format("ImportExport.Done.Toast", Number(_report.Created + _report.Updated)), + T.Format("ImportExport.Done.Lead", TargetName(_report.Target), _report.Created, _report.Updated, _report.Skipped, _report.Failed)); + } + catch (AccessDeniedException) + { + Toasts.Show(ToastKind.Error, T["Pages.AccessDenied.Title"], T["ImportExport.NoTargets"]); + } + catch (ImportFileException ex) + { + Toasts.Show(ToastKind.Error, TargetName(Target.Key), T[ex.Code]); + } + finally + { + _busy = false; + } + } + + private async Task ReportAsync() + { + using var buffer = new MemoryStream(); + IReadOnlyList labels = + [ + T["ImportExport.ReportColumns.Line"], T["ImportExport.ReportColumns.Key"], T["ImportExport.ReportColumns.Field"], T["ImportExport.ReportColumns.Outcome"], + T["ImportExport.ReportColumns.Message"], + ]; + await ImportService.WriteErrorReportAsync( + AllRows, + (_, message) => (T[message.IsWarning ? "ImportExport.Outcome.Warning" : "ImportExport.Outcome.Error"], MessageText(message)), + labels, + buffer); + var name = "report-" + Path.GetFileNameWithoutExtension(_file?.Name ?? Target.Key) + ".csv"; + await DownloadAsync(buffer, name, ImportService.MediaType(TransferFormat.Csv)); + } + + private async Task TemplateAsync() + { + using var buffer = new MemoryStream(); + await ImportService.WriteTemplateAsync(Target, _format, buffer); + await DownloadAsync(buffer, ImportService.FileName(Target.Key, _format, null), ImportService.MediaType(_format)); + } + + private async Task ExportAsync() + { + if (Session.Actor is not { } actor || Session.Company is not { } company) + { + return; + } + + _busy = true; + try + { + using var buffer = new MemoryStream(); + var count = await Imports.ExportAsync(actor, company.Code, Target.Key, _format, buffer); + await DownloadAsync(buffer, ImportService.FileName(Target.Key, _format, DateOnly.FromDateTime(DateTime.Now)), ImportService.MediaType(_format)); + Toasts.Show(ToastKind.Success, TargetName(Target.Key), T.Format("ImportExport.Export.Done", Number(count))); + } + catch (AccessDeniedException) + { + Toasts.Show(ToastKind.Error, T["Pages.AccessDenied.Title"], T["ImportExport.Export.NotAllowed"]); + } + finally + { + _busy = false; + } + } + + private async Task DownloadAsync(MemoryStream buffer, string name, string mediaType) + { + buffer.Position = 0; + using var stream = new DotNetStreamReference(buffer, leaveOpen: true); + await JS.InvokeVoidAsync("khaemhat.download", name, mediaType, stream); + } +} diff --git a/src/Khaemhat.Web/Components/Pages/ComingSoon.razor b/src/Khaemhat.Web/Components/Pages/ComingSoon.razor index dc42fc8..fd4fa6c 100644 --- a/src/Khaemhat.Web/Components/Pages/ComingSoon.razor +++ b/src/Khaemhat.Web/Components/Pages/ComingSoon.razor @@ -10,7 +10,6 @@ @page "/servizi/{*Rest}" @page "/canali/{*Rest}" @page "/report/{*Rest}" -@page "/tabelle/{*Rest}" @page "/automazioni/{*Rest}" @page "/amministrazione/{*Rest}" @attribute [Authorize] diff --git a/src/Khaemhat.Web/Components/Pages/Items/ItemCategoriesPage.razor b/src/Khaemhat.Web/Components/Pages/Items/ItemCategoriesPage.razor new file mode 100644 index 0000000..5697233 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Items/ItemCategoriesPage.razor @@ -0,0 +1,10 @@ +@page "/anagrafiche/categorie" +@attribute [Authorize] +@using Khaemhat.Web.Items +@inject NavigationManager Navigation + +@* The menu entry Anagrafiche > Categorie: the item categories are a company table, kept with the others. *@ +@code { + /// + protected override void OnInitialized() => Navigation.NavigateTo(ItemScreens.CategoriesUrl, new NavigationOptions { ReplaceHistoryEntry = true }); +} diff --git a/src/Khaemhat.Web/Components/Pages/Items/ItemPage.razor b/src/Khaemhat.Web/Components/Pages/Items/ItemPage.razor new file mode 100644 index 0000000..3bc8c85 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Items/ItemPage.razor @@ -0,0 +1,782 @@ +@page "/anagrafiche/articoli/nuovo" +@page "/anagrafiche/articoli/{Id:long}" +@attribute [Authorize] +@inherits MasterDataPage +@using Khaemhat.Application.Audit +@using Khaemhat.Application.Items +@using Khaemhat.Application.Parties +@using Khaemhat.Application.Security +@using Khaemhat.Application.Tables +@using Khaemhat.Core.Common +@using Khaemhat.Core.Items +@using Khaemhat.Web.Items +@using Khaemhat.Web.Parties +@using Khaemhat.Web.Components.Pages.Parties +@using Khaemhat.Web.Tables +@inject ShellSession Session +@inject ItemService Items +@inject PriceListService PriceLists +@inject PartyService Parties +@inject TableService Tables +@inject AttachmentService Attachments + +@* The record of an item (SPEC §11.2, mockup 017): header with code, description and the base price today, tabs for + main data, alternative units, alternative codes, prices of the lists and net prices of the customers, suppliers, + substitutes, notes with attachments, history. Stock and movements per warehouse arrive with the warehouse (M6). The + checks are those of ItemService: errors stop the save and open the tab of the first one, warnings show after saving. *@ + + +@if (!_loaded) +{ +

@T["Common.Loading"]

+} +else if (Session.Company is null) +{ +

@T["Items.NoCompany"]

+} +else if (!Session.Permissions.Allows(ItemService.ReadPermission)) +{ +
+ +

@T["Pages.AccessDenied.Title"]

+

@T["Pages.AccessDenied.Lead"]

+
+} +else if (Record is null) +{ +
+ +

@T["Items.NotFound"]

+ @T["Items.Title"] +
+} +else +{ + + + + + @if (I.Disabled) + { + @T["Items.States.Disabled"] + } + else if (!IsNew) + { + @T["Items.States.Active"] + } + @if (!I.Stocked) + { + @T["Items.States.NotStocked"] + } + @if (I.IsDemo) + { + @T["Items.States.Demo"] + } + @if (IsModified) + { + @T["CompanyTables.Modified"] + } + + + @if (PartyScreens.Describe(_lookups.Categories, I.CategoryId, full: true) is { } category) + { + + } + @if (PartyScreens.Describe(_lookups.Units, I.UnitOfMeasureId) is { } unit) + { + + } + @if (PartyScreens.Describe(_lookups.TaxCodes, I.SalesTaxCodeId) is { } tax) + { + + } + @if (Record.Suppliers.FirstOrDefault(s => s.IsDefault) is { } supplier && _parties.TryGetValue(supplier.PartyId, out var party)) + { + + } + + + + + + @switch (ActiveTab) + { + case ItemScreens.Tabs.Main: + + + + + + + + + + + + + + + + + + + + + + @if (_costs) + { + + + + +

@T["Items.Hints.Costs"]

+ } + else + { +

@T["Items.Hints.CostsHidden"]

+ } +
+ + + + + + +

@T[I.Kind == ItemKind.Goods ? "Items.Hints.Stock" : "Items.Hints.NotStocked"]

+
+ + + + + break; + + case ItemScreens.Tabs.Units: +

@T["Items.Hints.Units"]

+ @for (var i = 0; i < Record.Units.Count; i++) + { + var index = i; + var u = Record.Units[i]; + + + + + @if (!IsReadOnly) + { +
+ +
+ } +
+ } + + break; + + case ItemScreens.Tabs.Barcodes: +

@T["Items.Hints.Barcodes"]

+ @for (var i = 0; i < Record.Barcodes.Count; i++) + { + var index = i; + var b = Record.Barcodes[i]; + + + + @if (!IsReadOnly) + { +
+ +
+ } +
+ } + + break; + + case ItemScreens.Tabs.Prices: + @if (_today is { } today && !IsNew) + { + + + + + + + + + @if (_costs) + { + + } + + + + @foreach (var list in _columns) + { + var cell = today.Prices.GetValueOrDefault(list.Id) ?? PriceCell.Empty; + + + + + + @if (_costs) + { + + } + + } + +
@T["Items.Fields.PriceListId"]@T["Items.Fields.Price"]@T["Items.Fields.ValidFrom"]@T["Items.Fields.Source"]@T["Items.Fields.Margin"]
@list.Code @list.Description@(cell.Price is { } p ? T.Money(p) : "-")@(cell.ValidFrom is { } from ? T.Date(from) : null)@(cell.Derived ? T["Items.Hints.Derived"] : null)@ItemScreens.MarginText(cell.Price, Cost, T.Culture)
+
+ } +

@T["Items.Hints.Prices"]

+ + @foreach (var index in PriceRows(net: false)) + { + var p = Record.Prices[index]; + + + + @if (!IsReadOnly) + { +
+ +
+ } + } + @if (!Record.Prices.Any(p => p.PartyId is null)) + { +

@T["Items.Empty.ListPrices"]

+ } + @if (!IsReadOnly) + { +
+ +
+ } +
+ + @foreach (var index in PriceRows(net: true)) + { + var p = Record.Prices[index]; + + + + @if (!IsReadOnly) + { +
+ +
+ } + } + @if (!Record.Prices.Any(p => p.PartyId is not null)) + { +

@T["Items.Empty.NetPrices"]

+ } + @if (!IsReadOnly) + { +
+ +
+ } +
+ break; + + case ItemScreens.Tabs.Suppliers: + @for (var i = 0; i < Record.Suppliers.Count; i++) + { + var index = i; + var s = Record.Suppliers[i]; + + + + + + + + @if (!IsReadOnly) + { +
+ +
+ } +
+ } + + break; + + case ItemScreens.Tabs.Substitutes: + @for (var i = 0; i < Record.Substitutes.Count; i++) + { + var index = i; + var s = Record.Substitutes[i]; + + + + @if (!IsReadOnly) + { +
+ +
+ } +
+ } + + break; + + case ItemScreens.Tabs.Notes: + + + + break; + } +
+ @if (ActiveTab == ItemScreens.Tabs.Notes && !IsNew && Session.Permissions.Allows(AttachmentService.ReadPermission)) + { +
+ } + @if (ActiveTab == ItemScreens.Tabs.History) + { +
+ } +
+
+} + +@code { + private ItemLookups _lookups = ItemLookups.Empty; + private IReadOnlyList _history = []; + private IReadOnlyList _columns = []; + private readonly Dictionary _parties = []; + private readonly Dictionary _items = []; + private PriceGridRow? _today; + private int _attachments; + private bool _costs; + private bool _loaded; + private bool _busy; + + /// The item, absent for a new one. + [Parameter] + public long? Id { get; set; } + + private Item I => Record!.Item; + + private bool CanWrite => Session.Permissions.Allows(ItemService.WritePermission); + + private string PageTitle => Record is null ? T["Items.Title"] : IsNew ? T["Items.NewTitle"] : (Record.Item.Code + " · " + Record.Item.Description); + + private PriceListColumn? BaseList => _columns.FirstOrDefault(c => c.IsBase); + + private decimal? BasePrice => BaseList is { } list && _today?.Prices.GetValueOrDefault(list.Id) is { Price: { } price } ? price : I.Price; + + private string BaseLabel => BaseList is { } list ? T["Items.Radar.BasePrice"] + " · " + list.Code : T["Items.Fields.ItemPrice"]; + + private decimal? Cost => I.AverageCost ?? I.StandardCost; + + private IReadOnlyList? HeadStats => !_costs || IsNew ? null : + [ + new(T["Items.Fields.AverageCost"], Cost is { } cost ? T.Money(cost) : "-"), + new(T["Items.Fields.Margin"], ItemScreens.MarginText(BasePrice, Cost, T.Culture) ?? "-"), + ]; + + private IReadOnlyList HeadLines + { + get + { + var lines = new List(); + if (string.Join(" · ", new[] { I.Brand, I.Manufacturer }.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct()) is { Length: > 0 } brand) + { + lines.Add(brand); + } + + if (I.Barcode is { } barcode) + { + lines.Add(T["Items.Fields.Barcode"] + " " + barcode); + } + + return lines; + } + } + + private IReadOnlyList> KindChoices => ItemScreens.Choices(T, "Kinds"); + + /// + public override bool IsReadOnly => !CanWrite; + + /// + protected override bool IsNew => Record is { Item.Id: 0 }; + + /// + protected override bool CanDelete => base.CanDelete && Session.Permissions.Allows(ItemService.DeletePermission); + + /// + protected override string? NewUrl => CanWrite ? ItemScreens.NewUrl : null; + + /// + protected override int? AttachmentCount => IsNew || Record is null ? null : _attachments; + + /// + public override IReadOnlyList Tabs => Record is null ? [] : + [ + TabOf(ItemScreens.Tabs.Main, "box", "Main"), + TabOf(ItemScreens.Tabs.Units, "layers", "Units", Record.Units.Count), + TabOf(ItemScreens.Tabs.Barcodes, "key", "Barcodes", Record.Barcodes.Count), + TabOf(ItemScreens.Tabs.Prices, "tag", "Prices", Record.Prices.Count), + TabOf(ItemScreens.Tabs.Suppliers, "truck", "Suppliers", Record.Suppliers.Count), + TabOf(ItemScreens.Tabs.Substitutes, "refresh", "Substitutes", Record.Substitutes.Count), + TabOf(ItemScreens.Tabs.Notes, "paperclip", "Notes", IsNew ? null : _attachments), + TabOf(ItemScreens.Tabs.History, "history", "History"), + ]; + + private KhTabItem TabOf(string id, string icon, string text, int? count = null) + { + // A tab with errors shows how many; otherwise how many details it holds. + var errors = Validation.Messages.Count(m => ItemScreens.TabOf(m.Field) == id); + return new(id, icon, T["Items.Tabs." + text], errors > 0 ? errors : count is > 0 ? count : null); + } + + /// + protected override async Task OnParametersSetAsync() + { + await Session.EnsureLoadedAsync(); + if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(ItemService.ReadPermission)) + { + if (!_loaded) + { + _lookups = await ItemLookups.ForRecordAsync(Tables, actor, company); + _costs = await Items.CanSeeCostsAsync(actor, company); + } + + if (Record is null || Record.Item.Id != (Id ?? 0)) + { + await ReloadAsync(); + MarkSaved(); + } + } + + _loaded = true; + } + + /// + protected override async Task ReloadAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + Validation.Clear(); + if (Id is { } id) + { + Record = await Items.GetAsync(actor, company, id); + await LoadSideAsync(actor, company); + } + else + { + Record = await Items.NewAsync(actor, company); + _history = []; + _attachments = 0; + _today = null; + _columns = await PriceLists.ListsAsync(actor, company); + } + } + + private async Task LoadSideAsync(Actor actor, string company) + { + if (Record is not { Item.Id: > 0 } record) + { + return; + } + + _history = [.. (await Items.HistoryAsync(actor, company, record.Item.Id)).Select(AuditTrailService.Item)]; + _attachments = Session.Permissions.Allows(AttachmentService.ReadPermission) + ? await Attachments.CountAsync(actor, company, ItemService.Entity, record.Item.Id) + : 0; + var grid = await PriceLists.GridAsync(actor, company, + new ListQuery { Filters = [ListFilter.Of("code", ListFilterOperator.Equals, record.Item.Code)], Limit = 1 }, Today, null); + _columns = grid.Lists; + _today = grid.Page.Items.FirstOrDefault(r => r.ItemId == record.Item.Id); + + // The names shown by the links: customers of the net prices, suppliers, substitutes. + long[] parties = [.. record.Prices.Where(p => p.PartyId is not null).Select(p => p.PartyId!.Value).Concat(record.Suppliers.Select(s => s.PartyId)).Where(p => !_parties.ContainsKey(p))]; + if (parties.Length > 0 && Session.Permissions.Allows(PartyService.ReadPermission)) + { + foreach (var row in await Parties.RowsAsync(actor, company, parties)) + { + _parties[row.Id] = row; + } + } + + long[] items = [.. record.Substitutes.Select(s => s.SubstituteId).Where(i => !_items.ContainsKey(i))]; + if (items.Length > 0) + { + foreach (var row in await Items.RowsAsync(actor, company, items)) + { + _items[row.Id] = row; + } + } + } + + private static DateOnly Today => DateOnly.FromDateTime(DateTime.Today); + + /// + protected override async Task SaveCoreAsync() + { + if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company || _busy) + { + return false; + } + + _busy = true; + Validation.Clear(); + try + { + var wasNew = IsNew; + var problems = await Items.ValidateAsync(actor, company, Record); + if (problems.Any(p => !p.IsWarning)) + { + Refuse(problems.Where(p => !p.IsWarning).Select(p => ((string?)p.Field, p.Code))); + return false; + } + + Record = await Items.SaveAsync(actor, company, Record); + await LoadSideAsync(actor, company); + if (problems.Count > 0) + { + Toasts.Show(ToastKind.Warning, T.Format("Items.Actions.Warnings", string.Join(" ", problems.Select(p => Message(p.Code))))); + } + + if (wasNew) + { + MarkSaved(); + Navigation.NavigateTo(ItemScreens.RecordUrl(Record.Item.Id), new NavigationOptions { ReplaceHistoryEntry = true }); + } + + return true; + } + catch (ValidationFailedException ex) + { + Refuse(ex.Errors.Select(TableValues.SplitError)); + return false; + } + catch (ConcurrencyException) + { + Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], T["CompanyTables.Concurrency"]); + return false; + } + finally + { + _busy = false; + } + } + + private void Refuse(IEnumerable<(string? Field, string Code)> errors) + { + foreach (var (field, code) in errors) + { + Validation.Add(field, Message(code)); + } + + // Show the tab of the first error when the open one has none. + if (!Validation.Messages.Any(m => ItemScreens.TabOf(m.Field) == ActiveTab) && Validation.Messages.FirstOrDefault() is { } first) + { + _ = ShowTabAsync(ItemScreens.TabOf(first.Field)); + } + } + + private string Message(string code) => T.Contains(code) ? T[code] : T["CompanyTables.UnknownError"]; + + /// + protected override async Task DeleteCoreAsync() + { + if (Record is not { Item.Id: > 0 } record || Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + if (await Items.DeleteAsync(actor, company, record.Item.Id) == ItemDeleteOutcome.Disabled) + { + Toasts.Show(ToastKind.Info, T["Items.Actions.DeletedInstead"]); + } + + Navigation.NavigateTo(ItemScreens.RadarUrl); + } + + /// + protected override Task RadarAsync() + { + Navigation.NavigateTo(ItemScreens.RadarUrl); + return Task.CompletedTask; + } + + /// + protected override Task AttachmentsAsync() => ShowTabAsync(ItemScreens.Tabs.Notes); + + /// + protected override IEnumerable ContextActions() + { + if (Record is null || IsNew) + { + yield break; + } + + yield return new ToolbarItem("pricelists", "tag", T["Items.Actions.PriceLists"]) + { + Kind = ToolbarKind.Action, OnClick = () => + { + Navigation.NavigateTo(ItemScreens.PriceListsUrl); + return Task.CompletedTask; + }, + }; + } + + /// + protected override IEnumerable MenuCommands() + { + if (Record is null || IsNew || !CanWrite) + { + yield break; + } + + yield return new ToolbarItem("disable", I.Disabled ? "check-circle" : "x-circle", T[I.Disabled ? "Items.Actions.Enable" : "Items.Actions.Disable"]) + { + Kind = ToolbarKind.Menu, Disabled = IsModified || _busy, OnClick = ToggleDisabledAsync, + }; + } + + private async Task ToggleDisabledAsync() + { + if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + var disabled = !I.Disabled; + await Items.SetDisabledAsync(actor, company, [I.Id], disabled); + Toasts.Show(ToastKind.Success, T.Format(disabled ? "Items.Actions.Disabled" : "Items.Actions.Enabled", 1)); + Record = await Items.GetAsync(actor, company, I.Id) ?? Record; + await LoadSideAsync(actor, company); + StateHasChanged(); + } + + private void Change(Action change) + { + change(); + MarkModified(); + } + + private static string Key(string list, int index, string field) => list + "." + index.ToString(System.Globalization.CultureInfo.InvariantCulture) + "." + field; + + private void Add(List list, TDetail detail) + { + list.Add(detail); + MarkModified(); + } + + private void Remove(List list, int index) + { + if (index < list.Count) + { + list.RemoveAt(index); + Validation.Clear(); + MarkModified(); + } + } + + // The positions of the list prices or of the net prices: the errors name a row by its position in Prices. + private List PriceRows(bool net) => [.. Enumerable.Range(0, Record!.Prices.Count).Where(i => Record.Prices[i].PartyId is not null == net)]; + + private void AddListPrice() => Add(Record!.Prices, new ItemPrice { PriceListId = BaseList?.Id ?? 0, ValidFrom = Today }); + + private void AddNetPrice() => Add(Record!.Prices, new ItemPrice { PartyId = 0, ValidFrom = Today }); + + private void SetKind(string? value) => Change(() => + { + I.Kind = Enum.Parse(value!); + // Only goods go in stock. + if (I.Kind != ItemKind.Goods) + { + I.Stocked = false; + } + }); + + private PartyRow? PartyOf(long? id) => id is { } key && _parties.TryGetValue(key, out var row) ? row : null; + + private ItemRow? ItemOf(long id) => _items.TryGetValue(id, out var row) ? row : null; + + private void SetParty(PartyRow? row, Action set) => Change(() => + { + if (row is not null) + { + _parties[row.Id] = row; + } + + set(row?.Id); + }); + + private void SetItem(ItemRow? row, Action set) => Change(() => + { + if (row is not null) + { + _items[row.Id] = row; + } + + set(row?.Id); + }); + + private async Task> SearchCustomersAsync(string text, CancellationToken cancellationToken) => + Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission) + ? await Parties.SearchAsync(actor, company, PartyArchive.Customers, text, cancellationToken) + : []; + + private async Task> SearchSuppliersAsync(string text, CancellationToken cancellationToken) => + Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission) + ? await Parties.SearchAsync(actor, company, PartyArchive.Suppliers, text, cancellationToken) + : []; + + private async Task> SearchItemsAsync(string text, CancellationToken cancellationToken) => + Session.Actor is { } actor && Session.Company?.Code is { } company + ? [.. (await Items.SearchAsync(actor, company, text, null, cancellationToken)).Where(r => r.Id != I.Id)] + : []; + + private void OpenCustomer(PartyRow row) => Navigation.NavigateTo(PartyScreens.RecordUrl(PartyArchive.Customers, row.Id)); + + private void OpenSupplier(PartyRow row) => Navigation.NavigateTo(PartyScreens.RecordUrl(PartyArchive.Suppliers, row.Id)); + + private void OpenItem(ItemRow row) => Navigation.NavigateTo(ItemScreens.RecordUrl(row.Id)); + + private string? FieldLabel(string field) + { + var key = "Items.Fields." + field.Split('.')[^1]; + return T.Contains(key) ? T[key] : null; + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Items/ItemsPage.razor b/src/Khaemhat.Web/Components/Pages/Items/ItemsPage.razor new file mode 100644 index 0000000..948b9f2 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Items/ItemsPage.razor @@ -0,0 +1,151 @@ +@page "/anagrafiche/articoli" +@attribute [Authorize] +@using Khaemhat.Application.Items +@using Khaemhat.Application.Tables +@using Khaemhat.Core.Items +@using Khaemhat.Web.Items +@using Khaemhat.Web.Parties +@inject ShellSession Session +@inject ItemService Items +@inject TableService Tables +@inject ToastService Toasts +@inject NavigationManager Navigation + +@* The radar of the items (SPEC §11.2): search on code, description, bar code, brand and producer; filters for kind, + category, stock and state; the price of the base list today and, for who may see it, the average cost. Selection to + disable or enable; Enter or double click opens the record. Stock arrives with the warehouse (M6). *@ + + +@if (!_loaded) +{ +

@T["Common.Loading"]

+} +else if (Session.Company is null) +{ +

@T["Items.NoCompany"]

+} +else if (!Session.Permissions.Allows(ItemService.ReadPermission)) +{ +
+ +

@T["Pages.AccessDenied.Title"]

+

@T["Pages.AccessDenied.Lead"]

+
+} +else +{ + + + @if (CanWrite) + { + + + + } + @T["Items.Actions.PriceLists"] + + +} + +@code { + private ItemLookups _lookups = ItemLookups.Empty; + private KhRadar? _radar; + private List _selected = []; + private bool _costs; + private bool _loaded; + private bool _busy; + + private bool CanWrite => Session.Permissions.Allows(ItemService.WritePermission); + + private static IReadOnlyList InitialFilters => [ListFilter.Of("disabled", ListFilterOperator.Equals, "false")]; + + private IReadOnlyList> Columns => + [ + new("code", T["Items.Fields.Code"], r => r.Code) { Kind = KhColumnKind.Code, Width = "130px" }, + new("description", T["Items.Fields.Description"], r => r.Description), + new("category", T["Items.Radar.Category"], r => PartyScreens.Describe(_lookups.Categories, r.CategoryId)) { Width = "110px" }, + new("unit", T["Items.Radar.Unit"], r => PartyScreens.Describe(_lookups.Units, r.UnitOfMeasureId)) { Width = "60px" }, + new("barcode", T["Items.Fields.Barcode"], r => r.Barcode) { Width = "140px", Visible = false }, + new("brand", T["Items.Fields.Brand"], r => r.Brand) { Width = "130px" }, + new("kind", T["Items.Radar.Kind"], r => T["Items.Kinds." + r.Kind]) { Width = "100px" }, + new("averageCost", T["Items.Radar.AverageCost"], r => r.AverageCost) { Kind = KhColumnKind.Money, Width = "110px", Sortable = false, Visible = _costs, Export = _costs }, + new("basePrice", T["Items.Radar.BasePrice"], r => r.BasePrice) { Kind = KhColumnKind.Money, Width = "110px", Sortable = false }, + new("state", T["Items.Radar.State"], r => StateOf(r).Text) + { + Sortable = false, Width = "130px", + Template = r => @@StateOf(r).Text, + }, + ]; + + private IReadOnlyList QuickFilters => + [ + new("kind", T["Items.Radar.Kind"], [new(string.Empty, T["Items.Radar.All"]), .. ItemScreens.Choices(T, "Kinds")]), + new("category", T["Items.Radar.Category"], [new(string.Empty, T["Items.Radar.All"]), .. _lookups.Categories]), + new("stocked", T["Items.Radar.Stocked"], + [new(string.Empty, T["Items.Radar.All"]), new("true", T["Items.Fields.Stocked"]), new("false", T["Items.States.NotStocked"])]), + new("disabled", T["Items.Radar.State"], + [new(string.Empty, T["Items.Radar.All"]), new("false", T["Items.Radar.Active"]), new("true", T["Items.Radar.Disabled"])]), + ]; + + /// + protected override async Task OnParametersSetAsync() + { + await Session.EnsureLoadedAsync(); + if (!_loaded && Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(ItemService.ReadPermission)) + { + _lookups = await ItemLookups.ForRadarAsync(Tables, actor, company); + _costs = await Items.CanSeeCostsAsync(actor, company); + } + + _loaded = true; + } + + private (string Text, KhTone Tone) StateOf(ItemRow row) => row switch + { + { Disabled: true } => (T["Items.States.Disabled"], KhTone.Neutral), + { Stocked: false } => (T["Items.States.NotStocked"], KhTone.Info), + _ => (T["Items.States.Active"], KhTone.Ok), + }; + + private Task> ListAsync(ListQuery query, CancellationToken cancellationToken) => + Session.Actor is { } actor && Session.Company?.Code is { } company + ? Items.ListAsync(actor, company, query, cancellationToken) + : Task.FromResult(new ListPage([], 0, new Dictionary())); + + private void SetSelection(IReadOnlyCollection keys) => _selected = [.. keys.OfType()]; + + private static string? RowClassOf(ItemRow row) => row.Disabled ? "muted" : null; + + private void Open(ItemRow row) => Navigation.NavigateTo(ItemScreens.RecordUrl(row.Id)); + + private void New() => Navigation.NavigateTo(ItemScreens.NewUrl); + + private async Task SetDisabledAsync(bool disabled) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _selected.Count == 0) + { + return; + } + + _busy = true; + try + { + var count = await Items.SetDisabledAsync(actor, company, _selected, disabled); + Toasts.Show(ToastKind.Success, T.Format(disabled ? "Items.Actions.Disabled" : "Items.Actions.Enabled", count)); + if (_radar is not null) + { + await _radar.ReloadAsync(); + } + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Items/PriceListsPage.razor b/src/Khaemhat.Web/Components/Pages/Items/PriceListsPage.razor new file mode 100644 index 0000000..d72cc6b --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Items/PriceListsPage.razor @@ -0,0 +1,431 @@ +@page "/anagrafiche/listini" +@attribute [Authorize] +@using Khaemhat.Application.Items +@using Khaemhat.Application.Parties +@using Khaemhat.Application.Security +@using Khaemhat.Application.Tables +@using Khaemhat.Core.Items +@using Khaemhat.Web.Items +@using Khaemhat.Web.Parties +@using Khaemhat.Web.Tables +@inject ShellSession Session +@inject PriceListService PriceLists +@inject ItemService Items +@inject PartyService Parties +@inject TableService Tables +@inject ToastService Toasts +@inject DialogService Dialogs +@inject NavigationManager Navigation + +@* The price grid (SPEC §11.2, mockup 018): one row per item, one column per active price list with the price in effect + at the validity date, the net prices of a customer and the margin. A price is changed in its cell (double click or + F2) and a mass update computes many at once: the changed cells stay highlighted until saved, and every saved price + starts at the validity date, so older documents keep the price of their day (ADR 0030). *@ + + +@if (!_loaded) +{ +

@T["Common.Loading"]

+} +else if (Session.Company is null) +{ +

@T["Items.NoCompany"]

+} +else if (!Session.Permissions.Allows(ItemService.ReadPermission)) +{ +
+ +

@T["Pages.AccessDenied.Title"]

+

@T["Pages.AccessDenied.Lead"]

+
+} +else if (_lists.Count == 0) +{ +
+ +

@T["Items.PriceLists.NoLists"]

+ @T["Items.PriceLists.NewList"] +
+} +else +{ +
+
+ + +
+
+ +
+ @if (Session.Permissions.Allows(PartyService.ReadPermission)) + { +
+ +
+ } + @if (_costs) + { + + } + + @(_party is null ? T.Format("Items.PriceLists.Count", _lists.Count) : T.Format("Items.PriceLists.CountNet", _lists.Count)) +
+ + + + @if (CanWrite) + { + + + + } + @if (Session.Permissions.Allows(TableService.WritePermission)) + { + @T["Items.PriceLists.NewList"] + } + + + @T.Format("Items.PriceLists.Footer", _pending.Count, T.Date(_date)) + + + +
@T["Items.PriceLists.Hint"]
+ + + + + + + + + + + + @if (_selected.Count > 0) + { + + } + + +
+ + +
+
+} + +@code { + private readonly Dictionary _pending = []; + private readonly KhValidation _bulkValidation = new(); + private IReadOnlyList _lists = []; + private ItemLookups _lookups = ItemLookups.Empty; + private KhRadar? _radar; + private List _selected = []; + private PartyRow? _party; + private long? _onlyList; + private DateOnly _date = DateOnly.FromDateTime(DateTime.Today); + private BulkUpdate _bulk = new(); + private bool _bulkOpen; + private bool _bulkSelected; + private bool _showMargin = true; + private bool _costs; + private bool _loaded; + private bool _busy; + + /// A cell of the grid: a list price, or the net price of a customer. + private readonly record struct Target(long ItemId, long? PriceListId, long? PartyId); + + /// A price changed and not saved: none removes the price of that day. + private readonly record struct Pending(decimal? Price, DateOnly ValidFrom); + + private bool CanWrite => Session.Permissions.Allows(ItemService.WritePermission); + + private static IReadOnlyList InitialFilters => [ListFilter.Of("disabled", ListFilterOperator.Equals, "false")]; + + private PriceListColumn? MarginList => _lists.FirstOrDefault(l => l.Id == _onlyList) ?? _lists.FirstOrDefault(l => l.IsBase) ?? _lists.FirstOrDefault(); + + private IReadOnlyList> ListChoices => [.. _lists.Select(l => new KhOption(PartyScreens.Text(l.Id)!, l.Code + " · " + l.Description))]; + + private IReadOnlyList> DirectionChoices => ItemScreens.Choices(T, "Directions"); + + private IReadOnlyList> StepChoices => + [.. new[] { 0.01m, 0.10m, 0.50m, 1.00m }.Select(s => new KhOption(StepText(s), s.ToString("0.00", T.Culture)))]; + + private void SetStep(string? value) => + _bulk = _bulk with { RoundingStep = decimal.TryParse(value, System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out var step) ? step : 0.01m }; + + private void SetDirection(string? value) => _bulk = _bulk with { Direction = Enum.TryParse(value, out var direction) ? direction : RoundingDirection.Nearest }; + + private static string StepText(decimal step) => step.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture); + + private IReadOnlyList> Columns + { + get + { + var columns = new List> + { + new("code", T["Items.Fields.Code"], r => r.Code) { Kind = KhColumnKind.Code, Width = "120px" }, + new("description", T["Items.Fields.Description"], r => r.Description), + new("unit", T["Items.Radar.Unit"], r => PartyScreens.Describe(_lookups.Units, r.UnitOfMeasureId)) { Width = "60px" }, + }; + if (_costs) + { + columns.Add(new("averageCost", T["Items.Radar.AverageCost"], r => r.AverageCost) { Kind = KhColumnKind.Money, Width = "110px", Sortable = false }); + } + + foreach (var list in _lists.Where(l => _onlyList is null || l.Id == _onlyList)) + { + var id = list.Id; + columns.Add(new("list-" + PartyScreens.Text(id), list.Code + " " + list.Description, r => PriceOf(r, id)) + { + Kind = KhColumnKind.Money, Width = "120px", Sortable = false, + CellClass = r => CellClassOf(r, new Target(r.ItemId, id, null)), + Edit = CanWrite ? (r, text) => EditAsync(new Target(r.ItemId, id, null), CurrentOf(r, id), text) : null, + }); + } + + if (_party is { } party) + { + var partyId = party.Id; + columns.Add(new("net", T.Format("Items.PriceLists.NetColumn", party.Name), r => NetOf(r, partyId)) + { + Kind = KhColumnKind.Money, Width = "140px", Sortable = false, + CellClass = r => CellClassOf(r, new Target(r.ItemId, null, partyId)), + Edit = CanWrite ? (r, text) => EditAsync(new Target(r.ItemId, null, partyId), r.Net?.Price, text) : null, + }); + } + + if (_costs && _showMargin && MarginList is { } marginList) + { + var id = marginList.Id; + columns.Add(new("margin", T.Format("Items.PriceLists.Margin", marginList.Code), r => ItemScreens.MarginText(PriceOf(r, id), r.AverageCost, T.Culture)) + { + Width = "100px", Sortable = false, CellClass = _ => "num", + }); + } + + return columns; + } + } + + private IReadOnlyList QuickFilters => + [ + new("category", T["Items.Radar.Category"], [new(string.Empty, T["Items.Radar.All"]), .. _lookups.Categories]), + new("disabled", T["Items.Radar.State"], + [new(string.Empty, T["Items.Radar.All"]), new("false", T["Items.Radar.Active"]), new("true", T["Items.Radar.Disabled"])]), + ]; + + /// + protected override async Task OnParametersSetAsync() + { + await Session.EnsureLoadedAsync(); + if (!_loaded && Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(ItemService.ReadPermission)) + { + _lookups = await ItemLookups.ForRadarAsync(Tables, actor, company); + _lists = await PriceLists.ListsAsync(actor, company); + _costs = await Items.CanSeeCostsAsync(actor, company); + } + + _loaded = true; + } + + private async Task> ListAsync(ListQuery query, CancellationToken cancellationToken) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return new ListPage([], 0, new Dictionary()); + } + + var grid = await PriceLists.GridAsync(actor, company, query, _date, _party?.Id, cancellationToken); + return grid.Page; + } + + private decimal? CurrentOf(PriceGridRow row, long listId) => row.Prices.GetValueOrDefault(listId)?.Price; + + private decimal? PriceOf(PriceGridRow row, long listId) => + _pending.TryGetValue(new Target(row.ItemId, listId, null), out var pending) ? pending.Price : CurrentOf(row, listId); + + private decimal? NetOf(PriceGridRow row, long partyId) => + _pending.TryGetValue(new Target(row.ItemId, null, partyId), out var pending) ? pending.Price : row.Net?.Price; + + private string? CellClassOf(PriceGridRow row, Target target) + { + if (_pending.ContainsKey(target)) + { + return "kh-changed"; + } + + return target.PriceListId is { } list && row.Prices.GetValueOrDefault(list) is { Derived: true } ? "kh-derived" : null; + } + + private Task EditAsync(Target target, decimal? current, string text) + { + if (!ItemScreens.TryParsePrice(text, T.Culture, out var price)) + { + return Task.FromResult(T["Items.PriceLists.Invalid"]); + } + + // Back to the price in effect: nothing to save for this cell. + if (price == current) + { + _pending.Remove(target); + } + else + { + _pending[target] = new Pending(price, _date); + } + + // The grid calls this as a plain delegate: the page renders again for Save and Undo to follow the count. + StateHasChanged(); + return Task.FromResult(null); + } + + private static string? RowClassOf(PriceGridRow row) => null; + + private void SetSelection(IReadOnlyCollection keys) => _selected = [.. keys.OfType()]; + + private void Open(PriceGridRow row) => Navigation.NavigateTo(ItemScreens.RecordUrl(row.ItemId)); + + private async Task SetDateAsync(DateOnly? value) + { + if (_pending.Count > 0) + { + Toasts.Show(ToastKind.Warning, T["Items.PriceLists.Leave"]); + return; + } + + _date = value ?? DateOnly.FromDateTime(DateTime.Today); + await ReloadAsync(); + } + + private async Task SetPartyAsync(PartyRow? value) + { + if (_pending.Keys.Any(k => k.PartyId is not null)) + { + Toasts.Show(ToastKind.Warning, T["Items.PriceLists.Leave"]); + return; + } + + _party = value; + await ReloadAsync(); + } + + private async Task> SearchCustomersAsync(string text, CancellationToken cancellationToken) => + Session.Actor is { } actor && Session.Company?.Code is { } company + ? await Parties.SearchAsync(actor, company, PartyArchive.Customers, text, cancellationToken) + : []; + + private async Task ReloadAsync() + { + StateHasChanged(); + if (_radar is not null) + { + await _radar.ReloadAsync(); + } + } + + private async Task SaveAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + if (_pending.Count == 0) + { + Toasts.Show(ToastKind.Info, T["Items.PriceLists.NoChanges"]); + return; + } + + _busy = true; + try + { + IReadOnlyList edits = [.. _pending.Select(p => new PriceEdit(p.Key.ItemId, p.Key.PriceListId, p.Key.PartyId, p.Value.Price, p.Value.ValidFrom))]; + var written = await PriceLists.SaveAsync(actor, company, edits); + _pending.Clear(); + Toasts.Show(ToastKind.Success, T.Format("Items.PriceLists.Saved", written)); + await ReloadAsync(); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], + string.Join(" ", ex.Errors.Select(TableValues.SplitError).Select(e => e.Code).Distinct().Select(c => T.Contains(c) ? T[c] : T["CompanyTables.UnknownError"]))); + } + finally + { + _busy = false; + } + } + + private async Task UndoAsync() + { + if (_pending.Count == 0 + || !await Dialogs.ConfirmAsync(new(T["Items.PriceLists.UndoTitle"], T["Items.PriceLists.UndoText"], T["Items.PriceLists.Undo"], T["Common.Cancel"], Danger: true))) + { + return; + } + + _pending.Clear(); + await ReloadAsync(); + } + + private void OpenBulk() + { + _bulkValidation.Clear(); + _bulk = new BulkUpdate + { + PriceListId = _onlyList ?? _lists.FirstOrDefault(l => l.IsBase)?.Id ?? _lists[0].Id, RoundingStep = 0.10m, Direction = RoundingDirection.Nearest, Date = _date, + }; + _bulkSelected = _selected.Count > 0; + _bulkOpen = true; + } + + private async Task ApplyBulkAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _busy = true; + try + { + var update = _bulk with { ItemIds = _bulkSelected && _selected.Count > 0 ? [.. _selected] : null }; + var edits = await PriceLists.PreviewAsync(actor, company, update); + foreach (var edit in edits) + { + _pending[new Target(edit.ItemId, edit.PriceListId, edit.PartyId)] = new Pending(edit.Price, edit.ValidFrom ?? update.Date); + } + + _bulkOpen = false; + Toasts.Show(edits.Count == 0 ? ToastKind.Info : ToastKind.Success, edits.Count == 0 ? T["Items.Bulk.None"] : T.Format("Items.Bulk.Result", edits.Count)); + await ReloadAsync(); + } + catch (ValidationFailedException ex) + { + _bulkValidation.Clear(); + foreach (var (field, code) in ex.Errors.Select(TableValues.SplitError)) + { + _bulkValidation.Add(field, T.Contains(code) ? T[code] : T["CompanyTables.UnknownError"]); + } + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Parties/DetailFooter.razor b/src/Khaemhat.Web/Components/Pages/Parties/DetailFooter.razor new file mode 100644 index 0000000..7cc62a0 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Parties/DetailFooter.razor @@ -0,0 +1,30 @@ +@* The foot of a list of details of a party (addresses, contacts, bank accounts): what to say when it is empty and the + button that adds one. *@ +
+ @if (Empty is not null) + { + @Empty + } + @if (CanAdd) + { + + } +
+ +@code { + /// The text of an empty list, or . + [Parameter] + public string? Empty { get; set; } + + /// Whether a detail can be added. + [Parameter] + public bool CanAdd { get; set; } + + /// The text of the button. + [Parameter] + public string AddText { get; set; } = string.Empty; + + /// Adds a detail. + [Parameter] + public EventCallback OnAdd { get; set; } +} diff --git a/src/Khaemhat.Web/Components/Pages/Parties/PartiesPage.razor b/src/Khaemhat.Web/Components/Pages/Parties/PartiesPage.razor new file mode 100644 index 0000000..c17ae83 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Parties/PartiesPage.razor @@ -0,0 +1,165 @@ +@page "/anagrafiche/clienti" +@page "/anagrafiche/fornitori" +@page "/anagrafiche/contatti" +@attribute [Authorize] +@using Khaemhat.Application.Parties +@using Khaemhat.Application.Tables +@using Khaemhat.Core.Parties +@using Khaemhat.Web.Parties +@inject ShellSession Session +@inject PartyService Parties +@inject TableService Tables +@inject ToastService Toasts +@inject NavigationManager Navigation + +@* The radar of the parties (SPEC §11.2, mockups 012 and 013): customers, suppliers, or prospects and leads. Search on + code, name, VAT number, tax code and city; filters for kind, subject and state; selection to disable or enable; Enter + or double click opens the record. Turnover and overdue arrive with sales (M5) and the schedule (M9). *@ + + +@if (!_loaded) +{ +

@T["Common.Loading"]

+} +else if (Session.Company is null) +{ +

@T["Parties.NoCompany"]

+} +else if (!Session.Permissions.Allows(PartyService.ReadPermission)) +{ +
+ +

@T["Pages.AccessDenied.Title"]

+

@T["Pages.AccessDenied.Lead"]

+
+} +else +{ + + + @if (CanWrite) + { + + @if (_archive == PartyArchive.Contacts) + { + + } + + + } + + +} + +@code { + private PartyArchive _archive; + private PartyLookups _lookups = PartyLookups.Empty; + private KhRadar? _radar; + private List _selected = []; + private bool _loaded; + private bool _busy; + + private string Title => T["Parties.Archives." + _archive]; + + private bool CanWrite => Session.Permissions.Allows(PartyService.WritePermission); + + private static IReadOnlyList InitialFilters => [ListFilter.Of("disabled", ListFilterOperator.Equals, "false")]; + + private IReadOnlyList> Columns => + [ + new("code", T["Parties.Fields.Code"], r => r.Code) { Kind = KhColumnKind.Code, Width = "110px" }, + new("name", T["Parties.Fields.Name"], r => r.Name), + new("vatNumber", T["Parties.Radar.Identifier"], r => r.Identifier) { Width = "170px" }, + new("city", T["Parties.Radar.City"], r => r.Province is { } p ? r.City + " (" + p + ")" : r.City) { Width = "170px" }, + new("payment", T["Parties.Radar.Payment"], r => PartyScreens.Describe(_lookups.PaymentTerms, r.Terms?.PaymentTermId, full: true)) { Sortable = false, Visible = _archive != PartyArchive.Contacts }, + new("priceList", T["Parties.Radar.PriceList"], r => PartyScreens.Describe(_lookups.PriceLists, r.Terms?.PriceListId)) { Sortable = false, Width = "90px", Visible = _archive == PartyArchive.Customers }, + new("salesperson", T["Parties.Radar.Salesperson"], r => PartyScreens.Describe(_lookups.Salespeople, r.SalespersonId, full: true)) { Width = "120px" }, + new("kind", T["Parties.Radar.Kind"], r => T["Parties.Kinds." + r.Kind]) { Width = "100px", Visible = _archive == PartyArchive.Contacts }, + new("state", T["Parties.Radar.State"], r => StateOf(r).Text) + { + Sortable = false, Width = "130px", + Template = r => @@StateOf(r).Text, + }, + ]; + + private IReadOnlyList QuickFilters => + [ + .. _archive == PartyArchive.Contacts + ? [new KhQuickFilter("kind", T["Parties.Radar.Kind"], + [new(string.Empty, T["Parties.Radar.All"]), new(nameof(PartyKind.Prospect), T["Parties.Kinds.Prospect"]), new(nameof(PartyKind.Lead), T["Parties.Kinds.Lead"])])] + : Array.Empty(), + new("subjectType", T["Parties.Radar.Subject"], + [new(string.Empty, T["Parties.Radar.All"]), .. PartyScreens.Choices(T, "SubjectTypes")]), + new("salesperson", T["Parties.Radar.Salesperson"], [new(string.Empty, T["Parties.Radar.All"]), .. _lookups.Salespeople]), + new("disabled", T["Parties.Radar.State"], + [new(string.Empty, T["Parties.Radar.All"]), new("false", T["Parties.Radar.Active"]), new("true", T["Parties.Radar.Disabled"])]), + ]; + + /// + protected override async Task OnParametersSetAsync() + { + _archive = PartyScreens.ArchiveOf(Navigation.ToBaseRelativePath(Navigation.Uri)); + _selected = []; + await Session.EnsureLoadedAsync(); + if (!_loaded && Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission)) + { + _lookups = await PartyLookups.ForRadarAsync(Tables, actor, company); + } + + _loaded = true; + } + + private (string Text, KhTone Tone) StateOf(PartyRow row) => row switch + { + { Disabled: true } => (T["Parties.States.Disabled"], KhTone.Neutral), + { Terms.Blocked: true } => (T["Parties.States.Blocked"], KhTone.Error), + { Terms.SplitPayment: true } => (T["Parties.States.Split"], KhTone.Info), + { SubjectType: SubjectType.EuCompany or SubjectType.NonEuCompany or SubjectType.Person } => (T["Parties.SubjectTypes." + row.SubjectType], KhTone.Info), + { Kind: PartyKind.Customer, IsAlsoSupplier: true } when _archive == PartyArchive.Suppliers => (T["Parties.States.AlsoCustomer"], KhTone.Accent), + { IsAlsoSupplier: true } => (T["Parties.States.AlsoSupplier"], KhTone.Accent), + _ => (T["Parties.States.Active"], KhTone.Ok), + }; + + private Task> ListAsync(ListQuery query, CancellationToken cancellationToken) => + Session.Actor is { } actor && Session.Company?.Code is { } company + ? Parties.ListAsync(actor, company, _archive, query, cancellationToken) + : Task.FromResult(new ListPage([], 0, new Dictionary())); + + private void SetSelection(IReadOnlyCollection keys) => _selected = [.. keys.OfType()]; + + private static string? RowClassOf(PartyRow row) => row.Disabled ? "muted" : null; + + private void Open(PartyRow row) => Navigation.NavigateTo(PartyScreens.RecordUrl(_archive, row.Id)); + + private void New(PartyKind? kind) => Navigation.NavigateTo(PartyScreens.NewUrl(_archive, kind)); + + private async Task SetDisabledAsync(bool disabled) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _selected.Count == 0) + { + return; + } + + _busy = true; + try + { + var count = await Parties.SetDisabledAsync(actor, company, _selected, disabled); + Toasts.Show(ToastKind.Success, T.Format(disabled ? "Parties.Actions.Disabled" : "Parties.Actions.Enabled", count)); + if (_radar is not null) + { + await _radar.ReloadAsync(); + } + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Parties/PartyPage.razor b/src/Khaemhat.Web/Components/Pages/Parties/PartyPage.razor new file mode 100644 index 0000000..96533f7 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Parties/PartyPage.razor @@ -0,0 +1,1002 @@ +@page "/anagrafiche/clienti/nuovo" +@page "/anagrafiche/clienti/{Id:long}" +@page "/anagrafiche/fornitori/nuovo" +@page "/anagrafiche/fornitori/{Id:long}" +@page "/anagrafiche/contatti/nuovo" +@page "/anagrafiche/contatti/{Id:long}" +@attribute [Authorize] +@inherits MasterDataPage +@using Khaemhat.Application.Audit +@using Khaemhat.Application.Items +@using Khaemhat.Application.Parties +@using Khaemhat.Application.Security +@using Khaemhat.Application.Tables +@using Khaemhat.Core.Common +@using Khaemhat.Core.Items +@using Khaemhat.Core.Parties +@using Khaemhat.Fiscal.Abstractions +@using Khaemhat.Infrastructure.Http +@using Khaemhat.Web.Items +@using Khaemhat.Web.Parties +@using Khaemhat.Web.Tables +@inject ShellSession Session +@inject PartyService Parties +@inject ItemService Items +@inject TableService Tables +@inject AutoFillService AutoFill +@inject AttachmentService Attachments + +@* The record of a party (SPEC §11.2, mockups 014-016): header with identity and conditions, tabs for main data, + addresses, contacts, terms, fiscal data and e-invoice, banks, notes with attachments, history. The checks are those + of PartyService: errors stop the save and open the tab of the first one, warnings are shown after saving. *@ + + +@if (!_loaded) +{ +

@T["Common.Loading"]

+} +else if (Session.Company is null) +{ +

@T["Parties.NoCompany"]

+} +else if (!Session.Permissions.Allows(PartyService.ReadPermission)) +{ +
+ +

@T["Pages.AccessDenied.Title"]

+

@T["Pages.AccessDenied.Lead"]

+
+} +else if (Record is null) +{ +
+ +

@T["Parties.NotFound"]

+ @T["Parties.Archives." + _archive] +
+} +else +{ + + + + + @T["Parties.SubjectTypes." + P.SubjectType] + @if (P.PreviousCode is { } previous) + { + · @T["Parties.Fields.PreviousCode"] @previous + } + + + @if (P.Disabled) + { + @T["Parties.States.Disabled"] + } + else if (Record.Sales.Blocked) + { + @T["Parties.States.Blocked"] + } + else if (!IsNew) + { + @T["Parties.States.Active"] + } + @if (P.Kind == PartyKind.Customer && P.IsAlsoSupplier) + { + @T["Parties.States.AlsoSupplier"] + } + @if (P.IsDemo) + { + @T["Parties.States.Demo"] + } + @if (IsModified) + { + @T["CompanyTables.Modified"] + } + + + @if (PartyScreens.Describe(_lookups.PaymentTerms, PaymentTermId, full: true) is { } payment) + { + + } + @if (P.IsCustomer && PartyScreens.Describe(_lookups.PriceLists, Record.Sales.PriceListId) is { } list) + { + + } + @if (PartyScreens.Describe(_lookups.Salespeople, P.SalespersonId, full: true) is { } salesperson) + { + + } + @if (P.VatCheck != VatCheckStatus.None) + { + + } + @if (Record.Fiscal.SplitPayment) + { + + } + + + + + + @switch (ActiveTab) + { + case PartyScreens.Tabs.Main: + + + + + @if (P.SubjectType == SubjectType.Person) + { + + + } + + + + + + + @if (P.SubjectType == SubjectType.Person && !IsReadOnly) + { + + + + +
+ +
+
+ } + + + + + + + @if (_places.Count > 1) + { +
+ @T.Format("Parties.Actions.Places", _places.Count) + @foreach (var place in _places) + { + + } +
+ } + +
+ + + + + + + + + + + + + + + @if (P.Kind == PartyKind.Customer) + { + + } + + + break; + + case PartyScreens.Tabs.Addresses: + @for (var i = 0; i < Record.Addresses.Count; i++) + { + var index = i; + var a = Record.Addresses[i]; + + + + + + + + + + + + @if (!IsReadOnly) + { +
+ +
+ } +
+ } + + break; + + case PartyScreens.Tabs.Contacts: + @for (var i = 0; i < Record.Contacts.Count; i++) + { + var index = i; + var c = Record.Contacts[i]; + + + + + + + + + @if (!IsReadOnly) + { +
+ +
+ } +
+ } + + break; + + case PartyScreens.Tabs.Terms: + @if (!P.IsCustomer && !P.IsSupplier) + { +

@T["Parties.NoTerms"]

+ } + @if (P.IsCustomer) + { + var s = Record.Sales; + + + + + + + + + + + + + + + + + + + } + @if (P.IsSupplier) + { + var u = Record.Purchase; + + + + + + + + + + + } + @if (P.IsCustomer || P.IsSupplier) + { + + @if (P.IsCustomer) + { + + } + @if (P.IsSupplier) + { + + } +

@T["Parties.AccountsHint"]

+
+

@T["Parties.TermsHint"]

+ } + break; + + case PartyScreens.Tabs.Fiscal: + var f = Record.Fiscal; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

@T["Parties.IntentHint"]

+
+ break; + + case PartyScreens.Tabs.Banks: + @for (var i = 0; i < Record.BankAccounts.Count; i++) + { + var index = i; + var b = Record.BankAccounts[i]; + + + + + + + + @if (!IsReadOnly) + { +
+ +
+ } +
+ } + + break; + + case PartyScreens.Tabs.ItemCodes: +

@T["Parties.ItemCodesHint"]

+ @for (var i = 0; i < Record.ItemCodes.Count; i++) + { + var index = i; + var c = Record.ItemCodes[i]; + + + + + @if (!IsReadOnly) + { +
+ +
+ } +
+ } + + break; + + case PartyScreens.Tabs.Notes: + + + + break; + } +
+ @if (ActiveTab == PartyScreens.Tabs.Notes && !IsNew && Session.Permissions.Allows(AttachmentService.ReadPermission)) + { +
+ } + @if (ActiveTab == PartyScreens.Tabs.History) + { +
+ } +
+
+} + +@code { + private PartyArchive _archive; + private PartyLookups _lookups = PartyLookups.Empty; + private IReadOnlyList _history = []; + private IReadOnlyList _places = []; + private readonly Dictionary _items = []; + private int _attachments; + private bool _loaded; + private bool _busy; + private DateOnly? _birthDate; + private string? _sex; + private string? _birthPlace; + + /// The party, absent for a new one. + [Parameter] + public long? Id { get; set; } + + /// The kind of a new party among the contacts (?tipo=lead). + [SupplyParameterFromQuery(Name = "tipo")] + public string? Kind { get; set; } + + private Party P => Record!.Party; + + private bool CanWrite => Session.Permissions.Allows(PartyService.WritePermission); + + private bool CanReadItems => Session.Permissions.Allows(ItemService.ReadPermission); + + private string KindIcon => Record?.Party.Kind switch + { + PartyKind.Supplier => "truck", + PartyKind.Prospect or PartyKind.Lead => "target", + _ => "users", + }; + + private string PageTitle => Record is null ? T["Parties.Archives." + _archive] + : IsNew ? T["Parties.New." + Record.Party.Kind] + : (Record.Party.Code + " · " + Record.Party.Name); + + private long? PaymentTermId => P.IsCustomer ? Record!.Sales.PaymentTermId : Record!.Purchase.PaymentTermId; + + private IReadOnlyList HeadLines + { + get + { + var lines = new List(); + var street = string.Join(' ', new[] { P.Address, P.StreetNumber }.Where(s => !string.IsNullOrWhiteSpace(s))); + var place = string.Join(' ', new[] { P.PostalCode, P.City, P.Province is { } p ? "(" + p + ")" : null }.Where(s => !string.IsNullOrWhiteSpace(s))); + if (string.Join(" · ", new[] { street, place }.Where(s => s.Length > 0)) is { Length: > 0 } address) + { + lines.Add(address); + } + + var ids = new List(); + if (P.VatNumber is { } vat) + { + ids.Add(T["Parties.Fields.VatNumber"] + " " + (P.CountryCode == "IT" ? vat : P.CountryCode + vat)); + } + + if (P.TaxCode is { } tax && tax != P.VatNumber) + { + ids.Add(T["Parties.Fields.TaxCode"] + " " + tax); + } + + if (ids.Count > 0) + { + lines.Add(string.Join(" · ", ids)); + } + + if (string.Join(" · ", new[] { P.Phone, P.Email ?? P.Pec }.Where(s => !string.IsNullOrWhiteSpace(s))) is { Length: > 0 } reach) + { + lines.Add(reach); + } + + return lines; + } + } + + private IReadOnlyList> KindChoices => PartyScreens.Choices(T, "Kinds"); + + private IReadOnlyList> SubjectChoices => PartyScreens.Choices(T, "SubjectTypes"); + + private IReadOnlyList> AddressKindChoices => PartyScreens.Choices(T, "AddressKinds"); + + private IReadOnlyList> DeliveryChoices => PartyScreens.Choices(T, "Delivery"); + + private IReadOnlyList> SexChoices => PartyScreens.Choices(T, "Sexes"); + + private IReadOnlyList> ExigibilityChoices => [.. new[] { "I", "D", "S" }.Select(v => new KhOption(v, T["Parties.Exigibilities." + v]))]; + + /// + public override bool IsReadOnly => !CanWrite; + + /// + protected override bool IsNew => Record is { Party.Id: 0 }; + + /// + protected override bool CanDelete => base.CanDelete && Session.Permissions.Allows(PartyService.DeletePermission); + + /// + protected override string? NewUrl => CanWrite ? PartyScreens.NewUrl(_archive) : null; + + /// + protected override int? AttachmentCount => IsNew || Record is null ? null : _attachments; + + /// + public override IReadOnlyList Tabs => Record is null ? [] : + [ + TabOf(PartyScreens.Tabs.Main, "user", "Main"), + TabOf(PartyScreens.Tabs.Addresses, "pin", "Addresses", Record.Addresses.Count), + TabOf(PartyScreens.Tabs.Contacts, "phone", "Contacts", Record.Contacts.Count), + TabOf(PartyScreens.Tabs.Terms, "coins", "Terms"), + TabOf(PartyScreens.Tabs.Fiscal, "file-check", "Fiscal"), + TabOf(PartyScreens.Tabs.Banks, "euro", "Banks", Record.BankAccounts.Count), + TabOf(PartyScreens.Tabs.ItemCodes, "box", "ItemCodes", Record.ItemCodes.Count), + TabOf(PartyScreens.Tabs.Notes, "paperclip", "Notes", IsNew ? null : _attachments), + TabOf(PartyScreens.Tabs.History, "history", "History"), + ]; + + private KhTabItem TabOf(string id, string icon, string text, int? count = null) + { + // A tab with errors shows how many; otherwise how many details it holds. + var errors = Validation.Messages.Count(m => PartyScreens.TabOf(m.Field) == id); + return new(id, icon, T["Parties.Tabs." + text], errors > 0 ? errors : count is > 0 ? count : null); + } + + /// + protected override async Task OnParametersSetAsync() + { + _archive = PartyScreens.ArchiveOf(Navigation.ToBaseRelativePath(Navigation.Uri)); + await Session.EnsureLoadedAsync(); + if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission)) + { + if (!_loaded) + { + _lookups = await PartyLookups.ForRecordAsync(Tables, actor, company); + } + + if (Record is null || Record.Party.Id != (Id ?? 0)) + { + await ReloadAsync(); + MarkSaved(); + } + } + + _loaded = true; + } + + /// + protected override async Task ReloadAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + Validation.Clear(); + _places = []; + if (Id is { } id) + { + Record = await Parties.GetAsync(actor, company, id); + await LoadSideAsync(actor, company); + } + else + { + Record = await Parties.NewAsync(actor, company, PartyScreens.KindOf(_archive, Kind)); + _history = []; + _attachments = 0; + } + } + + private async Task LoadSideAsync(Actor actor, string company) + { + if (Record is not { Party.Id: > 0 } record) + { + return; + } + + _history = [.. (await Parties.HistoryAsync(actor, company, record.Party.Id)).Select(AuditTrailService.Item)]; + long[] items = [.. record.ItemCodes.Select(c => c.ItemId).Where(i => i > 0 && !_items.ContainsKey(i))]; + if (items.Length > 0 && CanReadItems) + { + foreach (var row in await Items.RowsAsync(actor, company, items)) + { + _items[row.Id] = row; + } + } + + _attachments = Session.Permissions.Allows(AttachmentService.ReadPermission) + ? await Attachments.CountAsync(actor, company, PartyService.Entity, record.Party.Id) + : 0; + } + + /// + protected override async Task SaveCoreAsync() + { + if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company || _busy) + { + return false; + } + + _busy = true; + Validation.Clear(); + try + { + var wasNew = IsNew; + var problems = await Parties.ValidateAsync(actor, company, Record); + if (problems.Any(p => !p.IsWarning)) + { + Refuse(problems.Where(p => !p.IsWarning).Select(p => ((string?)p.Field, p.Code))); + return false; + } + + Record = await Parties.SaveAsync(actor, company, Record); + await LoadSideAsync(actor, company); + if (problems.Count > 0) + { + Toasts.Show(ToastKind.Warning, T.Format("Parties.Actions.Warnings", string.Join(" ", problems.Select(p => Message(p.Code))))); + } + + if (wasNew) + { + MarkSaved(); + Navigation.NavigateTo(PartyScreens.RecordUrl(_archive, Record.Party.Id), new NavigationOptions { ReplaceHistoryEntry = true }); + } + + return true; + } + catch (ValidationFailedException ex) + { + Refuse(ex.Errors.Select(TableValues.SplitError)); + return false; + } + catch (ConcurrencyException) + { + Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], T["CompanyTables.Concurrency"]); + return false; + } + finally + { + _busy = false; + } + } + + private void Refuse(IEnumerable<(string? Field, string Code)> errors) + { + foreach (var (field, code) in errors) + { + Validation.Add(field, Message(code)); + } + + // Show the tab of the first error when the open one has none. + if (!Validation.Messages.Any(m => PartyScreens.TabOf(m.Field) == ActiveTab) && Validation.Messages.FirstOrDefault() is { } first) + { + _ = ShowTabAsync(PartyScreens.TabOf(first.Field)); + } + } + + private string Message(string code) => T.Contains(code) ? T[code] : T["CompanyTables.UnknownError"]; + + /// + protected override async Task DeleteCoreAsync() + { + if (Record is not { Party.Id: > 0 } record || Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + if (await Parties.DeleteAsync(actor, company, record.Party.Id) == PartyDeleteOutcome.Disabled) + { + Toasts.Show(ToastKind.Info, T["Parties.Actions.DeletedInstead"]); + } + + Navigation.NavigateTo(PartyScreens.RadarUrl(_archive)); + } + + /// + protected override Task RadarAsync() + { + Navigation.NavigateTo(PartyScreens.RadarUrl(_archive)); + return Task.CompletedTask; + } + + /// + protected override Task AttachmentsAsync() => ShowTabAsync(PartyScreens.Tabs.Notes); + + /// + protected override IEnumerable ContextActions() + { + if (Record is null || IsNew || !CanWrite) + { + yield break; + } + + if (P.VatNumber is not null && P.SubjectType is SubjectType.EuCompany or SubjectType.Company) + { + yield return new ToolbarItem("vies", "shield-check", T["Parties.Actions.Vies"]) + { + Kind = ToolbarKind.Action, Disabled = IsModified || _busy, OnClick = CheckVatAsync, + }; + } + + if (P.Kind != PartyKind.Customer) + { + yield return new ToolbarItem("convert", "users", T["Parties.Actions.Convert"]) + { + Kind = ToolbarKind.Action, Primary = P.Kind is PartyKind.Prospect or PartyKind.Lead, Disabled = IsModified || _busy, OnClick = ConvertAsync, + }; + } + } + + /// + protected override IEnumerable MenuCommands() + { + if (Record is null || IsNew || !CanWrite) + { + yield break; + } + + yield return new ToolbarItem("disable", P.Disabled ? "check-circle" : "x-circle", T[P.Disabled ? "Parties.Actions.Enable" : "Parties.Actions.Disable"]) + { + Kind = ToolbarKind.Menu, Disabled = IsModified || _busy, OnClick = ToggleDisabledAsync, + }; + } + + private async Task CheckVatAsync() + { + if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _busy = true; + try + { + var result = await Parties.CheckVatAsync(actor, company, P.Id); + if (result is null) + { + Toasts.Show(ToastKind.Warning, T["Parties.Vies.NeedsVat"]); + return; + } + + Record = await Parties.GetAsync(actor, company, P.Id) ?? Record; + var tone = result.Status == ViesStatus.Valid ? ToastKind.Success : result.Status == ViesStatus.Invalid ? ToastKind.Error : ToastKind.Warning; + Toasts.Show(tone, T["Parties.Vies." + result.Status], result.Name); + await LoadSideAsync(actor, company); + } + finally + { + _busy = false; + StateHasChanged(); + } + } + + private async Task ConvertAsync() + { + if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company + || !await Dialogs.ConfirmAsync(new(T["Parties.Actions.ConvertTitle"], T["Parties.Actions.ConvertText"], T["Parties.Actions.Convert"], T["Common.Cancel"]))) + { + return; + } + + try + { + var converted = await Parties.ConvertToCustomerAsync(actor, company, P.Id); + Toasts.Show(ToastKind.Success, T.Format("Parties.Actions.Converted", converted.Party.Code)); + Record = converted; + Navigation.NavigateTo(PartyScreens.RecordUrl(PartyArchive.Customers, converted.Party.Id)); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], string.Join(" ", ex.Errors.Select(TableValues.SplitError).Select(e => Message(e.Code)))); + } + } + + private async Task ToggleDisabledAsync() + { + if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + var disabled = !P.Disabled; + await Parties.SetDisabledAsync(actor, company, [P.Id], disabled); + Toasts.Show(ToastKind.Success, T.Format(disabled ? "Parties.Actions.Disabled" : "Parties.Actions.Enabled", 1)); + Record = await Parties.GetAsync(actor, company, P.Id) ?? Record; + await LoadSideAsync(actor, company); + StateHasChanged(); + } + + private void Change(Action change) + { + change(); + MarkModified(); + } + + private static string Key(string list, int index, string field) => list + "." + index.ToString(System.Globalization.CultureInfo.InvariantCulture) + "." + field; + + private void Add(List list, TDetail detail) + { + list.Add(detail); + MarkModified(); + } + + private void Remove(List list, int index) + { + if (index < list.Count) + { + list.RemoveAt(index); + Validation.Clear(); + MarkModified(); + } + } + + private ItemRow? ItemOf(long id) => _items.TryGetValue(id, out var row) ? row : null; + + private void SetItem(PartyItemCode code, ItemRow? row) => Change(() => + { + if (row is not null) + { + _items[row.Id] = row; + } + + code.ItemId = row?.Id ?? 0; + code.Description ??= row?.Description; + }); + + private async Task> SearchItemsAsync(string text, CancellationToken cancellationToken) => + Session.Actor is { } actor && Session.Company?.Code is { } company && CanReadItems + ? await Items.SearchAsync(actor, company, text, null, cancellationToken) + : []; + + private void OpenItem(ItemRow row) => Navigation.NavigateTo(ItemScreens.RecordUrl(row.Id)); + + private void SetKind(string? value) => Change(() => P.Kind = Enum.Parse(value!)); + + private void SetAddressKind(PartyAddress address, string? value) => Change(() => address.Kind = Enum.Parse(value!)); + + private void SetDelivery(PartySalesTerms terms, string? value) => Change(() => terms.SendDocuments = Enum.Parse(value!)); + + private Task SetSubjectAsync(string? value) + { + Change(() => + { + P.SubjectType = Enum.Parse(value!); + // A foreign subject lives abroad: the country is chosen again. + if (P.SubjectType is SubjectType.EuCompany or SubjectType.NonEuCompany && P.CountryCode == "IT") + { + P.CountryCode = string.Empty; + } + else if (P.SubjectType is SubjectType.Company or SubjectType.PublicAdministration or SubjectType.FlatRate or SubjectType.Person && P.CountryCode.Length == 0) + { + P.CountryCode = "IT"; + } + }); + return Task.CompletedTask; + } + + private async Task SetPostalCodeAsync(string? value) + { + Change(() => P.PostalCode = value); + _places = []; + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || P.CountryCode != "IT" + || !await AutoFill.IsOnAsync(company, AutoFillService.PostalCode)) + { + return; + } + + var places = await AutoFill.PlacesByPostalCodeAsync(actor, company, value); + if (places.Count == 1) + { + PickPlace(places[0]); + } + else if (!places.Any(p => string.Equals(p.Name, P.City, StringComparison.CurrentCultureIgnoreCase))) + { + _places = places; + } + } + + private async Task SetCityAsync(string? value) + { + Change(() => P.City = value); + _places = []; + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || P.CountryCode != "IT" + || !await AutoFill.IsOnAsync(company, AutoFillService.PostalCode)) + { + return; + } + + var exact = (await AutoFill.PlacesByNameAsync(actor, company, value)) + .Where(p => string.Equals(p.Name, value?.Trim(), StringComparison.CurrentCultureIgnoreCase)).ToList(); + if (exact.Count == 1) + { + P.Province = exact[0].ProvinceCode; + // A single postal code is filled; a city with many keeps what was typed. + if (string.IsNullOrWhiteSpace(P.PostalCode) && exact[0].PostalCode is { } code && code.All(char.IsAsciiDigit)) + { + P.PostalCode = code; + } + } + } + + private void PickPlace(PlaceSuggestion place) + { + P.City = place.Name; + P.Province = place.ProvinceCode; + _places = []; + MarkModified(); + } + + private async Task SetIbanAsync(PartyBankAccount account, string? value) + { + Change(() => account.Iban = value ?? string.Empty); + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || !await AutoFill.IsOnAsync(company, AutoFillService.BankFromIban)) + { + return; + } + + if (await AutoFill.BankFromIbanAsync(actor, company, value) is { } bank) + { + account.BankCode = bank.BankCode; + account.BranchCode = bank.BranchCode; + account.BankName ??= bank.Name; + account.Bic ??= bank.Bic; + } + } + + private async Task ComputeTaxCodeAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || Record is null) + { + return; + } + + var place = _birthPlace?.Trim().ToUpperInvariant(); + if (place is { Length: > 0 } && !(place.Length == 4 && char.IsAsciiLetter(place[0]) && place[1..].All(char.IsAsciiDigit))) + { + // A name: the municipality with exactly that name. + place = (await AutoFill.PlacesByNameAsync(actor, company, _birthPlace)) + .FirstOrDefault(p => string.Equals(p.Name, _birthPlace?.Trim(), StringComparison.CurrentCultureIgnoreCase))?.MunicipalityCode; + } + + string? code = null; + if (_birthDate is { } date && Enum.TryParse(_sex, out var sex) && place is { Length: > 0 }) + { + code = await AutoFill.PersonalTaxCodeAsync(company, new PersonalTaxCodeData(P.LastName ?? string.Empty, P.FirstName ?? string.Empty, date, sex, place)); + } + + if (code is null) + { + Toasts.Show(ToastKind.Warning, T["Parties.Actions.TaxCodeMissing"]); + return; + } + + Change(() => P.TaxCode = code); + Toasts.Show(ToastKind.Success, T["Parties.Actions.TaxCodeDone"], code); + } + + private string? FieldLabel(string field) + { + var key = "Parties.Fields." + field.Split('.')[^1]; + return T.Contains(key) ? T[key] : null; + } +} 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/CompanyProfilePage.razor b/src/Khaemhat.Web/Components/Pages/Tables/CompanyProfilePage.razor new file mode 100644 index 0000000..ef85522 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Tables/CompanyProfilePage.razor @@ -0,0 +1,173 @@ +@page "/tabelle/profilo-azienda" +@attribute [Authorize] +@using Khaemhat.Application.Security +@using Khaemhat.Application.Tables +@using Khaemhat.Core.Common +@using Khaemhat.Core.Tables +@using Khaemhat.Web.Tables +@using Khaemhat.Web.Components.Tables +@inject ShellSession Session +@inject CompanyProfileService Profiles +@inject TableService Tables +@inject CompanyFiscalContext Fiscal +@inject ToastService Toasts + +@* The company profile (SPEC §11.1, mockup 075): company data, tax and e-invoice, default bank, print, fiscal year and + VAT, transmitter and intermediary. The country of the profile picks the fiscal pack of the company. *@ + + + +
+
+
@T["Shell.Menu.CompanyTables"] / @T["CompanyTables.Profile.Title"]
+

@(_profile?.LegalName is { Length: > 0 } name ? name : T["CompanyTables.Profile.Title"])

+
@T["CompanyTables.Profile.Hint"]
+
+
+ @if (_modified) + { + @T["CompanyTables.Modified"] + } +
+ + +
+
+ + @if (_profile is not null) + { +
+ + + @foreach (var group in ProfileLayout.Tabs.First(t => t.Id == _tab).Groups) + { + + @foreach (var field in group.Fields) + { + + } + + } + + @if (_tab == "esercizi") + { +

@T["CompanyTables.Profile.YearsHint"] @T["CompanyTables.FiscalYears.Title"]

+ } + @if (_tab == "stampa") + { +

@T["CompanyTables.Profile.LogoHint"]

+ } +
+ } +
+ +@code { + private readonly KhValidation _validation = new(); + private readonly TableOptions _options = new(); + private CompanyProfile? _profile; + private CompanyProfile? _saved; + private string _tab = ProfileLayout.Tabs[0].Id; + private bool _modified; + private bool _busy; + + private bool CanWrite => Session.Permissions.Allows(TableService.WritePermission); + + private IReadOnlyList TabItems => + [ + .. ProfileLayout.Tabs.Select(t => new KhTabItem(t.Id, t.Icon, T["CompanyTables.Profile.Tabs." + t.Id], + _validation.Messages.Count(m => ProfileLayout.TabOf(m.Field) == t) is > 0 and var n ? n : null)), + ]; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(TableService.ReadPermission)) + { + await _options.LoadAsync(Tables, Fiscal, ProfileLayout.Fields, actor, company); + Show(await Profiles.GetAsync(actor, company)); + } + } + + private void Show(CompanyProfile profile) + { + _profile = profile; + _saved = Copy(profile); + _modified = false; + _validation.Clear(); + } + + private Task UndoAsync() + { + if (_saved is { } saved) + { + Show(Copy(saved)); + } + + return Task.CompletedTask; + } + + private async Task SaveAsync() + { + if (_profile is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _busy = true; + _validation.Clear(); + try + { + var problems = Profiles.Validate(_profile); + if (problems.Count > 0) + { + Refuse(problems.Select(p => ((string?)p.Field, p.Code))); + return; + } + + Show(await Profiles.SaveAsync(actor, company, _profile)); + await _options.LoadAsync(Tables, Fiscal, ProfileLayout.Fields, actor, company); + Toasts.Show(ToastKind.Success, T["CompanyTables.Saved"], _profile.LegalName); + } + catch (ValidationFailedException ex) + { + Refuse(ex.Errors.Select(TableValues.SplitError)); + } + catch (ConcurrencyException) + { + Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], T["CompanyTables.Concurrency"]); + } + 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"]); + } + + // Show the tab of the first error, which may not be the one open. + if (_validation.Messages.Select(m => ProfileLayout.TabOf(m.Field)).FirstOrDefault(t => t is not null) is { } tab + && !_validation.Messages.Any(m => ProfileLayout.TabOf(m.Field)?.Id == _tab)) + { + _tab = tab.Id; + } + + Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], T["CompanyTables.FixFields"]); + } + + private static CompanyProfile Copy(CompanyProfile profile) + { + var copy = new CompanyProfile(); + foreach (var property in typeof(CompanyProfile).GetProperties().Where(p => p.CanRead && p.CanWrite)) + { + property.SetValue(copy, property.GetValue(profile)); + } + + return copy; + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Tables/ExchangeRatesPage.razor b/src/Khaemhat.Web/Components/Pages/Tables/ExchangeRatesPage.razor new file mode 100644 index 0000000..14d08bc --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Tables/ExchangeRatesPage.razor @@ -0,0 +1,129 @@ +@page "/tabelle/cambi" +@attribute [Authorize] +@using Khaemhat.Application.Security +@using Khaemhat.Application.Tables +@using Khaemhat.Core.Tables +@using Khaemhat.Web.Tables +@inject ShellSession Session +@inject ExchangeRateService Rates +@inject TableService Tables +@inject ToastService Toasts +@inject TimeProvider Clock + +@* Exchange rates (SPEC §11.1): the reference rates of the European Central Bank, read every working day by the system + task "Cambi di riferimento BCE", and the rates typed by hand, which the task never overwrites. *@ + + + +
+
+
@T["Shell.Menu.CompanyTables"] / @T["CompanyTables.Rates.Title"]
+

@T["CompanyTables.Rates.Title"]

+
@T["CompanyTables.Rates.Hint"]
+
+
+ +
+ + + @if (CanWrite) + { + + + + + + +
+ + @T["CompanyTables.Rates.ManualHint"] +
+
+ } +
+
+ +@code { + private readonly KhValidation _validation = new(); + private KhRadar? _radar; + private IReadOnlyList> _currencies = []; + private string? _currency; + private DateOnly? _date; + private decimal? _rate; + private bool _busy; + + private bool CanWrite => Session.Permissions.Allows(TableService.WritePermission); + + private IReadOnlyList> Columns => + [ + new("currency", T["CompanyTables.Fields.CurrencyCode"], r => r.CurrencyCode) { Kind = KhColumnKind.Code, Width = "90px" }, + new("date", T["CompanyTables.Fields.RateDate"], r => r.RateDate) { Kind = KhColumnKind.Date, Width = "120px" }, + new("rate", T["CompanyTables.Fields.Rate"], r => r.Rate) { Kind = KhColumnKind.Number, Decimals = 6, Width = "140px" }, + new("source", T["CompanyTables.Fields.Source"], r => T["CompanyTables.Values.Source." + r.Source]) { Sortable = false }, + ]; + + private IReadOnlyList QuickFilters => + [ + new("source", T["CompanyTables.Fields.Source"], + [ + new(string.Empty, T["CompanyTables.Filter.All"]), new(ExchangeRateService.EcbSource, T["CompanyTables.Values.Source.ECB"]), + new(ExchangeRateService.ManualSource, T["CompanyTables.Values.Source.MANUAL"]), + ]), + ]; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + _date = DateOnly.FromDateTime(Clock.GetLocalNow().DateTime); + if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(TableService.ReadPermission)) + { + var currencies = await Tables.ActiveAsync(actor, company); + _currencies = [.. currencies.Where(c => c.Code != "EUR").Select(c => new KhOption(c.Code, c.Code + " · " + c.Description))]; + } + } + + private Task> ListAsync(ListQuery query, CancellationToken cancellationToken) => + Session.Actor is { } actor && Session.Company?.Code is { } company + ? Rates.ListAsync(actor, company, query, cancellationToken) + : Task.FromResult(new ListPage([], 0, new Dictionary())); + + private async Task SaveAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _validation.Clear(); + if (_currency is null || _date is null || _rate is not > 0) + { + _validation.Add(_currency is null ? "CurrencyCode" : _date is null ? "RateDate" : "Rate", T[ExchangeRateService.RateInvalid]); + return; + } + + _busy = true; + try + { + await Rates.SetManualAsync(actor, company, _currency, _date.Value, _rate.Value); + Toasts.Show(ToastKind.Success, T["CompanyTables.Saved"], _currency); + _rate = null; + if (_radar is not null) + { + await _radar.ReloadAsync(); + } + } + catch (ValidationFailedException ex) + { + foreach (var (field, code) in ex.Errors.Select(TableValues.SplitError)) + { + _validation.Add(field ?? "Rate", T.Contains(code) ? T[code] : T["CompanyTables.UnknownError"]); + } + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Tables/FiscalYearsPage.razor b/src/Khaemhat.Web/Components/Pages/Tables/FiscalYearsPage.razor new file mode 100644 index 0000000..72582f8 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Tables/FiscalYearsPage.razor @@ -0,0 +1,217 @@ +@page "/tabelle/esercizi" +@attribute [Authorize] +@using Khaemhat.Application.Security +@using Khaemhat.Application.Tables +@using Khaemhat.Core.Tables +@using Khaemhat.Web.Tables +@inject ShellSession Session +@inject FiscalYearService Years +@inject ToastService Toasts +@inject DialogService Dialogs +@inject TimeProvider Clock + +@* Fiscal years and periods (SPEC §11.1, mockup 052): the years with their state, the months of the chosen year with + the lock that stops new entries and documents on those dates. The VAT settlement (M7) marks a month as settled. *@ + + + +
+
+
@T["Shell.Menu.CompanyTables"] / @T["CompanyTables.FiscalYears.Title"]
+

@T["CompanyTables.FiscalYears.Heading"]

+
@T["CompanyTables.FiscalYears.Hint"]
+
+
+
+ +
+
+ +
+ + @if (_years.Count == 0) + { +

@T["CompanyTables.FiscalYears.None"]

+ } + else + { + + + + + + + + + + + + + @foreach (var view in _years) + { + var year = view.Year; + + + + + + + + + } + +
@T["CompanyTables.FiscalYears.Year"]@T["CompanyTables.FiscalYears.Start"]@T["CompanyTables.FiscalYears.End"]@T["CompanyTables.FiscalYears.State"]@T["CompanyTables.FiscalYears.LockedMonths"]@T["CompanyTables.FiscalYears.LastSettled"]
@year.Code@T.Date(year.StartDate)@T.Date(year.EndDate)@T[TableScreens.EnumKey(year.Status)]@view.Periods.Count(p => p.Status != FiscalPeriodStatus.Open) / @view.Periods.Count@(view.Periods.LastOrDefault(p => p.Status == FiscalPeriodStatus.Settled) is { } last ? MonthName(last) : "-")
+ } +
+ + @if (_selected is { } selected) + { + + + + + + + + + + + + + @foreach (var period in selected.Periods) + { + + + + + + + + } + +
@T["CompanyTables.FiscalYears.Period"]@T["CompanyTables.FiscalYears.From"]@T["CompanyTables.FiscalYears.To"]@T["CompanyTables.FiscalYears.State"]@T["CompanyTables.FiscalYears.Lock"]
@MonthName(period)@T.Date(period.StartDate)@T.Date(period.EndDate)@T[TableScreens.EnumKey(period.Status)] + @if (period.Status == FiscalPeriodStatus.Settled) + { + @T["CompanyTables.FiscalYears.SettledLock"] + } + else + { + var locked = period.Status == FiscalPeriodStatus.Locked; + + } +
+
+ } +
+
+ +@code { + private IReadOnlyList _years = []; + private FiscalYearView? _selected; + private Khaemhat.Core.Tax.VatPeriodicity _periodicity; + private bool _busy; + + /// The service of the company profile, for the VAT periodicity shown on the months. + [Inject] + private CompanyProfileService Profiles { get; set; } = default!; + + private bool CanWrite => Session.Permissions.Allows(TableService.WritePermission); + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + if (Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(TableService.ReadPermission)) + { + _periodicity = (await Profiles.GetAsync(actor, company)).VatPeriodicity; + await LoadAsync(actor, company); + } + } + + private async Task LoadAsync(Actor actor, string company) + { + var selected = _selected?.Year.Id; + _years = await Years.ListAsync(actor, company); + var today = DateOnly.FromDateTime(Clock.GetLocalNow().DateTime); + _selected = _years.FirstOrDefault(y => y.Year.Id == selected) + ?? _years.FirstOrDefault(y => y.Year.StartDate <= today && today <= y.Year.EndDate) + ?? _years.FirstOrDefault(); + } + + private async Task CreateAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _busy = true; + try + { + var created = await Years.CreateNextAsync(actor, company, DateOnly.FromDateTime(Clock.GetLocalNow().DateTime)); + _selected = created; + await LoadAsync(actor, company); + Toasts.Show(ToastKind.Success, T["CompanyTables.FiscalYears.Created"], created.Year.Code); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], string.Join(" ", ex.Errors.Select(e => T[TableValues.SplitError(e).Code]))); + } + finally + { + _busy = false; + } + } + + private async Task LockAsync(FiscalPeriod period, bool locked) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + if (!locked && !await Dialogs.ConfirmAsync(new ConfirmRequest(T["CompanyTables.FiscalYears.Unlock"], T.Format("CompanyTables.FiscalYears.UnlockText", MonthName(period)), + T["CompanyTables.FiscalYears.Unlock"], T["Common.Cancel"]))) + { + return; + } + + _busy = true; + try + { + await Years.SetLockedAsync(actor, company, period.Id, locked); + await LoadAsync(actor, company); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], string.Join(" ", ex.Errors.Select(e => T[TableValues.SplitError(e).Code]))); + } + finally + { + _busy = false; + } + } + + private string MonthName(FiscalPeriod period) + { + var text = period.StartDate.ToString("MMMM yyyy", T.Culture); + return char.ToUpper(text[0], T.Culture) + text[1..]; + } + + private static KhTone ToneOf(FiscalYearStatus status) => status switch + { + FiscalYearStatus.Open => KhTone.Ok, + FiscalYearStatus.Closing => KhTone.Warning, + _ => KhTone.Neutral, + }; + + private static KhTone ToneOf(FiscalPeriodStatus status) => status switch + { + FiscalPeriodStatus.Open => KhTone.Ok, + FiscalPeriodStatus.Settled => KhTone.Info, + _ => KhTone.Warning, + }; +} diff --git a/src/Khaemhat.Web/Components/Pages/Tables/TablePage.razor b/src/Khaemhat.Web/Components/Pages/Tables/TablePage.razor new file mode 100644 index 0000000..22f62ed --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Tables/TablePage.razor @@ -0,0 +1,31 @@ +@page "/tabelle/{Slug}" +@attribute [Authorize] +@using Khaemhat.Web.Tables +@using Khaemhat.Web.Components.Tables + +@* A company table by address (/tabelle/codici-iva): the generic editor of its entity. *@ + + @if (TableScreens.Find(Slug) is { } screen) + { + + } + else + { + +
+ +

@T["Pages.NotFound.Title"]

+ @T["Shell.Menu.CompanyTables"] +
+ } +
+ +@code { + /// The last part of the address. + [Parameter] + public string? Slug { get; set; } + + private static Type EditorOf(TableScreen screen) => typeof(KhTableEditor<>).MakeGenericType(screen.Entity); + + private static Dictionary ParametersOf(TableScreen screen) => new() { ["Screen"] = screen }; +} diff --git a/src/Khaemhat.Web/Components/Pages/Tables/TablesGuard.razor b/src/Khaemhat.Web/Components/Pages/Tables/TablesGuard.razor new file mode 100644 index 0000000..f8d1d98 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Tables/TablesGuard.razor @@ -0,0 +1,43 @@ +@inject ShellSession Session + +@* What every page of the company tables checks first: an open company and the permission to read its settings. *@ +@if (!_loaded) +{ +

@T["Common.Loading"]

+} +else if (Session.Company is null) +{ +
+ +

@T["CompanyTables.NoCompany.Title"]

+

@T["CompanyTables.NoCompany.Lead"]

+
+} +else if (!Session.Permissions.Allows(Khaemhat.Application.Tables.TableService.ReadPermission)) +{ +
+ +

@T["Pages.AccessDenied.Title"]

+

@T["Pages.AccessDenied.Lead"]

+ @T["Common.BackHome"] +
+} +else +{ + @ChildContent +} + +@code { + private bool _loaded; + + /// The page. + [Parameter] + public RenderFragment? ChildContent { get; set; } + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + _loaded = true; + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Tables/TablesIndex.razor b/src/Khaemhat.Web/Components/Pages/Tables/TablesIndex.razor new file mode 100644 index 0000000..3623d55 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Tables/TablesIndex.razor @@ -0,0 +1,47 @@ +@page "/tabelle" +@attribute [Authorize] +@using Khaemhat.Web.Tables + +@* The company tables (SPEC §11.1): the profile, the fiscal years and the exchange rates, then every table by group. *@ + + + +
+
+

@T["Shell.Menu.CompanyTables"]

+
@T["CompanyTables.Index.Subtitle"]
+
+
+
+ +
+ @foreach (var (href, icon, title, hint) in Pages) + { + @T[title]@T[hint] + } +
+
+ @foreach (var group in TableScreens.All.GroupBy(s => s.Group)) + { + +
+ @foreach (var screen in group) + { + @T[screen.TitleKey]@T[screen.HintKey] + } +
+
+ } +
+
+ +@code { + /// The pages of the company that are not tables. + public static readonly IReadOnlyList<(string Href, string Icon, string Title, string Hint)> Pages = + [ + ("/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/Tables/KhPaymentTermLines.razor b/src/Khaemhat.Web/Components/Tables/KhPaymentTermLines.razor new file mode 100644 index 0000000..3eb5d36 --- /dev/null +++ b/src/Khaemhat.Web/Components/Tables/KhPaymentTermLines.razor @@ -0,0 +1,145 @@ +@using System.Globalization +@using Khaemhat.Application.Security +@using Khaemhat.Application.Tables +@using Khaemhat.Core.Tables +@inject ShellSession Session +@inject PaymentTermService Terms +@inject ToastService Toasts + +@* The installments of a payment term (SPEC §11.1): days, end of month, fixed day, share. They are saved together, + because only the whole set has to add up to 100%. *@ + + + @if (!ReadOnly) + { + + + } + + + + + + + + + + + + + + + @for (var i = 0; i < _lines.Count; i++) + { + var line = _lines[i]; + var number = i + 1; + + + + + + + + + } + + + + + + + + +
#@T["CompanyTables.Lines.Days"]@T["CompanyTables.Lines.EndOfMonth"]@T["CompanyTables.Lines.FixedDay"]@T["CompanyTables.Lines.Percent"]
@number + + + + + + + + + @if (!ReadOnly) + { + + } +
@T["CompanyTables.Lines.Total"]@ItalianNumber.Format(Total, 2, Italian)
+ @if (_error is not null) + { +

@_error

+ } +
+
+ +@code { + private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT"); + + private List _lines = []; + private bool _modified; + private bool _busy; + private string? _error; + + /// The payment term. + [Parameter, EditorRequired] + public long PaymentTermId { get; set; } + + /// Whether the installments can only be read. + [Parameter] + public bool ReadOnly { get; set; } + + private decimal Total => _lines.Sum(l => l.Percent); + + /// + protected override async Task OnInitializedAsync() + { + if (Session.Actor is { } actor && Session.Company?.Code is { } company) + { + _lines = [.. await Terms.LinesAsync(actor, company, PaymentTermId)]; + } + } + + private void Set(Action change) + { + change(); + _modified = true; + _error = null; + } + + private void Add() => Set(() => _lines.Add(new PaymentTermLine { Days = _lines.Count == 0 ? 30 : _lines[^1].Days + 30, EndOfMonth = _lines.LastOrDefault()?.EndOfMonth ?? false, + Percent = Math.Max(0m, 100m - Total) })); + + private void Remove(PaymentTermLine line) => Set(() => _lines.Remove(line)); + + private async Task SaveAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _busy = true; + try + { + _lines = [.. await Terms.SaveLinesAsync(actor, company, PaymentTermId, _lines)]; + _modified = false; + Toasts.Show(ToastKind.Success, T["CompanyTables.Lines.Saved"]); + } + catch (ValidationFailedException ex) + { + _error = string.Join(" ", ex.Errors.Select(e => T[e[(e.IndexOf(':', StringComparison.Ordinal) + 1)..]])); + } + finally + { + _busy = false; + } + } + + private static int? Integer(object? value) => + int.TryParse(value?.ToString(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var number) ? number : null; + + private static decimal? Decimal(object? value) => ItalianNumber.TryParse(value?.ToString(), out var number) ? number : null; +} diff --git a/src/Khaemhat.Web/Components/Tables/KhRowField.razor b/src/Khaemhat.Web/Components/Tables/KhRowField.razor new file mode 100644 index 0000000..e99853c --- /dev/null +++ b/src/Khaemhat.Web/Components/Tables/KhRowField.razor @@ -0,0 +1,72 @@ +@using System.Reflection +@using Khaemhat.Web.Tables + +@* One field of a company table or of the company profile, edited as its TableField says. *@ +@switch (Field.Kind) +{ + case TableFieldKind.Number: + + break; + case TableFieldKind.Bool: + + break; + case TableFieldKind.Date: + + break; + case TableFieldKind.Choice or TableFieldKind.Lookup or TableFieldKind.CodeList: + + break; + default: + if (Field.Rows > 1) + { + + } + else + { + + } + + break; +} + +@code { + /// The row. + [Parameter, EditorRequired] + public object Row { get; set; } = default!; + + /// The field. + [Parameter, EditorRequired] + public TableField Field { get; set; } = default!; + + /// The choices of the page. + [Parameter, EditorRequired] + public TableOptions Options { get; set; } = default!; + + /// Whether the page cannot be changed. + [Parameter] + public bool ReadOnly { get; set; } + + /// Called after every change. + [Parameter] + public EventCallback OnChanged { get; set; } + + private PropertyInfo Property => TableValues.PropertyOf(Row.GetType(), Field); + + private string Label => T[Field.LabelKey]; + + private bool IsReadOnly => ReadOnly || Field.ReadOnly; + + private Task ChangeAsync(Action change) + { + change(); + return OnChanged.InvokeAsync(); + } +} diff --git a/src/Khaemhat.Web/Components/Tables/KhTableEditor.razor b/src/Khaemhat.Web/Components/Tables/KhTableEditor.razor new file mode 100644 index 0000000..338de64 --- /dev/null +++ b/src/Khaemhat.Web/Components/Tables/KhTableEditor.razor @@ -0,0 +1,451 @@ +@typeparam TRow where TRow : Khaemhat.Core.Tables.CodedEntity, new() +@using System.Reflection +@using Khaemhat.Application.Seeding +@using Khaemhat.Application.Security +@using Khaemhat.Application.Tables +@using Khaemhat.Core.Common +@using Khaemhat.Core.Tables +@using Khaemhat.Web.Tables +@inject ShellSession Session +@inject TableService Tables +@inject CompanyFiscalContext Fiscal +@inject SeedRunner Seeds +@inject ToastService Toasts +@inject DialogService Dialogs +@inject IJSRuntime JS + +@* A company table (SPEC §11.1, mockup 076): the rows in a radar with search and the enabled/disabled filter, the + detail of the current row below, the commands to add, save, undo, delete, export and import CSV and to add the + rows of the base data that are missing. Every table is described by a TableScreen; the rules are the service's. *@ + + +
+
+
@T["Shell.Menu.CompanyTables"] / @T[Screen.TitleKey]
+

@T[Screen.TitleKey]

+
@T[Screen.HintKey]
+
+
+ @if (_modified) + { + @T["CompanyTables.Modified"] + } +
+ + + +
+ + + @if (_row is not null) + { + + + + + + @foreach (var field in Screen.Fields) + { + + } + + @if (_warnings.Count > 0) + { +
    + @foreach (var warning in _warnings) + { +
  • @warning
  • + } +
+ } +
+ + @if (_row is PaymentTerm { Id: > 0 } term) + { + + } + } +
+ + + +

@T["CompanyTables.Import.Text"]

+

@T.Format("CompanyTables.Import.Columns", string.Join(", ", Definition.CsvColumns.Select(c => c.Header)))

+ + @if (_import is { } result) + { + @if (result.Succeeded) + { +

@T.Format("CompanyTables.Import.Done", result.Inserted, result.Updated)

+ } + else + { +

@T.Format("CompanyTables.Import.Refused", result.Errors.Count)

+
    + @foreach (var error in result.Errors.Take(50)) + { +
  • @T.Format("CompanyTables.Import.Error", error.Row, error.Field ?? "-", ErrorText(error.Code))
  • + } +
+ } + } +
+
+ +
+
+ +@code { + private const long MaxImportBytes = 20L * 1024 * 1024; + + private readonly KhValidation _validation = new(); + private readonly TableOptions _options = new(); + private KhRadar? _radar; + private TRow? _row; + private TRow? _saved; + private bool _modified; + private bool _busy; + private bool _importOpen; + private TableImportResult? _import; + private List _warnings = []; + private IReadOnlyList>? _columns; + + /// The table. + [Parameter, EditorRequired] + public TableScreen Screen { get; set; } = default!; + + private static string? DisabledClass(TRow row) => row.Disabled ? "muted" : null; + + private TableDefinition Definition => Tables.Catalog.Find(Screen.Key)!; + + private string? Company => Session.Company?.Code; + + private bool CanWrite => Session.Permissions.Allows(TableService.WritePermission); + + private string DetailTitle => _row is { Id: > 0 } row ? T.Format("CompanyTables.Detail", row.Code) : T["CompanyTables.NewRow"]; + + private IReadOnlyList EnabledOnly => [new("disabled", ListFilterOperator.Equals, ["false"])]; + + private IReadOnlyList QuickFilters => + [ + new("disabled", T["CompanyTables.Filter.State"], + [ + new(string.Empty, T["CompanyTables.Filter.All"]), new("false", T["CompanyTables.Filter.Enabled"]), new("true", T["CompanyTables.Filter.Disabled"]), + ]), + ]; + + private IReadOnlyList> Columns => _columns ??= + [ + new("code", T["CompanyTables.Fields.Code"], r => r.Code) { Kind = KhColumnKind.Code, Width = "110px" }, + new("description", T["CompanyTables.Fields.Description"], r => r.Description), + .. Screen.Fields.Where(f => f.InGrid).Select(Column), + new("disabled", T["CompanyTables.Fields.Disabled"], r => r.Disabled) { Kind = KhColumnKind.Bool, Width = "90px" }, + ]; + + private IReadOnlyList ToolbarItems => + [ + new("new", "plus", T["CompanyTables.New"]) { OnClick = NewAsync, Disabled = !CanWrite, Primary = true, Shortcut = "Alt+N" }, + new("save", "save", T["Common.Save"]) { OnClick = SaveAsync, Disabled = !CanWrite || !_modified || _busy, Shortcut = "Ctrl+S" }, + new("undo", "undo", T["CompanyTables.Undo"]) { OnClick = UndoAsync, Disabled = !_modified }, + new("delete", "trash", T["CompanyTables.Delete"]) { OnClick = DeleteAsync, Disabled = !CanWrite || _row is not { Id: > 0 } || _busy, Danger = true }, + new("export", "download", T["CompanyTables.Export"]) { Kind = ToolbarKind.Action, OnClick = ExportAsync }, + new("import", "upload", T["CompanyTables.Import.Title"]) { Kind = ToolbarKind.Action, OnClick = OpenImport, Disabled = !CanWrite }, + new("base", "refresh", T["CompanyTables.BaseData"]) { Kind = ToolbarKind.Action, OnClick = BaseDataAsync, Disabled = !CanWrite || _busy }, + ]; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + if (Company is { } company) + { + await LoadOptionsAsync(company); + } + } + + private KhColumn Column(TableField field) + { + var property = TableValues.PropertyOf(typeof(TRow), field); + return field.Kind switch + { + TableFieldKind.Number => new(field.Property, T[field.LabelKey], r => TableValues.GetNumber(r, property)) + { + Kind = KhColumnKind.Number, Decimals = field.Decimals, Width = field.Width, Sortable = false, + }, + TableFieldKind.Bool => new(field.Property, T[field.LabelKey], r => property.GetValue(r)) { Kind = KhColumnKind.Bool, Width = field.Width, Sortable = false }, + TableFieldKind.Date => new(field.Property, T[field.LabelKey], r => property.GetValue(r)) { Kind = KhColumnKind.Date, Width = field.Width, Sortable = false }, + TableFieldKind.Choice => new(field.Property, T[field.LabelKey], r => property.GetValue(r) is Enum v ? T[TableScreens.EnumKey(v)] : null) + { + Width = field.Width, Sortable = false, + }, + TableFieldKind.Lookup => new(field.Property, T[field.LabelKey], r => _options.CodeOf(field, TableValues.GetText(r, property))) { Width = field.Width, Sortable = false }, + _ => new(field.Property, T[field.LabelKey], r => TableValues.GetText(r, property)) + { + Kind = field.Kind is TableFieldKind.Code or TableFieldKind.CodeList ? KhColumnKind.Code : KhColumnKind.Text, Width = field.Width, Sortable = false, + }, + }; + } + + private async Task LoadOptionsAsync(string company) + { + if (Session.Actor is { } actor) + { + await _options.LoadAsync(Tables, Fiscal, Screen.Fields, actor, company); + _columns = null; + } + } + + private Task> ListAsync(ListQuery query, CancellationToken cancellationToken) => + Session.Actor is { } actor && Company is { } company + ? Tables.ListAsync(actor, company, query, cancellationToken) + : Task.FromResult(new ListPage([], 0, new Dictionary())); + + private async Task OpenAsync(TRow row) + { + if (_row?.Id == row.Id || !await LeaveAsync()) + { + return; + } + + Show(row); + } + + private void Show(TRow row) + { + _row = Copy(row); + _saved = row.Id > 0 ? Copy(row) : null; + _modified = false; + _warnings = []; + _validation.Clear(); + } + + // Asks before throwing away what was typed. + private async Task LeaveAsync() => + !_modified || await Dialogs.ConfirmAsync(new ConfirmRequest(T["CompanyTables.Leave.Title"], T["CompanyTables.Leave.Text"], T["CompanyTables.Leave.Confirm"], + T["Common.Cancel"], Danger: true)); + + private async Task NewAsync() + { + if (await LeaveAsync()) + { + Show(new TRow()); + _modified = true; + } + } + + private Task UndoAsync() + { + if (_saved is { } saved) + { + Show(saved); + } + else + { + _row = null; + _modified = false; + _validation.Clear(); + } + + return Task.CompletedTask; + } + + private void Change(Action change) + { + change(); + _modified = true; + } + + private async Task SaveAsync() + { + if (_row is null || Session.Actor is not { } actor || Company is not { } company) + { + return; + } + + _busy = true; + _validation.Clear(); + try + { + var problems = await Tables.ValidateAsync(actor, company, _row); + _warnings = [.. problems.Where(p => p.IsWarning).Select(p => T[p.Code])]; + var errors = problems.Where(p => !p.IsWarning).ToList(); + if (errors.Count > 0) + { + foreach (var problem in errors) + { + _validation.Add(problem.Field, ErrorText(problem.Code)); + } + + Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], T["CompanyTables.FixFields"]); + return; + } + + var saved = await Tables.SaveAsync(actor, company, _row); + var warnings = _warnings; + Show(saved); + _warnings = warnings; + Toasts.Show(ToastKind.Success, T["CompanyTables.Saved"], saved.Code); + await RefreshAsync(company); + } + catch (ValidationFailedException ex) + { + foreach (var (field, code) in ex.Errors.Select(TableValues.SplitError)) + { + _validation.Add(field, ErrorText(code)); + } + + Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], T["CompanyTables.FixFields"]); + } + catch (ConcurrencyException) + { + Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], T["CompanyTables.Concurrency"]); + } + finally + { + _busy = false; + } + } + + private async Task DeleteAsync() + { + if (_row is not { Id: > 0 } row || Session.Actor is not { } actor || Company is not { } company) + { + return; + } + + if (!await Dialogs.ConfirmAsync(new ConfirmRequest(T["CompanyTables.Delete"], T.Format("CompanyTables.DeleteText", row.Code), T["CompanyTables.Delete"], + T["Common.Cancel"], Danger: true))) + { + return; + } + + _busy = true; + try + { + var outcome = await Tables.DeleteAsync(actor, company, row.Id); + Toasts.Show(ToastKind.Success, outcome == TableDeleteOutcome.Deleted ? T["CompanyTables.Deleted"] : T["CompanyTables.DisabledInstead"], row.Code); + _row = null; + _saved = null; + _modified = false; + await RefreshAsync(company); + } + catch (KeyNotFoundException) + { + Toasts.Show(ToastKind.Error, T["tables.not-found"]); + } + finally + { + _busy = false; + } + } + + private async Task RefreshAsync(string company) + { + if (Screen.Fields.Any(f => f.Lookup == typeof(TRow))) + { + await LoadOptionsAsync(company); + } + + if (_radar is not null) + { + await _radar.ReloadAsync(); + } + } + + private async Task ExportAsync() + { + if (Session.Actor is not { } actor || Company is not { } company) + { + return; + } + + using var buffer = new MemoryStream(); + var count = await Tables.ExportCsvAsync(actor, company, buffer); + buffer.Position = 0; + using var stream = new DotNetStreamReference(buffer, leaveOpen: true); + await JS.InvokeVoidAsync("khaemhat.download", Screen.Slug + ".csv", "text/csv", stream); + Toasts.Show(ToastKind.Success, T.Format("Ui.Grid.Exported", T.Number(count))); + } + + private Task OpenImport() + { + _import = null; + _importOpen = true; + return Task.CompletedTask; + } + + private void CloseImport() => _importOpen = false; + + private async Task ImportAsync(InputFileChangeEventArgs e) + { + if (Session.Actor is not { } actor || Company is not { } company) + { + return; + } + + if (e.File.Size > MaxImportBytes) + { + Toasts.Show(ToastKind.Error, e.File.Name, T["CompanyTables.Import.TooLarge"]); + return; + } + + _busy = true; + try + { + await using var source = e.File.OpenReadStream(MaxImportBytes); + using var content = new MemoryStream(); + await source.CopyToAsync(content); + content.Position = 0; + _import = await Tables.ImportCsvAsync(actor, company, content); + if (_import.Succeeded) + { + await RefreshAsync(company); + } + } + finally + { + _busy = false; + } + } + + private async Task BaseDataAsync() + { + if (Session.Actor is not { } actor || Company is not { } company) + { + return; + } + + _busy = true; + try + { + var report = await Seeds.UpdateBaseAsync(actor, company); + Toasts.Show(ToastKind.Success, T["CompanyTables.BaseData"], T.Format("CompanyTables.BaseDataDone", report.Total, report.DataVersion)); + await LoadOptionsAsync(company); + await RefreshAsync(company); + } + finally + { + _busy = false; + } + } + + private string ErrorText(string code) => T.Contains(code) ? T[code] : T["CompanyTables.UnknownError"]; + + private static TRow Copy(TRow row) + { + var copy = new TRow(); + foreach (var property in typeof(TRow).GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.CanRead && p.CanWrite)) + { + property.SetValue(copy, property.GetValue(row)); + } + + return copy; + } +} 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. *@ -