feat: postal codes from GeoNames for the ISTAT municipalities (#45)

The municipalities now come with their postal codes, so the lookup from
postal code works on a new company without loading anything. GeoNames
(CC BY 4.0) lists places rather than municipalities: a postal code goes
to a municipality only when the name and the province abbreviation match
exactly one of them (the name alone within Sardinia, whose abbreviations
changed), which covers 7,750 of 7,894 municipalities; the rest are mostly
renamed or merged ones that users complete by hand.

tools/Khaemhat.PlacesTool rebuilds both lists from the ISTAT sheet and
the GeoNames file, framework only, so the yearly update is repeatable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-12 09:16:07 +01:00
1 parent 321aae7e81
commit a9eda510f2
15 files changed
+8192 -7936

No files matched your search

+2 -1
View File
@@ -32,7 +32,8 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`.
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`). I CAP non sono inclusi: si completano nella tabella *Comuni*.
(`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
+15
View File
@@ -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
+2 -1
View File
@@ -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/<Modulo>/, 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
+2 -2
View File
@@ -5,8 +5,8 @@
**Ultimo aggiornamento:** 2026-11-12
**Milestone corrente:** M4 — Tabelle, anagrafiche, articoli (issue #37-#46), ramo `feat/37-tabelle-anagrafiche`.
Fatti: pacchetto fiscale (#37), validatori e VIES (#40), tabelle azienda, profilo, esercizi e cambi con le maschere
(#38, #39), dati di base e `scripts/seed.sh --base` (#45) con province e comuni ISTAT (ADR 0028; mancano CAP e
banche ABI/CAB, senza fonte con licenza compatibile), codici automatici e compilazione automatica (#43). ADR 0025-0028.
(#38, #39), dati di base e `scripts/seed.sh --base` (#45) con province e comuni ISTAT e CAP GeoNames (ADR 0028;
mancano le banche ABI/CAB, senza fonte con licenza compatibile), codici automatici e compilazione automatica (#43). ADR 0025-0028.
**Prossimo passo:** anagrafiche (#41) e articoli e listini (#42) con i dati di esempio, import/export guidato (#44),
chiusura M4 (#46). #35 (PNG ad alta risoluzione) resta
aperta e non blocca.
@@ -35,8 +35,8 @@ grandi (8.000 comuni, decine di migliaia di sportelli) che non sono nel reposito
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 sono nei dati di base dalla versione `IT 2026.3`; CAP e
banche restano fuori.
*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`.
@@ -1,4 +1,4 @@
# ADR 0028 - Province e comuni dall'elenco ISTAT nel pacchetto fiscale, CAP esclusi
# ADR 0028 - Province e comuni dall'elenco ISTAT e CAP da GeoNames nel pacchetto fiscale
- **Stato:** accettata
- **Data:** 2026-11-12
@@ -27,20 +27,26 @@ caricati dopo il via dell'utente. Il via è arrivato il 2026-11-12 per due fonti
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) è scritta in `ItalianPlaces.ListSource`, nella
wiki *Dati di base e di esempio* e in questo ADR.
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. I comuni arrivano con il campo CAP vuoto: l'utente lo
completa a mano o con l'**Importa CSV** della tabella, e la compilazione dal CAP usa quello che trova. Una fonte
di CAP con licenza compatibile (ad esempio l'elenco dei codici postali di GeoNames, CC BY 4.0) si valuta a parte,
con un nuovo via dell'utente al download.
5. **Banche ABI/CAB** restano fuori finché non c'è una fonte aperta con licenza chiara (ADR 0026, ADR 0027 punto 6).
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 e comuni: il calcolo del codice fiscale e la scelta del comune funzionano
senza caricare nulla. Le aziende esistenti li ricevono al primo avvio con la versione `IT 2026.3`, o con
*Aggiorna tabelle di base*.
- 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
+8 -6
View File
@@ -40,7 +40,7 @@ Il pacchetto italiano fa parte del pacchetto fiscale Italia (vedi [Fiscalità it
| Pacchetto | Contenuto |
|---|---|
| **Paesi e comuni** | paesi ISO, province, comuni con codice catastale e codice ISTAT (CAP da completare) |
| **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 |
@@ -67,14 +67,16 @@ 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.
> Fonte: ISTAT, *Codici statistici delle unità amministrative territoriali*, licenza
> 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).
**I CAP non sono inclusi**: l'ISTAT non li pubblica e non c'è ancora una fonte con una licenza che permetta di
distribuirli. Si completano a mano nella tabella *Comuni* o con l'**Importa CSV** (colonne `Code` e `PostalCodes`;
più CAP separati da virgola, oppure un intervallo come `10121-10156`). La compilazione dal CAP propone i comuni che
hanno il CAP scritto. Anche le **banche ABI/CAB** non sono ancora incluse: banca e BIC dall'IBAN vengono da un conto
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
+1 -1
View File
@@ -89,7 +89,7 @@ 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** | 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 e comuni arrivano con i dati di base dall'elenco ISTAT; i CAP si completano a mano o con l'Importa CSV, vedi [Dati di base e di esempio](Dati-di-base-e-esempio) |
| **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) |
File diff suppressed because it is too large. Load diff
+6 -4
View File
@@ -5,13 +5,15 @@ namespace Khaemhat.Fiscal.Italy;
/// <summary>
/// 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. The
/// list has no postal codes. The files are read once, the first time they are needed.
/// 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
/// <c>tools/Khaemhat.PlacesTool</c> and read once, the first time they are needed.
/// </summary>
public sealed class ItalianPlaces : IPlaceDirectory
{
/// <summary>The source of the embedded files.</summary>
public const string ListSource = "ISTAT, Codici statistici delle unità amministrative territoriali, 26/02/2026 (CC BY 4.0)";
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<IReadOnlyList<ProvinceTemplate>> _provinces = new(ReadProvinces);
private readonly Lazy<IReadOnlyList<MunicipalityTemplate>> _municipalities = new(ReadMunicipalities);
@@ -29,7 +31,7 @@ public sealed class ItalianPlaces : IPlaceDirectory
[.. Read("province.csv").Select(l => new ProvinceTemplate(l[0], l[1], l[2]))];
private static IReadOnlyList<MunicipalityTemplate> ReadMunicipalities() =>
[.. Read("comuni.csv").Select(l => new MunicipalityTemplate(l[0], l[1], l[2], l[3], l[4], null))];
[.. 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<IReadOnlyList<string>> Read(string file)
{
@@ -23,6 +23,7 @@ public sealed class DependencyRulesTests
["Khaemhat.Web"] = ["Khaemhat.Application", "Khaemhat.Data.Sqlite", "Khaemhat.Data.PostgreSql", "Khaemhat.Fiscal.Italy"],
["Khaemhat.LicenseTool"] = ["Khaemhat.Core", "Khaemhat.Infrastructure"],
["Khaemhat.DataModelTool"] = ["Khaemhat.Data"],
["Khaemhat.PlacesTool"] = [],
};
// The only packages, and where each may be referenced.
@@ -33,12 +33,26 @@ public sealed class ItalianPlacesTests
}
[TestMethod]
[DataRow("L219", "Torino", "TO", "Piemonte", "001272")]
[DataRow("H501", "Roma", "RM", "Lazio", "058091")]
[DataRow("A952", "Bolzano", "BZ", "Trentino-Alto Adige/Südtirol", "021008")]
public void Municipality_HasTheCadastralCodeOfTheTaxCode(string code, string name, string province, string region, string istat)
[DataRow("L219", "Torino", "TO", "Piemonte", "001272", "10100,10121-10156")]
[DataRow("A952", "Bolzano", "BZ", "Trentino-Alto Adige/Südtirol", "021008", "39100")]
[DataRow("B354", "Cagliari", "CA", "Sardegna", "118006", "09100,09121-09131,09134")]
[DataRow("I138", "Sanremo", "IM", "Liguria", "008055", null)]
public void Municipality_HasTheCadastralCodeOfTheTaxCode_AndThePostalCodesFound(string code, string name, string province, string region, string istat, string? postalCodes)
{
Assert.AreEqual(new MunicipalityTemplate(code, name, province, region, istat, null), Places.Municipalities.Single(m => m.Code == code));
Assert.AreEqual(new MunicipalityTemplate(code, name, province, region, istat, postalCodes), Places.Municipalities.Single(m => m.Code == code));
}
[TestMethod]
public void PostalCodes_CoverAlmostEveryMunicipality_AndAreFiveDigitsOrRanges()
{
var withCodes = Places.Municipalities.Where(m => m.PostalCodes is not null).ToList();
Assert.IsGreaterThan(7700, withCodes.Count);
Assert.Contains("GeoNames", Places.Source);
foreach (var municipality in withCodes)
{
Assert.MatchesRegex(@"^[0-9]{5}(-[0-9]{5})?(,[0-9]{5}(-[0-9]{5})?)*$", municipality.PostalCodes!, municipality.Code);
}
}
[TestMethod]
@@ -123,16 +123,15 @@ public sealed class CodeRulesTests
var tables = services.GetRequiredService<TableService>();
var autoFill = services.GetRequiredService<AutoFillService>();
// The base data brings every municipality of the ISTAT list, without postal codes: the users add them.
// The base data brings every municipality of the ISTAT list with the GeoNames postal codes; the few missing
// ones are written by the users.
var municipalities = await tables.ActiveAsync<Municipality>(Root, company);
Assert.HasCount(7894, municipalities);
Assert.IsEmpty(await autoFill.PlacesByPostalCodeAsync(Root, company, "10128"));
var turinRow = municipalities.Single(m => m.Code == "L219");
turinRow.PostalCodes = "10121-10156";
await tables.SaveAsync(Root, company, turinRow);
var pinerolo = municipalities.Single(m => m.Code == "G674");
pinerolo.PostalCodes = "10064";
await tables.SaveAsync(Root, company, pinerolo);
Assert.IsEmpty(await autoFill.PlacesByPostalCodeAsync(Root, company, "18038"));
var sanremo = municipalities.Single(m => m.Code == "I138");
sanremo.PostalCodes = "18038";
await tables.SaveAsync(Root, company, sanremo);
Assert.AreEqual("Sanremo", (await autoFill.PlacesByPostalCodeAsync(Root, company, "18038")).Single().Name);
var turin = (await autoFill.PlacesByPostalCodeAsync(Root, company, "10128")).Single();
Assert.AreEqual(new PlaceSuggestion("L219", "Torino", "TO", "Piemonte", "10128"), turin);
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<RootNamespace>Khaemhat.PlacesTool</RootNamespace>
<!-- Developer tool, never shipped (ADR 0010): rebuilds the ISTAT lists of Khaemhat.Fiscal.Italy (ADR 0028). -->
<IsPackable>false</IsPackable>
</PropertyGroup>
</Project>
+205
View File
@@ -0,0 +1,205 @@
// Khaemhat.PlacesTool: rebuilds Data/province.csv and Data/comuni.csv of Khaemhat.Fiscal.Italy (ADR 0028) from the
// ISTAT list of municipality codes (xlsx, CC BY 4.0) and, optionally, the GeoNames postal codes of Italy (IT.zip,
// CC BY 4.0). The downloads stay outside the repository; only the two files it writes are committed.
using System.Globalization;
using System.IO.Compression;
using System.Text;
using System.Xml.Linq;
const string Usage = """
Khaemhat.PlacesTool
--istat <Elenco-comuni-italiani.xlsx> [--postal <IT.zip>] --out <directory>
Writes province.csv and comuni.csv. Postal codes are matched to the municipalities by name and province
abbreviation (by name alone in Sardinia, whose abbreviations changed); hamlets are ignored.
""";
var options = new Dictionary<string, string>(StringComparer.Ordinal);
for (var i = 0; i + 1 < args.Length; i += 2)
{
options[args[i]] = args[i + 1];
}
if (!options.TryGetValue("--istat", out var istatPath) || !options.TryGetValue("--out", out var outDir))
{
Console.WriteLine(Usage);
return 1;
}
var sheet = ReadFirstSheet(istatPath);
var provinces = new SortedDictionary<string, (string Name, string Region)>(StringComparer.Ordinal);
var municipalities = new List<Place>();
foreach (var row in sheet.Skip(1).Where(r => r.Count > 20 && r[20].Trim().Length > 0))
{
var place = new Place(row[20].Trim().ToUpperInvariant(), row[6].Trim(), row[14].Trim(), row[10].Trim(), row[4].Trim());
if (place.Code.Length != 4 || place.Province.Length != 2 || place.Istat.Length != 6 || place.Name.Contains(';', StringComparison.Ordinal))
{
throw new InvalidDataException($"Unexpected row: {string.Join('|', row)}");
}
var province = (row[11].Trim(), place.Region);
if (provinces.TryGetValue(place.Province, out var known) && known != province)
{
throw new InvalidDataException($"Province {place.Province} has two names: {known} and {province}.");
}
provinces[place.Province] = province;
municipalities.Add(place);
}
if (municipalities.Select(m => m.Code).Distinct(StringComparer.Ordinal).Count() != municipalities.Count)
{
throw new InvalidDataException("Duplicate cadastral codes.");
}
var postal = options.TryGetValue("--postal", out var postalPath) ? MatchPostalCodes(postalPath, municipalities) : [];
Directory.CreateDirectory(outDir);
var provinceText = new StringBuilder("sigla;denominazione;regione\n");
foreach (var (code, (name, region)) in provinces)
{
provinceText.Append(CultureInfo.InvariantCulture, $"{code};{name};{region}\n");
}
var municipalityText = new StringBuilder("codice_catastale;denominazione;sigla;regione;codice_istat;cap\n");
foreach (var m in municipalities.OrderBy(m => m.Istat, StringComparer.Ordinal))
{
var codes = postal.TryGetValue(m.Code, out var set) ? Ranges(set) : string.Empty;
municipalityText.Append(CultureInfo.InvariantCulture, $"{m.Code};{m.Name};{m.Province};{m.Region};{m.Istat};{codes}\n");
}
await File.WriteAllTextAsync(Path.Combine(outDir, "province.csv"), provinceText.ToString(), new UTF8Encoding(false));
await File.WriteAllTextAsync(Path.Combine(outDir, "comuni.csv"), municipalityText.ToString(), new UTF8Encoding(false));
Console.WriteLine($"{provinces.Count} provinces, {municipalities.Count} municipalities, {postal.Count} with postal codes.");
return 0;
// The rows of the first sheet of an xlsx, read with the framework only (shared strings and inline strings).
static List<List<string>> ReadFirstSheet(string path)
{
XNamespace ns = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
using var zip = ZipFile.OpenRead(path);
var shared = zip.GetEntry("xl/sharedStrings.xml") is { } entry
? [.. Load(entry).Root!.Elements(ns + "si").Select(si => string.Concat(si.Descendants(ns + "t").Select(t => t.Value)))]
: new List<string>();
var sheetEntry = zip.Entries.Where(e => e.FullName.StartsWith("xl/worksheets/sheet", StringComparison.Ordinal)).OrderBy(e => e.FullName, StringComparer.Ordinal).First();
var rows = new List<List<string>>();
foreach (var row in Load(sheetEntry).Descendants(ns + "row"))
{
var cells = new SortedDictionary<int, string>();
foreach (var cell in row.Elements(ns + "c"))
{
var value = cell.Element(ns + "v")?.Value;
cells[Column((string)cell.Attribute("r")!)] = (string?)cell.Attribute("t") switch
{
"s" when value is not null => shared[int.Parse(value, CultureInfo.InvariantCulture)],
"inlineStr" => string.Concat(cell.Descendants(ns + "t").Select(t => t.Value)),
_ => value ?? string.Empty,
};
}
var width = cells.Count == 0 ? 0 : cells.Keys.Max() + 1;
rows.Add([.. Enumerable.Range(0, width).Select(i => cells.GetValueOrDefault(i, string.Empty))]);
}
return rows;
static XDocument Load(ZipArchiveEntry entry)
{
using var stream = entry.Open();
return XDocument.Load(stream);
}
static int Column(string reference)
{
var n = 0;
foreach (var ch in reference.TakeWhile(char.IsAsciiLetterUpper))
{
n = (n * 26) + (ch - 'A' + 1);
}
return n - 1;
}
}
// GeoNames rows: country, postal code, place, region, region code, province, abbreviation, ...
static Dictionary<string, SortedSet<string>> MatchPostalCodes(string path, List<Place> municipalities)
{
using var zip = ZipFile.OpenRead(path);
using var reader = new StreamReader(zip.GetEntry("IT.txt")!.Open(), Encoding.UTF8);
var byNameAndProvince = municipalities.ToLookup(m => (Normalize(m.Name), m.Province));
var byName = municipalities.ToLookup(m => Normalize(m.Name));
var result = new Dictionary<string, SortedSet<string>>(StringComparer.Ordinal);
while (reader.ReadLine() is { } line)
{
var fields = line.Split('\t');
var name = Normalize(fields[2]);
var match = byNameAndProvince[(name, fields[6])].ToList();
if (match.Count != 1 && fields[3] == "Sardegna")
{
match = [.. byName[name].Where(m => m.Region == "Sardegna")];
}
if (match.Count == 1)
{
if (!result.TryGetValue(match[0].Code, out var set))
{
result[match[0].Code] = set = new SortedSet<string>(StringComparer.Ordinal);
}
set.Add(fields[1]);
}
}
return result;
}
// Lower case without accents, apostrophes or hyphens; the Italian part of bilingual names.
static string Normalize(string name)
{
var text = name.Split('/')[0].Normalize(NormalizationForm.FormD);
var builder = new StringBuilder();
foreach (var ch in text)
{
if (CharUnicodeInfo.GetUnicodeCategory(ch) == UnicodeCategory.NonSpacingMark)
{
continue;
}
builder.Append(ch is '-' or '\'' or '`' or '.' ? ' ' : char.ToLowerInvariant(ch));
}
return string.Join(' ', builder.ToString().Split(' ', StringSplitOptions.RemoveEmptyEntries));
}
// 10121,10122,10123 becomes 10121-10123.
static string Ranges(SortedSet<string> codes)
{
var parts = new List<string>();
string? start = null;
string? previous = null;
foreach (var code in codes)
{
if (start is not null && int.Parse(code, CultureInfo.InvariantCulture) == int.Parse(previous!, CultureInfo.InvariantCulture) + 1)
{
previous = code;
continue;
}
if (start is not null)
{
parts.Add(start == previous ? start : $"{start}-{previous}");
}
start = previous = code;
}
if (start is not null)
{
parts.Add(start == previous ? start : $"{start}-{previous}");
}
return string.Join(',', parts);
}
internal sealed record Place(string Code, string Name, string Province, string Region, string Istat);