diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7203944..4654fc8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -68,6 +68,13 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`.
- 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
diff --git a/docs/STATUS.md b/docs/STATUS.md
index fe26fec..7fb69b1 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -8,10 +8,10 @@ Fatti: pacchetto fiscale (#37), validatori e VIES (#40), tabelle azienda, profil
(#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), anagrafiche con radar, scheda, controlli, VIES e
21 anagrafiche di esempio (#41, ADR 0029), articoli e listini con prezzi a validità, listini derivati,
-aggiornamento massivo, codici delle anagrafiche, 120 articoli di esempio e `seed --demo [--scale N]` (#42, ADR 0030).
-ADR 0025-0030.
-**Prossimo passo:** import/export guidato (#44), chiusura M4 come `v0.4.0` (#46). #35 (PNG ad alta risoluzione) resta
-aperta e non blocca.
+aggiornamento massivo, codici delle anagrafiche, 120 articoli di esempio e `seed --demo [--scale N]` (#42, ADR 0030),
+import/export guidato CSV/XLSX/JSON con tracciato del piano dei conti (#44, ADR 0031; giacenze e piano dei conti solo
+verifica fino a M6/M7). ADR 0025-0031.
+**Prossimo passo:** chiusura M4 come `v0.4.0` (#46). #35 (PNG ad alta risoluzione) resta aperta e non blocca.
Da recuperare: misure di riferimento su PostgreSQL in `docs/DATA-MODEL.md` §6.1; indicatore di robustezza della
password (mockup 003); schede *Layout salvati* (M4) e *Notifiche* (con le e-mail, M5) del profilo; rinomina e
filtro predefinito nei radar.
@@ -19,7 +19,7 @@ filtro predefinito nei radar.
## Fatto
- Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E6.
-- ADR 0001-0030.
+- 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`,
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/Import-Export.md b/docs/wiki/Import-Export.md
index 8d09698..70e4508 100644
--- a/docs/wiki/Import-Export.md
+++ b/docs/wiki/Import-Export.md
@@ -1,103 +1,163 @@
# 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

*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***
## 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 completato 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 +165,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 +244,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/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