feat: guided import and export for parties, items, prices, opening stock and chart of accounts (#44)

Companies starting on Khaemhat need to bring their master data from another
system or a spreadsheet, and the chart of accounts has no Italian exchange
standard, so SPEC 12.12 asks for a guided wizard and an own layout.

- Administration > Import / export: CSV (separator and encoding guessed),
  XLSX (in-house reader, first sheet) and JSON, automatic column mapping with
  aliases, row-by-row check, error report, import confirmation and log entry.
- Rows go through PartyService, ItemService and PriceListService, so the
  import has exactly the rules, error codes and history of the forms; options
  cover existing and missing codes, VIES and city from postal code.
- Export writes the same columns as the import, plus empty templates.
- Opening stock and the chart of accounts (khaemhat-coa layout, natura, tipo,
  flag) are check-only until M6 and M7 add the ledgers to write into.
- PartyService.SaveAsync takes an explicit VIES switch for the import.
- ADR 0031, wiki Import-Export, CHANGELOG and STATUS updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-12 11:52:59 +01:00
1 parent 3dbbaba86e
commit caa33a2cee
29 files changed
+4783 -90

No files matched your search

+7
View File
@@ -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
+5 -5
View File
@@ -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`,
+69
View File
@@ -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.
+160 -76
View File
@@ -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
![077 · Import/Export · procedura guidata CSV/XLSX/JSON](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/077-import-export-wizard.png)
*Mockup 077 — a sinistra i quattro passi della procedura guidata (Origine, Mappatura colonne, Validazione,
Importazione) e le opzioni; a destra l'**Anteprima e validazione** con l'esito riga per riga; in alto **Scarica report
errori** e **Importa N righe** (anteprima ridotta)*
Importazione), le opzioni e il riquadro **Esporta e modelli**; a destra la mappatura o l'**Anteprima e validazione**
con l'esito riga per riga; in alto **Scarica report errori** e **Importa N righe***
## 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)
@@ -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;
/// <summary>An account of the chart read from a file.</summary>
/// <param name="Code">The code, parts separated by points (<c>01.02.003</c>).</param>
/// <param name="Description">The description.</param>
/// <param name="Level">The level, 1 to 3: the number of parts of the code.</param>
/// <param name="ParentCode">The code without its last part.</param>
/// <param name="Nature">The nature.</param>
/// <param name="Type">The use.</param>
/// <param name="Postable">Postings go on it (only leaves).</param>
/// <param name="VatRelevant">Relevant for VAT.</param>
/// <param name="SubLedger">With a sub-ledger of customers or suppliers.</param>
/// <param name="ClosesAutomatically">Closed by the year end.</param>
/// <param name="Disabled">Not used any more.</param>
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);
/// <summary>
/// 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.
/// </summary>
public static class ChartOfAccountsImportValidator
{
/// <summary>The words of <c>natura</c>, in the order of <see cref="AccountNature"/>.</summary>
public static readonly IReadOnlyList<string> NatureWords = ["attivo", "passivo", "costo", "ricavo", "ordine"];
/// <summary>The words of <c>tipo</c>, in the order of <see cref="AccountType"/>.</summary>
public static readonly IReadOnlyList<string> TypeWords = ["generico", "clienti", "fornitori", "banca", "cassa", "iva", "erario"];
/// <summary>The flag letters: postable, VAT relevant, sub-ledger, automatic closing, disabled.</summary>
public const string FlagLetters = "MIPCX";
/// <summary>The deepest level.</summary>
public const int MaxLevel = 3;
/// <summary>The columns of the chart.</summary>
public static IReadOnlyList<ImportField> 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"]),
];
/// <summary>Checks the rows of a chart.</summary>
/// <param name="rows">The rows.</param>
/// <returns>A result per row, and the accounts without errors.</returns>
public static (IReadOnlyList<ImportRowResult> Results, IReadOnlyList<ImportedAccount> Accounts) Check(IReadOnlyList<ImportRow> 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<string, AccountNature?>(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<string>(StringComparer.OrdinalIgnoreCase);
var results = new List<ImportRowResult>(rows.Count);
var accounts = new List<ImportedAccount>();
foreach (var row in rows)
{
var messages = new List<ImportMessage>();
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);
}
/// <summary>The code without its last part, or <see langword="null"/> for a first level account.</summary>
/// <param name="code">The code.</param>
/// <returns>The parent code.</returns>
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<string, AccountNature?> 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<string> words) => text is null ? null : ImportValues.Choice(text, words) is var i and >= 0 ? i : null;
}
/// <summary>
/// The chart of accounts (<c>piano-dei-conti</c>): CSV, XLSX or <c>khaemhat-coa.json</c>. Until the ledger exists (M7)
/// the file is only checked; M7 writes the accounts this check accepts.
/// </summary>
/// <param name="permissions">Checks the permission.</param>
public sealed class ChartOfAccountsImportTarget(PermissionService permissions) : IImportTarget
{
/// <summary>The permission to change the chart of accounts.</summary>
public const string WritePermission = "ledger.account.write";
/// <inheritdoc />
public string Key => "piano-dei-conti";
/// <inheritdoc />
public string ModuleCode => ModuleCodes.Accounting;
/// <inheritdoc />
public string Permission => WritePermission;
/// <inheritdoc />
public string ExportPermission => "ledger.account.read";
/// <inheritdoc />
public bool CanApply => false;
/// <inheritdoc />
public bool CanExport => false;
/// <inheritdoc />
public IReadOnlyList<ImportField> Fields => ChartOfAccountsImportValidator.Fields;
/// <inheritdoc />
public async Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
return ChartOfAccountsImportValidator.Check(rows).Results;
}
/// <inheritdoc />
public Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
throw new InvalidOperationException(ImportErrors.CheckOnly);
/// <inheritdoc />
public Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken) =>
Task.FromResult<IReadOnlyList<IReadOnlyList<object?>>>([]);
}
/// <summary>
/// The opening stock (<c>giacenze-iniziali</c>): 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.
/// </summary>
/// <param name="factory">Opens the company databases.</param>
/// <param name="permissions">Checks the permission.</param>
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"]),
];
/// <inheritdoc />
public string Key => "giacenze-iniziali";
/// <inheritdoc />
public string ModuleCode => ModuleCodes.Core;
/// <inheritdoc />
public string Permission => "inventory.entry.write";
/// <inheritdoc />
public string ExportPermission => "inventory.stock.read";
/// <inheritdoc />
public bool CanApply => false;
/// <inheritdoc />
public bool CanExport => false;
/// <inheritdoc />
public IReadOnlyList<ImportField> Fields => StockFields;
/// <inheritdoc />
public async Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> 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<Item, long>().ListAsync(Query.For<Item>(), 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<Warehouse>(uow, cancellationToken).ConfigureAwait(false);
var seen = new HashSet<(long, long)>();
var results = new List<ImportRowResult>(rows.Count);
foreach (var row in rows)
{
var messages = new List<ImportMessage>();
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;
}
/// <inheritdoc />
public Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
throw new InvalidOperationException(ImportErrors.CheckOnly);
/// <inheritdoc />
public Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken) =>
Task.FromResult<IReadOnlyList<IReadOnlyList<object?>>>([]);
}
@@ -0,0 +1,255 @@
using System.Globalization;
using System.Text;
using System.Text.Json;
using Khaemhat.Infrastructure.Files;
namespace Khaemhat.Application.ImportExport;
/// <summary>A file the import cannot use; <see cref="Code"/> is one of the <c>import.file.*</c> codes.</summary>
public sealed class ImportFileException : Exception
{
/// <summary>Creates the exception.</summary>
public ImportFileException()
{
Code = ImportErrors.FileUnreadable;
}
/// <summary>Creates the exception.</summary>
/// <param name="message">What went wrong.</param>
public ImportFileException(string message)
: base(message)
{
Code = ImportErrors.FileUnreadable;
}
/// <summary>Creates the exception.</summary>
/// <param name="message">What went wrong.</param>
/// <param name="innerException">The cause.</param>
public ImportFileException(string message, Exception innerException)
: base(message, innerException)
{
Code = ImportErrors.FileUnreadable;
}
/// <summary>Creates the exception with a code.</summary>
/// <param name="code">The text code.</param>
/// <param name="message">What went wrong.</param>
/// <param name="innerException">The cause.</param>
public ImportFileException(string code, string message, Exception? innerException)
: base(message, innerException)
{
Code = code;
}
/// <summary>The text code.</summary>
public string Code { get; }
}
/// <summary>
/// Reads the files of the guided import (SPEC §12.12): CSV (UTF-8 with or without byte order mark, else Windows-1252;
/// separator <c>;</c>, <c>,</c> or tab guessed from the header), XLSX (first sheet) and JSON (an array of objects, or the
/// object of <c>khaemhat-coa.json</c> with its <c>accounts</c>). The first row holds the headers.
/// </summary>
public static class ImportFileReader
{
/// <summary>The most data rows an import takes.</summary>
public const int MaxRows = 50_000;
/// <summary>The format name written in <c>khaemhat-coa.json</c>.</summary>
public const string ChartFormat = "khaemhat-coa";
private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
/// <summary>The format of a file from its name.</summary>
/// <param name="fileName">The name.</param>
/// <returns>The format, or <see langword="null"/> when not supported.</returns>
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,
};
/// <summary>Reads a file.</summary>
/// <param name="fileName">The name, which gives the format.</param>
/// <param name="content">The content.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The file with headers and rows.</returns>
/// <exception cref="ImportFileException">The format is not supported, or the file is empty, damaged or too large.</exception>
public static async Task<ImportFile> 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()),
};
}
/// <summary>Reads CSV bytes.</summary>
/// <param name="fileName">The name.</param>
/// <param name="bytes">The content.</param>
/// <returns>The file.</returns>
/// <exception cref="ImportFileException">Empty or too large.</exception>
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<ImportFile> 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<string, int>? 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<string, int>(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<string>();
var index = new Dictionary<string, int>(StringComparer.Ordinal);
var objects = new List<Dictionary<string, string>>();
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<string, string>(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<IReadOnlyList<string>> { headers };
rows.AddRange(objects.Select(o => (IReadOnlyList<string>)[.. 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<IReadOnlyList<string>> lines,
IReadOnlyDictionary<string, int>? 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<IReadOnlyList<string>>(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'];
}
@@ -0,0 +1,197 @@
using Khaemhat.Application.Security;
namespace Khaemhat.Application.ImportExport;
/// <summary>The formats of the guided import and export (SPEC §12.12).</summary>
public enum TransferFormat
{
/// <summary>Text with <c>;</c>, UTF-8 (other separators and Windows-1252 are recognized when reading).</summary>
Csv = 0,
/// <summary>Excel workbook, first sheet, headers in the first row.</summary>
Xlsx = 1,
/// <summary>JSON: an array of objects keyed by column, or the object of <c>khaemhat-coa.json</c>.</summary>
Json = 2,
}
/// <summary>The kind of value of a column, for reading and writing it.</summary>
public enum ImportFieldKind
{
/// <summary>Free text.</summary>
Text = 0,
/// <summary>A code of another archive or table.</summary>
Code = 1,
/// <summary>A decimal number (Italian or invariant notation).</summary>
Number = 2,
/// <summary>A date (<c>dd/MM/yyyy</c>, ISO or a spreadsheet serial).</summary>
Date = 3,
/// <summary>Yes or no.</summary>
Boolean = 4,
/// <summary>One of a list of words.</summary>
Choice = 5,
}
/// <summary>A column an entity accepts.</summary>
/// <param name="Key">The column name used in files and templates (<c>partita_iva</c>).</param>
/// <param name="Kind">The kind of value.</param>
/// <param name="Required">Whether a new record needs it.</param>
/// <param name="Aliases">Other headers recognized by the automatic mapping, already normalized.</param>
/// <param name="Choices">The words accepted for <see cref="ImportFieldKind.Choice"/>.</param>
public sealed record ImportField(string Key, ImportFieldKind Kind = ImportFieldKind.Text, bool Required = false, IReadOnlyList<string>? Aliases = null,
IReadOnlyList<string>? Choices = null);
/// <summary>A file read for the import.</summary>
/// <param name="Name">The file name.</param>
/// <param name="Format">The format.</param>
/// <param name="Encoding">The text encoding (CSV), such as <c>UTF-8</c>.</param>
/// <param name="Separator">The separator (CSV).</param>
/// <param name="Headers">The headers of the columns.</param>
/// <param name="Rows">The rows under the headers, each as long as the headers.</param>
/// <param name="Sections">For <c>khaemhat-coa.json</c>: the other sections with their number of entries.</param>
public sealed record ImportFile(string Name, TransferFormat Format, string? Encoding, char? Separator, IReadOnlyList<string> Headers,
IReadOnlyList<IReadOnlyList<string>> Rows, IReadOnlyDictionary<string, int>? Sections = null)
{
/// <summary>The number of data rows.</summary>
public int Count => Rows.Count;
}
/// <summary>What happens to a row whose code is already in the archive.</summary>
public enum ExistingCodeAction
{
/// <summary>The record is updated with the non empty cells of the row.</summary>
Update = 0,
/// <summary>The row is skipped.</summary>
Skip = 1,
}
/// <summary>What happens to a row without a code.</summary>
public enum MissingCodeAction
{
/// <summary>The code comes from the automatic code rules.</summary>
Generate = 0,
/// <summary>The row is an error.</summary>
Refuse = 1,
}
/// <summary>The options of an import (mockup 077, step 1).</summary>
public sealed record ImportOptions
{
/// <summary>Rows whose code exists.</summary>
public ExistingCodeAction Existing { get; init; } = ExistingCodeAction.Update;
/// <summary>Rows without a code.</summary>
public MissingCodeAction Missing { get; init; } = MissingCodeAction.Generate;
/// <summary>Check the VAT numbers of EU parties on VIES while importing.</summary>
public bool VerifyVat { get; init; }
/// <summary>Fill the city from the postal code (and the postal code from the city) when one is missing.</summary>
public bool FillFromPostalCode { get; init; } = true;
}
/// <summary>Who imports, where and how: what a target needs besides the rows.</summary>
/// <param name="Actor">Who imports.</param>
/// <param name="CompanyCode">The company.</param>
/// <param name="Options">The options.</param>
public sealed record ImportContext(Actor Actor, string CompanyCode, ImportOptions Options);
/// <summary>A row of the file with the cells of the mapped columns by field key.</summary>
/// <param name="Line">The line in the file, counting the header as line 1.</param>
/// <param name="Values">The trimmed cells by field key; empty cells are left out.</param>
public sealed record ImportRow(int Line, IReadOnlyDictionary<string, string> Values)
{
/// <summary>The cell of a field, or <see langword="null"/> when empty or not mapped.</summary>
/// <param name="key">The field.</param>
/// <returns>The text.</returns>
public string? this[string key] => Values.TryGetValue(key, out var value) ? value : null;
}
/// <summary>The outcome of a row in the preview (mockup 077: OK, avviso, errore).</summary>
public enum ImportOutcome
{
/// <summary>Importable.</summary>
Ok = 0,
/// <summary>Importable, with a correction proposed or a remark.</summary>
Warning = 1,
/// <summary>Not importable.</summary>
Error = 2,
}
/// <summary>What the import does with a row.</summary>
public enum ImportAction
{
/// <summary>A new record.</summary>
Create = 0,
/// <summary>An existing record changes.</summary>
Update = 1,
/// <summary>Nothing (existing code to skip, or an error).</summary>
Skip = 2,
}
/// <summary>A remark on a row: a text code with the field it concerns.</summary>
/// <param name="Field">The field key, or empty for the whole row.</param>
/// <param name="Code">The text code (an error code of the services or <c>import.*</c>).</param>
/// <param name="IsWarning">A warning instead of an error.</param>
/// <param name="Value">A value to show in the text (<c>{0}</c>), such as the code not found or the city proposed.</param>
public sealed record ImportMessage(string Field, string Code, bool IsWarning = false, string? Value = null);
/// <summary>The check of a row.</summary>
/// <param name="Line">The line in the file.</param>
/// <param name="Key">The code or description that identifies the row in the preview.</param>
/// <param name="Action">What the import will do.</param>
/// <param name="Messages">The remarks.</param>
public sealed record ImportRowResult(int Line, string Key, ImportAction Action, IReadOnlyList<ImportMessage> Messages)
{
/// <summary>The outcome from the remarks.</summary>
public ImportOutcome Outcome =>
Messages.Any(m => !m.IsWarning) ? ImportOutcome.Error : Messages.Count > 0 ? ImportOutcome.Warning : ImportOutcome.Ok;
}
/// <summary>The preview of an import (mockup 077, steps 3 and 4).</summary>
/// <param name="Target">The entity.</param>
/// <param name="Rows">The checked rows, in file order.</param>
/// <param name="CanApply">Whether the entity can be written now (opening stock and chart of accounts only check, until M6 and M7).</param>
public sealed record ImportPreview(string Target, IReadOnlyList<ImportRowResult> Rows, bool CanApply)
{
/// <summary>Rows that will create a record.</summary>
public int Creates => Rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Create);
/// <summary>Rows that will update a record.</summary>
public int Updates => Rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Update);
/// <summary>Rows skipped on purpose.</summary>
public int Skips => Rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Skip);
/// <summary>Rows with errors.</summary>
public int Errors => Rows.Count(r => r.Outcome == ImportOutcome.Error);
/// <summary>Rows with warnings only.</summary>
public int Warnings => Rows.Count(r => r.Outcome == ImportOutcome.Warning);
/// <summary>Rows the import writes.</summary>
public int Importable => Creates + Updates;
}
/// <summary>The result of an import.</summary>
/// <param name="Target">The entity.</param>
/// <param name="Created">Records created.</param>
/// <param name="Updated">Records updated.</param>
/// <param name="Skipped">Rows skipped on purpose.</param>
/// <param name="Rows">Every row with its final outcome; rows refused while writing carry their errors.</param>
public sealed record ImportReport(string Target, int Created, int Updated, int Skipped, IReadOnlyList<ImportRowResult> Rows)
{
/// <summary>Rows not imported because of errors.</summary>
public int Failed => Rows.Count(r => r.Outcome == ImportOutcome.Error);
}
@@ -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;
/// <summary>
/// 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.
/// </summary>
public sealed partial class ImportService
{
private static readonly JsonWriterOptions JsonOptions = new() { Indented = true };
private readonly IReadOnlyList<IImportTarget> _targets;
private readonly ILicenseGate _license;
private readonly PermissionService _permissions;
private readonly ILogger<ImportService> _logger;
/// <summary>Creates the service.</summary>
/// <param name="targets">The entities.</param>
/// <param name="license">The licence.</param>
/// <param name="permissions">The permissions and the user flags.</param>
/// <param name="logger">The log.</param>
public ImportService(IEnumerable<IImportTarget> targets, ILicenseGate license, PermissionService permissions, ILogger<ImportService> logger)
{
ArgumentNullException.ThrowIfNull(targets);
ArgumentNullException.ThrowIfNull(license);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(logger);
_targets = [.. targets];
_license = license;
_permissions = permissions;
_logger = logger;
}
/// <summary>The entities whose module is licensed, in the order of the screen.</summary>
public IReadOnlyList<IImportTarget> Targets => [.. _targets.Where(t => _license.IsModuleActive(t.ModuleCode))];
/// <summary>A licensed entity by key.</summary>
/// <param name="key">The key.</param>
/// <returns>The entity.</returns>
/// <exception cref="ImportFileException">Unknown or not licensed (<see cref="ImportErrors.TargetUnknown"/>).</exception>
public IImportTarget Target(string key) =>
Targets.FirstOrDefault(t => string.Equals(t.Key, key, StringComparison.OrdinalIgnoreCase))
?? throw new ImportFileException(ImportErrors.TargetUnknown, "Unknown import: " + key, null);
/// <summary>
/// The field of each column of a file, by name or alias ignoring case, accents and punctuation; a field goes to one
/// column only.
/// </summary>
/// <param name="target">The entity.</param>
/// <param name="headers">The headers.</param>
/// <returns>The field key per column, or <see langword="null"/> for columns to ignore.</returns>
public static IReadOnlyList<string?> SuggestMapping(IImportTarget target, IReadOnlyList<string> headers)
{
ArgumentNullException.ThrowIfNull(target);
ArgumentNullException.ThrowIfNull(headers);
var taken = new HashSet<string>(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;
}
/// <summary>The rows of a file with the cells of the mapped columns.</summary>
/// <param name="file">The file.</param>
/// <param name="mapping">The field key per column, or <see langword="null"/>.</param>
/// <returns>The rows, line numbers counting the header as line 1.</returns>
public static IReadOnlyList<ImportRow> Rows(ImportFile file, IReadOnlyList<string?> mapping)
{
ArgumentNullException.ThrowIfNull(file);
ArgumentNullException.ThrowIfNull(mapping);
var rows = new List<ImportRow>(file.Count);
for (var r = 0; r < file.Count; r++)
{
var values = new Dictionary<string, string>(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;
}
/// <summary>Checks a file without writing (steps 2 and 3 of the screen).</summary>
/// <param name="actor">Who imports.</param>
/// <param name="companyCode">The company.</param>
/// <param name="targetKey">The entity.</param>
/// <param name="file">The file.</param>
/// <param name="mapping">The field per column.</param>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The preview.</returns>
public async Task<ImportPreview> PreviewAsync(Actor actor, string companyCode, string targetKey, ImportFile file, IReadOnlyList<string?> 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);
}
/// <summary>Imports the rows without errors (step 4); rows with errors are left out and reported.</summary>
/// <param name="actor">Who imports.</param>
/// <param name="companyCode">The company.</param>
/// <param name="targetKey">The entity.</param>
/// <param name="file">The file.</param>
/// <param name="mapping">The field per column.</param>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What was done.</returns>
/// <exception cref="ImportFileException">The entity is only checked for now (<see cref="ImportErrors.CheckOnly"/>).</exception>
public async Task<ImportReport> ImportAsync(Actor actor, string companyCode, string targetKey, ImportFile file, IReadOnlyList<string?> 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;
}
/// <summary>Writes the rows with errors and warnings as CSV (button <i>Scarica report errori</i>).</summary>
/// <param name="rows">The checked rows.</param>
/// <param name="text">The text of a remark, in the language of the user.</param>
/// <param name="labels">The headers: line, key, column, outcome, message.</param>
/// <param name="output">Where to write.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public static async Task WriteErrorReportAsync(IReadOnlyList<ImportRowResult> rows, Func<ImportRowResult, ImportMessage, (string Outcome, string Message)> text,
IReadOnlyList<string> 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);
}
/// <summary>Exports an entity with the columns of its import, so that the file can be imported again.</summary>
/// <param name="actor">Who exports: needs the export permission of the entity and the <i>can export</i> flag.</param>
/// <param name="companyCode">The company.</param>
/// <param name="targetKey">The entity.</param>
/// <param name="format">The format.</param>
/// <param name="output">Where to write.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The number of records written.</returns>
/// <exception cref="AccessDeniedException">The user cannot export.</exception>
public async Task<int> 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;
}
/// <summary>Writes the empty template of an entity: the headers only (for JSON, one object with empty values).</summary>
/// <param name="target">The entity.</param>
/// <param name="format">The format.</param>
/// <param name="output">Where to write.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public static Task WriteTemplateAsync(IImportTarget target, TransferFormat format, Stream output, CancellationToken cancellationToken = default) =>
WriteAsync(target, format, [], output, cancellationToken);
/// <summary>The name of an export or template file (<c>clienti-2026-11-12.csv</c>, <c>modello-clienti.xlsx</c>).</summary>
/// <param name="targetKey">The entity.</param>
/// <param name="format">The format.</param>
/// <param name="date">The day of an export, or <see langword="null"/> for a template.</param>
/// <returns>The file name.</returns>
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;
}
/// <summary>The media type of a format.</summary>
/// <param name="format">The format.</param>
/// <returns>The media type.</returns>
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<IReadOnlyList<object?>> 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<string> headers, IReadOnlyList<IReadOnlyList<object?>> 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<IReadOnlyList<object?>> 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);
}
@@ -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;
/// <summary>
/// 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.
/// </summary>
public interface IImportTarget
{
/// <summary>The key in addresses and texts (<c>clienti</c>, <c>piano-dei-conti</c>).</summary>
string Key { get; }
/// <summary>The licence module the entity belongs to.</summary>
string ModuleCode { get; }
/// <summary>The permission to import it (the write permission of its record).</summary>
string Permission { get; }
/// <summary>The permission to export it (besides the <i>can export</i> flag of the user).</summary>
string ExportPermission { get; }
/// <summary>Whether rows can be written now; otherwise the file is only checked (opening stock until M6, chart of accounts until M7).</summary>
bool CanApply { get; }
/// <summary>Whether there are records to export now.</summary>
bool CanExport { get; }
/// <summary>The columns, in the order of templates and exports.</summary>
IReadOnlyList<ImportField> Fields { get; }
/// <summary>Checks the rows without writing.</summary>
/// <param name="context">Who, where, how.</param>
/// <param name="rows">The rows.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A result per row, in order.</returns>
Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken);
/// <summary>Writes the rows without errors, each like a save of its record.</summary>
/// <param name="context">Who, where, how.</param>
/// <param name="rows">The rows.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A result per row, in order, with what was done.</returns>
Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken);
/// <summary>The records as rows of cells in the order of <see cref="Fields"/>.</summary>
/// <param name="context">Who, where.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows.</returns>
Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken);
}
/// <summary>Reads the cells of a row as values, adding a remark for every cell that is not what its field wants.</summary>
/// <param name="row">The row.</param>
/// <param name="messages">Where the remarks go.</param>
public sealed class CellReader(ImportRow row, List<ImportMessage> messages)
{
/// <summary>The row.</summary>
public ImportRow Row => row;
/// <summary>The remarks so far.</summary>
public List<ImportMessage> Messages => messages;
/// <summary>Whether the cell has a value.</summary>
/// <param name="key">The field.</param>
/// <returns><see langword="true"/> when not empty.</returns>
public bool Has(string key) => row[key] is not null;
/// <summary>The text of a cell.</summary>
/// <param name="key">The field.</param>
/// <returns>The text, or <see langword="null"/>.</returns>
public string? Text(string key) => row[key];
/// <summary>A number.</summary>
/// <param name="key">The field.</param>
/// <returns>The number, or <see langword="null"/> when empty or wrong (with a remark).</returns>
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;
}
/// <summary>A date.</summary>
/// <param name="key">The field.</param>
/// <returns>The date, or <see langword="null"/> when empty or wrong (with a remark).</returns>
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;
}
/// <summary>Yes or no.</summary>
/// <param name="key">The field.</param>
/// <returns>The value, or <see langword="null"/> when empty or wrong (with a remark).</returns>
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;
}
/// <summary>One of the words of a field.</summary>
/// <param name="field">The field with its choices.</param>
/// <returns>The position of the word, or <see langword="null"/> when empty or unknown (with a remark).</returns>
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;
}
/// <summary>The id of a code of another archive or table.</summary>
/// <param name="key">The field.</param>
/// <param name="index">The codes.</param>
/// <returns>The id, or <see langword="null"/> when empty or unknown (with a remark).</returns>
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;
}
}
/// <summary>The ids of the records of an archive or table by code, ignoring case.</summary>
public sealed class CodeIndex
{
private readonly Dictionary<string, long> _ids = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<long, string> _codes = [];
/// <summary>Creates an index.</summary>
/// <param name="entries">The codes with their ids.</param>
public CodeIndex(IEnumerable<(string Code, long Id)> entries)
{
ArgumentNullException.ThrowIfNull(entries);
foreach (var (code, id) in entries)
{
_ids.TryAdd(code, id);
_codes[id] = code;
}
}
/// <summary>The number of codes.</summary>
public int Count => _ids.Count;
/// <summary>Loads the codes of a table of the company.</summary>
/// <typeparam name="T">The table.</typeparam>
/// <param name="uow">The unit of work.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The index.</returns>
public static async Task<CodeIndex> LoadAsync<T>(IUnitOfWork uow, CancellationToken cancellationToken)
where T : CodedEntity, new()
{
ArgumentNullException.ThrowIfNull(uow);
var rows = await uow.Repository<T, long>().ListAsync(Query.For<T>(), cancellationToken).ConfigureAwait(false);
return new CodeIndex(rows.Items.Select(r => (r.Code, r.Id)));
}
/// <summary>The id of a code.</summary>
/// <param name="code">The code.</param>
/// <returns>The id, or <see langword="null"/>.</returns>
public long? Find(string? code) => code is not null && _ids.TryGetValue(code.Trim(), out var id) ? id : null;
/// <summary>The code of an id.</summary>
/// <param name="id">The id.</param>
/// <returns>The code, or <see langword="null"/>.</returns>
public string? CodeOf(long? id) => id is { } key && _codes.TryGetValue(key, out var code) ? code : null;
/// <summary>Adds a code written meanwhile.</summary>
/// <param name="code">The code.</param>
/// <param name="id">The id.</param>
public void Add(string code, long id)
{
ArgumentNullException.ThrowIfNull(code);
_ids[code] = id;
_codes[id] = code;
}
}
/// <summary>
/// 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.
/// </summary>
/// <typeparam name="TRecord">The record.</typeparam>
/// <typeparam name="TState">What is loaded once per check or import (codes of tables and archives).</typeparam>
public abstract class RecordImportTarget<TRecord, TState> : IImportTarget
where TRecord : class
{
/// <inheritdoc />
public abstract string Key { get; }
/// <inheritdoc />
public abstract string ModuleCode { get; }
/// <inheritdoc />
public abstract string Permission { get; }
/// <inheritdoc />
public abstract string ExportPermission { get; }
/// <inheritdoc />
public bool CanApply => true;
/// <inheritdoc />
public bool CanExport => true;
/// <inheritdoc />
public abstract IReadOnlyList<ImportField> Fields { get; }
/// <summary>The column with the code of the record.</summary>
protected virtual string CodeField => "codice";
/// <inheritdoc />
public Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
RunAsync(context, rows, write: false, cancellationToken);
/// <inheritdoc />
public Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
RunAsync(context, rows, write: true, cancellationToken);
/// <inheritdoc />
public abstract Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken);
/// <summary>Loads what every row needs, checking a permission.</summary>
/// <param name="context">Who, where, how.</param>
/// <param name="permission">The permission demanded (to import or to export).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The state.</returns>
protected abstract Task<TState> LoadAsync(ImportContext context, string permission, CancellationToken cancellationToken);
/// <summary>The id of an existing record with a code, or <see langword="null"/>; a remark refuses the code (another kind).</summary>
/// <param name="state">The state.</param>
/// <param name="code">The code.</param>
/// <param name="messages">Where remarks go.</param>
/// <returns>The id.</returns>
protected abstract long? Existing(TState state, string code, List<ImportMessage> messages);
/// <summary>A new record, or an existing one read by id.</summary>
/// <param name="context">Who, where.</param>
/// <param name="id">The id, or <see langword="null"/> for a new record.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The record.</returns>
protected abstract Task<TRecord?> OpenAsync(ImportContext context, long? id, CancellationToken cancellationToken);
/// <summary>Copies the cells of a row into the record; a code given for a new record is set too.</summary>
/// <param name="context">Who, where, how.</param>
/// <param name="state">The state.</param>
/// <param name="record">The record.</param>
/// <param name="cells">The row with its remarks.</param>
/// <param name="isNew">Whether the record is new.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
protected abstract Task FillAsync(ImportContext context, TState state, TRecord record, CellReader cells, bool isNew, CancellationToken cancellationToken);
/// <summary>Checks a record with the rules of its service.</summary>
/// <param name="context">Who, where.</param>
/// <param name="record">The record.</param>
/// <param name="isNew">Whether the record is new (its code is checked against the code rules).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The problems.</returns>
protected abstract Task<IReadOnlyList<TableProblem>> ValidateAsync(ImportContext context, TRecord record, bool isNew, CancellationToken cancellationToken);
/// <summary>Saves a record with its service.</summary>
/// <param name="context">Who, where, how.</param>
/// <param name="record">The record.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The code and id given by the save.</returns>
protected abstract Task<(string Code, long Id)> SaveAsync(ImportContext context, TRecord record, CancellationToken cancellationToken);
/// <summary>What identifies the row in the preview (code, else description).</summary>
/// <param name="row">The row.</param>
/// <returns>The text.</returns>
protected abstract string Label(ImportRow row);
/// <summary>Records a code saved, so that later rows find it.</summary>
/// <param name="state">The state.</param>
/// <param name="code">The code.</param>
/// <param name="id">The id.</param>
protected abstract void Remember(TState state, string code, long id);
/// <summary>The column of a field of the service (<c>VatNumber</c>, <c>Fiscal.RecipientCode</c>); empty for the row.</summary>
/// <param name="serviceField">The field named by the service.</param>
/// <returns>The column key.</returns>
protected abstract string ColumnOf(string serviceField);
private async Task<IReadOnlyList<ImportRowResult>> RunAsync(ImportContext context, IReadOnlyList<ImportRow> rows, bool write, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(rows);
var state = await LoadAsync(context, Permission, cancellationToken).ConfigureAwait(false);
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var results = new List<ImportRowResult>(rows.Count);
foreach (var row in rows)
{
cancellationToken.ThrowIfCancellationRequested();
var messages = new List<ImportMessage>();
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;
}
}
/// <summary>Splits the <c>Field:code</c> errors of <see cref="ValidationFailedException"/>.</summary>
internal static class TableErrors
{
/// <summary>Splits an error.</summary>
/// <param name="error">The error.</param>
/// <returns>The field (empty for the record) and the code.</returns>
public static (string Field, string Code) Split(string error)
{
var colon = error.LastIndexOf(':');
return colon < 0 ? (string.Empty, error) : (error[..colon], error[(colon + 1)..]);
}
}
@@ -0,0 +1,274 @@
using System.Globalization;
using System.Text;
namespace Khaemhat.Application.ImportExport;
/// <summary>The text codes of the import remarks (<c>import.*</c>), shown by the screen with the field and the value.</summary>
public static class ImportErrors
{
/// <summary>The file is not CSV, XLSX or JSON.</summary>
public const string FileFormat = "import.file.format";
/// <summary>The file has no header or no rows.</summary>
public const string FileEmpty = "import.file.empty";
/// <summary>The file cannot be read (damaged spreadsheet, invalid JSON).</summary>
public const string FileUnreadable = "import.file.unreadable";
/// <summary>The file has more rows than an import takes.</summary>
public const string FileTooLarge = "import.file.too-large";
/// <summary>The entity is unknown or not licensed.</summary>
public const string TargetUnknown = "import.target.unknown";
/// <summary>The entity is only checked for now (opening stock until M6, chart of accounts until M7).</summary>
public const string CheckOnly = "import.target.check-only";
/// <summary>A required column of a new record is empty or not mapped.</summary>
public const string Required = "import.value.required";
/// <summary>Not a number.</summary>
public const string Number = "import.value.number";
/// <summary>Not a date.</summary>
public const string Date = "import.value.date";
/// <summary>Not yes or no.</summary>
public const string Boolean = "import.value.boolean";
/// <summary>Not one of the words accepted (<c>{0}</c> lists them).</summary>
public const string Choice = "import.value.choice";
/// <summary>A code of another archive or table that does not exist (<c>{0}</c>).</summary>
public const string CodeUnknown = "import.value.code-unknown";
/// <summary>The row has no code and the options do not generate it.</summary>
public const string CodeMissing = "import.code.missing";
/// <summary>The same code is on an earlier row of the file.</summary>
public const string CodeRepeated = "import.code.repeated";
/// <summary>The code exists and the options skip existing codes (a remark, not an error).</summary>
public const string CodeExists = "import.code.exists";
/// <summary>The code belongs to a party of another kind (a supplier among the customers).</summary>
public const string OtherKind = "import.party.other-kind";
/// <summary>The city was filled from the postal code (<c>{0}</c>).</summary>
public const string CityFilled = "import.filled.city";
/// <summary>The postal code was filled from the city (<c>{0}</c>).</summary>
public const string PostalCodeFilled = "import.filled.postal-code";
/// <summary>A price row names both a list and a customer, or neither.</summary>
public const string PriceTarget = "import.price.target";
/// <summary>Opening stock of an item that is not stocked goods.</summary>
public const string NotStocked = "import.stock.not-stocked";
/// <summary>The quantity must be more than zero.</summary>
public const string Positive = "import.value.positive";
/// <summary>The record could not be written (someone changed it meanwhile, or an unexpected rule).</summary>
public const string WriteFailed = "import.write.failed";
/// <summary>The level of an account is not 1 to 3, or not the number of parts of its code.</summary>
public const string AccountLevel = "import.coa.level";
/// <summary>The parent of an account is not the code without its last part, or is not in the file (<c>{0}</c>).</summary>
public const string AccountParent = "import.coa.parent";
/// <summary>An account has a nature other than its parent's.</summary>
public const string AccountNature = "import.coa.nature";
/// <summary>An account with sub-accounts is marked as postable.</summary>
public const string AccountPostable = "import.coa.postable";
/// <summary>A leaf account is not marked as postable (a remark).</summary>
public const string AccountLeaf = "import.coa.leaf";
/// <summary>A flag letter is not M, I, P, C or X (<c>{0}</c>).</summary>
public const string AccountFlag = "import.coa.flag";
}
/// <summary>The cells of the import as values, and the values of the export as cells.</summary>
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<string> Yes = new(StringComparer.Ordinal) { "si", "s", "yes", "y", "x", "1", "true", "vero", "v" };
private static readonly HashSet<string> No = new(StringComparer.Ordinal) { "no", "n", "0", "false", "falso", "f", "-" };
private static readonly DateTime Epoch = new(1899, 12, 30, 0, 0, 0, DateTimeKind.Unspecified);
/// <summary>
/// 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 (<c>Partita IVA</c> and <c>partita-iva</c> both give <c>partita_iva</c>).
/// </summary>
/// <param name="text">The text.</param>
/// <returns>The normalized text.</returns>
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();
}
/// <summary>
/// Reads a number written the Italian way (<c>1.234,56</c>, <c>€ 12,5</c>) or the machine way (<c>1234.56</c>):
/// 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.
/// </summary>
/// <param name="text">The cell.</param>
/// <param name="value">The number.</param>
/// <returns><see langword="true"/> when the cell is a number.</returns>
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);
}
/// <summary>Reads a date: <c>dd/MM/yyyy</c> and its variants, ISO, or a spreadsheet serial number.</summary>
/// <param name="text">The cell.</param>
/// <param name="value">The date.</param>
/// <returns><see langword="true"/> when the cell is a date.</returns>
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;
}
/// <summary>Reads yes or no: <c>sì</c>, <c>x</c>, <c>1</c>, <c>VERO</c>, <c>true</c>... and <c>no</c>, <c>0</c>, <c>FALSO</c>...</summary>
/// <param name="text">The cell.</param>
/// <param name="value">The value.</param>
/// <returns><see langword="true"/> when the cell is yes or no.</returns>
public static bool TryBoolean(string? text, out bool value)
{
var word = Normalize(text);
value = Yes.Contains(word);
return value || No.Contains(word);
}
/// <summary>Finds a word among the choices of a field, ignoring case, accents, spaces and punctuation (<c>P.A.</c> is <c>pa</c>).</summary>
/// <param name="text">The cell.</param>
/// <param name="choices">The words accepted, in the order of the values they stand for.</param>
/// <returns>The position of the word, or -1.</returns>
public static int Choice(string? text, IReadOnlyList<string> 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;
}
/// <summary>A number for a text cell of the export, the Italian way without thousands marks (<c>1234,5</c>).</summary>
/// <param name="value">The number.</param>
/// <returns>The text, or <see langword="null"/>.</returns>
public static string? Text(decimal? value) => value?.ToString("0.############", Italian);
/// <summary>A date for a text cell of the export (<c>dd/MM/yyyy</c>).</summary>
/// <param name="value">The date.</param>
/// <returns>The text, or <see langword="null"/>.</returns>
public static string? Text(DateOnly? value) => value?.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
/// <summary>Yes or no for a text cell of the export.</summary>
/// <param name="value">The value.</param>
/// <returns><c>sì</c> or <c>no</c>.</returns>
public static string Text(bool value) => value ? "sì" : "no";
}
@@ -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;
/// <summary>
/// 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 <see cref="ItemService"/>. Empty cells keep the values of an
/// existing item; units, bar codes, prices and suppliers of the record are left as they are.
/// </summary>
/// <param name="items">The items.</param>
/// <param name="codes">The automatic codes.</param>
/// <param name="factory">Opens the company databases (codes of the tables).</param>
/// <param name="permissions">Checks the permission to import.</param>
public sealed class ItemsImportTarget(ItemService items, CodeRuleService codes, IUnitOfWorkFactory factory, PermissionService permissions)
: RecordImportTarget<ItemRecord, ItemsImportTarget.State>
{
/// <summary>The words of <c>tipo</c>, in the order of <see cref="ItemKind"/>.</summary>
public static readonly IReadOnlyList<string> 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<string, string> 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",
};
/// <inheritdoc />
public override string Key => "articoli";
/// <inheritdoc />
public override string ModuleCode => ModuleCodes.Core;
/// <inheritdoc />
public override string Permission => ItemService.WritePermission;
/// <inheritdoc />
public override string ExportPermission => ItemService.ReadPermission;
/// <inheritdoc />
public override IReadOnlyList<ImportField> Fields => ItemFields;
/// <inheritdoc />
public override async Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
var state = await LoadAsync(context, ExportPermission, cancellationToken).ConfigureAwait(false);
var rows = new List<IReadOnlyList<object?>>();
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;
}
/// <inheritdoc />
protected override async Task<State> 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<Item, long>().ListAsync(Query.For<Item>(), cancellationToken).ConfigureAwait(false)).Items;
return new State
{
Items = new CodeIndex(all.Select(i => (i.Code, i.Id))),
Categories = await CodeIndex.LoadAsync<ItemCategory>(uow, cancellationToken).ConfigureAwait(false),
Units = await CodeIndex.LoadAsync<UnitOfMeasure>(uow, cancellationToken).ConfigureAwait(false),
TaxCodes = await CodeIndex.LoadAsync<TaxCode>(uow, cancellationToken).ConfigureAwait(false),
Warehouses = await CodeIndex.LoadAsync<Warehouse>(uow, cancellationToken).ConfigureAwait(false),
};
}
/// <inheritdoc />
protected override long? Existing(State state, string code, List<ImportMessage> messages)
{
ArgumentNullException.ThrowIfNull(state);
return state.Items.Find(code);
}
/// <inheritdoc />
protected override async Task<ItemRecord?> 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);
/// <inheritdoc />
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;
}
/// <inheritdoc />
protected override async Task<IReadOnlyList<TableProblem>> 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;
}
/// <inheritdoc />
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);
}
/// <inheritdoc />
protected override string Label(ImportRow row)
{
ArgumentNullException.ThrowIfNull(row);
return row["codice"] ?? row["descrizione"] ?? string.Empty;
}
/// <inheritdoc />
protected override void Remember(State state, string code, long id)
{
ArgumentNullException.ThrowIfNull(state);
state.Items.Add(code, id);
}
/// <inheritdoc />
protected override string ColumnOf(string serviceField) => Columns.GetValueOrDefault(serviceField ?? string.Empty, string.Empty);
private static void Set(CellReader cells, string key, Action<string> 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,
];
/// <summary>What a check or an import of items loads once.</summary>
public sealed class State
{
/// <summary>The items.</summary>
public required CodeIndex Items { get; init; }
/// <summary>The categories.</summary>
public required CodeIndex Categories { get; init; }
/// <summary>The units of measure.</summary>
public required CodeIndex Units { get; init; }
/// <summary>The VAT codes.</summary>
public required CodeIndex TaxCodes { get; init; }
/// <summary>The warehouses.</summary>
public required CodeIndex Warehouses { get; init; }
}
}
@@ -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;
/// <summary>
/// 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 <see cref="PartyService"/>, so the import obeys the rules of the record
/// (fiscal checks, automatic codes, duplicates). Empty cells keep the values of an existing party.
/// </summary>
/// <param name="kind">Customers or suppliers.</param>
/// <param name="parties">The parties.</param>
/// <param name="codes">The automatic codes.</param>
/// <param name="autoFill">The places by postal code.</param>
/// <param name="factory">Opens the company databases (codes of the tables).</param>
/// <param name="permissions">Checks the permission to import.</param>
public sealed class PartiesImportTarget(
PartyKind kind, PartyService parties, CodeRuleService codes, AutoFillService autoFill, IUnitOfWorkFactory factory, PermissionService permissions)
: RecordImportTarget<PartyRecord, PartiesImportTarget.State>
{
/// <summary>The words of <c>tipo_soggetto</c>, in the order of <see cref="SubjectType"/>.</summary>
public static readonly IReadOnlyList<string> 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<string, string> 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",
};
/// <inheritdoc />
public override string Key => kind == PartyKind.Supplier ? "fornitori" : "clienti";
/// <inheritdoc />
public override string ModuleCode => ModuleCodes.Core;
/// <inheritdoc />
public override string Permission => PartyService.WritePermission;
/// <inheritdoc />
public override string ExportPermission => "parties.party.export";
/// <inheritdoc />
public override IReadOnlyList<ImportField> Fields => kind == PartyKind.Supplier ? SupplierFields : CustomerFields;
private bool IsCustomer => kind != PartyKind.Supplier;
/// <inheritdoc />
public override async Task<IReadOnlyList<IReadOnlyList<object?>>> 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<IReadOnlyList<object?>>();
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;
}
/// <inheritdoc />
protected override async Task<State> 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<Party, long>().ListAsync(Query.For<Party>(), 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<PartyCategory>(uow, cancellationToken).ConfigureAwait(false),
Salespeople = await CodeIndex.LoadAsync<Salesperson>(uow, cancellationToken).ConfigureAwait(false),
PaymentTerms = await CodeIndex.LoadAsync<PaymentTerm>(uow, cancellationToken).ConfigureAwait(false),
PriceLists = await CodeIndex.LoadAsync<PriceList>(uow, cancellationToken).ConfigureAwait(false),
};
}
/// <inheritdoc />
protected override long? Existing(State state, string code, List<ImportMessage> 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;
}
/// <inheritdoc />
protected override Task<PartyRecord?> OpenAsync(ImportContext context, long? id, CancellationToken cancellationToken) =>
id is { } key
? parties.GetAsync(context.Actor, context.CompanyCode, key, cancellationToken)
: NewAsync(context, cancellationToken);
/// <inheritdoc />
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);
}
}
/// <inheritdoc />
protected override async Task<IReadOnlyList<TableProblem>> 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;
}
/// <inheritdoc />
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);
}
/// <inheritdoc />
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));
}
/// <inheritdoc />
protected override void Remember(State state, string code, long id)
{
ArgumentNullException.ThrowIfNull(state);
state.Kinds[code] = (id, kind);
}
/// <inheritdoc />
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<string> 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<PartyRecord?> NewAsync(ImportContext context, CancellationToken cancellationToken) =>
await parties.NewAsync(context.Actor, context.CompanyCode, kind, cancellationToken).ConfigureAwait(false);
private async Task<CodeRule> 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));
}
}
}
/// <summary>What a check or an import of parties loads once.</summary>
public sealed class State
{
/// <summary>The id and kind of every party by code.</summary>
public required Dictionary<string, (long Id, PartyKind Kind)> Kinds { get; init; }
/// <summary>The categories.</summary>
public required CodeIndex Categories { get; init; }
/// <summary>The salespeople.</summary>
public required CodeIndex Salespeople { get; init; }
/// <summary>The payment terms.</summary>
public required CodeIndex PaymentTerms { get; init; }
/// <summary>The price lists.</summary>
public required CodeIndex PriceLists { get; init; }
/// <summary>Places found by postal code.</summary>
public Dictionary<string, IReadOnlyList<PlaceSuggestion>> ByPostalCode { get; } = new(StringComparer.Ordinal);
/// <summary>Places found by name.</summary>
public Dictionary<string, IReadOnlyList<PlaceSuggestion>> ByName { get; } = new(StringComparer.Ordinal);
}
}
@@ -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;
/// <summary>
/// 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 <see cref="PriceListService"/> in one transaction.
/// </summary>
/// <param name="prices">The price lists.</param>
/// <param name="factory">Opens the company databases.</param>
/// <param name="permissions">Checks the permission.</param>
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"]),
];
/// <inheritdoc />
public string Key => "listini";
/// <inheritdoc />
public string ModuleCode => ModuleCodes.Core;
/// <inheritdoc />
public string Permission => ItemService.WritePermission;
/// <inheritdoc />
public string ExportPermission => ItemService.ReadPermission;
/// <inheritdoc />
public bool CanApply => true;
/// <inheritdoc />
public bool CanExport => true;
/// <inheritdoc />
public IReadOnlyList<ImportField> Fields => PriceFields;
/// <inheritdoc />
public async Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
(await PlanAsync(context, rows, cancellationToken).ConfigureAwait(false)).Results;
/// <inheritdoc />
public async Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> 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)] })];
}
}
/// <inheritdoc />
public async Task<IReadOnlyList<IReadOnlyList<object?>>> 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<Item, long>().ListAsync(Query.For<Item>(), cancellationToken).ConfigureAwait(false)).Items.Select(i => (i.Code, i.Id)));
var parties = new CodeIndex((await uow.Repository<Party, long>().ListAsync(Query.For<Party>(), cancellationToken).ConfigureAwait(false)).Items.Select(p => (p.Code, p.Id)));
var lists = await CodeIndex.LoadAsync<PriceList>(uow, cancellationToken).ConfigureAwait(false);
var rows = (await uow.Repository<ItemPrice, long>().ListAsync(Query.For<ItemPrice>(), cancellationToken).ConfigureAwait(false)).Items;
return
[
.. rows.Select(p => (IReadOnlyList<object?>)[items.CodeOf(p.ItemId), lists.CodeOf(p.PriceListId), parties.CodeOf(p.PartyId), p.Price, p.ValidFrom])
.OrderBy(r => (string?)r[0], StringComparer.OrdinalIgnoreCase)
.ThenBy(r => (string?)r[1] ?? "~" + (string?)r[2], StringComparer.OrdinalIgnoreCase)
.ThenBy(r => (DateOnly?)r[4]),
];
}
private async Task<Plan> PlanAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(rows);
var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var items = new CodeIndex((await uow.Repository<Item, long>().ListAsync(Query.For<Item>(), cancellationToken).ConfigureAwait(false)).Items.Select(i => (i.Code, i.Id)));
var allParties = (await uow.Repository<Party, long>().ListAsync(Query.For<Party>(), cancellationToken).ConfigureAwait(false)).Items;
var customers = new CodeIndex(allParties.Where(p => p.IsCustomer).Select(p => (p.Code, p.Id)));
var others = new HashSet<string>(allParties.Where(p => !p.IsCustomer).Select(p => p.Code), StringComparer.OrdinalIgnoreCase);
var lists = await CodeIndex.LoadAsync<PriceList>(uow, cancellationToken).ConfigureAwait(false);
var existing = (await uow.Repository<ItemPrice, long>().ListAsync(Query.For<ItemPrice>(), cancellationToken).ConfigureAwait(false)).Items
.Select(p => (p.ItemId, p.PriceListId, p.PartyId, p.ValidFrom)).ToHashSet();
var seen = new HashSet<(long, long?, long?, DateOnly?)>();
var results = new List<ImportRowResult>(rows.Count);
var edits = new List<(PriceEdit Edit, int Result)>();
foreach (var row in rows)
{
var messages = new List<ImportMessage>();
var cells = new CellReader(row, messages);
var item = cells.Code("articolo", items);
long? list = null;
long? party = null;
if (cells.Has("listino") == cells.Has("cliente"))
{
messages.Add(new(cells.Has("listino") ? "cliente" : "listino", ImportErrors.PriceTarget));
}
else if (cells.Has("listino"))
{
list = cells.Code("listino", lists);
}
else if (row["cliente"] is { } customer && others.Contains(customer))
{
messages.Add(new("cliente", ImportErrors.OtherKind, Value: customer));
}
else
{
party = cells.Code("cliente", customers);
}
var price = cells.Number("prezzo");
if (price < 0)
{
messages.Add(new("prezzo", ItemService.NotNegative));
}
var from = cells.Date("valido_dal");
messages.AddRange(PriceFields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required)));
var label = row["articolo"] ?? string.Empty;
if (messages.Any(m => !m.IsWarning) || item is not { } itemId || price is not { } value)
{
results.Add(new(row.Line, label, ImportAction.Skip, messages));
continue;
}
var key = (itemId, list, party, from);
if (!seen.Add(key))
{
messages.Add(new("articolo", ImportErrors.CodeRepeated, Value: label));
results.Add(new(row.Line, label, ImportAction.Skip, messages));
continue;
}
var update = existing.Contains(key);
if (update && context.Options.Existing == ExistingCodeAction.Skip)
{
results.Add(new(row.Line, label, ImportAction.Skip, [new("articolo", ImportErrors.CodeExists, IsWarning: true, Value: label)]));
continue;
}
edits.Add((new PriceEdit(itemId, list, party, value, from), results.Count));
results.Add(new(row.Line, label, update ? ImportAction.Update : ImportAction.Create, messages));
}
return new Plan(results, edits);
}
private sealed record Plan(IReadOnlyList<ImportRowResult> Results, IReadOnlyList<(PriceEdit Edit, int Result)> Edits);
}
@@ -362,7 +362,19 @@ public sealed class PartyService
/// <returns>The saved record, read back.</returns>
/// <exception cref="ValidationFailedException">A rule failed; errors are <c>Field:code</c>.</exception>
/// <exception cref="Core.Common.ConcurrencyException">Someone else changed the party meanwhile.</exception>
public async Task<PartyRecord> SaveAsync(Actor actor, string companyCode, PartyRecord record, CancellationToken cancellationToken = default)
public Task<PartyRecord> SaveAsync(Actor actor, string companyCode, PartyRecord record, CancellationToken cancellationToken = default) =>
SaveAsync(actor, companyCode, record, null, cancellationToken);
/// <summary>Saves a party with its details, choosing whether to check an EU VAT number on VIES (the import asks it in its options).</summary>
/// <param name="actor">Who saves.</param>
/// <param name="companyCode">The company.</param>
/// <param name="record">The record.</param>
/// <param name="verifyVat">Check on VIES; <see langword="null"/>: as the automatic filling option of the company says.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The saved record, read back.</returns>
/// <exception cref="ValidationFailedException">A rule failed; errors are <c>Field:code</c>.</exception>
/// <exception cref="Core.Common.ConcurrencyException">Someone else changed the party meanwhile.</exception>
public async Task<PartyRecord> SaveAsync(Actor actor, string companyCode, PartyRecord record, bool? verifyVat, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(record);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
@@ -399,7 +411,7 @@ public sealed class PartyService
if (party.SubjectType == SubjectType.EuCompany && party.VatNumber is { Length: > 0 }
&& (before is null || before.Party.VatNumber != party.VatNumber || before.Party.CountryCode != party.CountryCode || before.Party.VatCheck == VatCheckStatus.None)
&& await _autoFill.IsOnAsync(company, AutoFillService.Vies, cancellationToken).ConfigureAwait(false))
&& (verifyVat ?? await _autoFill.IsOnAsync(company, AutoFillService.Vies, cancellationToken).ConfigureAwait(false)))
{
await CheckVatCoreAsync(company, id, actor.UserName, cancellationToken).ConfigureAwait(false);
}
@@ -0,0 +1,26 @@
namespace Khaemhat.Core.Accounting;
/// <summary>What a ledger account is used for, beyond its nature: the accounts the automatic postings look for.</summary>
public enum AccountType
{
/// <summary>Any other account.</summary>
Generic = 0,
/// <summary>The customers control account, with a sub-ledger per customer.</summary>
Customers = 1,
/// <summary>The suppliers control account, with a sub-ledger per supplier.</summary>
Suppliers = 2,
/// <summary>A bank account.</summary>
Bank = 3,
/// <summary>Cash.</summary>
Cash = 4,
/// <summary>VAT on sales or purchases, or the VAT settlement.</summary>
Vat = 5,
/// <summary>Amounts due to or from the tax authority (withholdings, taxes).</summary>
Tax = 6,
}
@@ -0,0 +1,414 @@
using System.Globalization;
using System.IO.Compression;
using System.Xml;
namespace Khaemhat.Infrastructure.Files;
/// <summary>A spreadsheet that cannot be read: not an Office Open XML workbook, damaged, or too large.</summary>
public sealed class XlsxReadException : Exception
{
/// <summary>Creates the exception.</summary>
public XlsxReadException()
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">What went wrong.</param>
public XlsxReadException(string message)
: base(message)
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">What went wrong.</param>
/// <param name="innerException">The cause.</param>
public XlsxReadException(string message, Exception innerException)
: base(message, innerException)
{
}
}
/// <summary>
/// Reads the first sheet of an Office Open XML workbook (<c>.xlsx</c>, SPEC §12.12) with <see cref="ZipArchive"/> and
/// <see cref="XmlReader"/>: shared, inline and formula strings, numbers as written in the file (invariant culture),
/// booleans as <c>true</c>/<c>false</c>, and numbers with a date format as ISO dates (<c>yyyy-MM-dd</c>). Empty cells in
/// the middle of a row are kept by their column letter; empty rows are skipped. Formulas are not computed: the cached
/// value saved by the spreadsheet is read.
/// </summary>
public static class XlsxReader
{
/// <summary>The largest uncompressed part read, against archives that expand to fill the memory.</summary>
public const long MaxPartBytes = 256L * 1024 * 1024;
private const string RelationshipNamespace = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
// The built-in number formats that show a date (ECMA-376 §18.8.30).
private static readonly HashSet<int> DateFormats = [14, 15, 16, 17, 18, 19, 20, 21, 22, 27, 30, 36, 45, 46, 47, 50, 57];
private static readonly DateTime Epoch = new(1899, 12, 30, 0, 0, 0, DateTimeKind.Unspecified);
/// <summary>Reads the rows of the first sheet.</summary>
/// <param name="content">The workbook; it is copied to memory when not seekable.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows, each with its cells from column A.</returns>
/// <exception cref="XlsxReadException">The file is not a readable workbook.</exception>
public static async Task<IReadOnlyList<IReadOnlyList<string>>> ReadAsync(Stream content, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(content);
var source = content;
MemoryStream? copy = null;
if (!content.CanSeek)
{
copy = new MemoryStream();
await content.CopyToAsync(copy, cancellationToken).ConfigureAwait(false);
copy.Position = 0;
source = copy;
}
try
{
using var zip = new ZipArchive(source, ZipArchiveMode.Read, leaveOpen: true);
var sheetPath = FirstSheetPath(zip);
var strings = SharedStrings(zip);
var dateStyles = DateStyles(zip);
var sheet = zip.GetEntry(sheetPath) ?? throw new XlsxReadException("The first sheet is missing: " + sheetPath);
return ReadSheet(sheet, strings, dateStyles, cancellationToken);
}
catch (InvalidDataException ex)
{
throw new XlsxReadException("Not a workbook.", ex);
}
catch (XmlException ex)
{
throw new XlsxReadException("A part of the workbook is not valid XML.", ex);
}
finally
{
if (copy is not null)
{
await copy.DisposeAsync().ConfigureAwait(false);
}
}
}
/// <summary>The zero-based column of a cell reference such as <c>AB12</c>.</summary>
/// <param name="reference">The reference.</param>
/// <returns>The column, or -1 when the reference has no letters.</returns>
public static int ColumnOf(string? reference)
{
if (string.IsNullOrEmpty(reference))
{
return -1;
}
var column = 0;
var letters = 0;
foreach (var c in reference)
{
if (!char.IsAsciiLetter(c))
{
break;
}
column = (column * 26) + (char.ToUpperInvariant(c) - 'A' + 1);
letters++;
}
return letters == 0 ? -1 : column - 1;
}
private static XmlReader Open(ZipArchiveEntry entry)
{
if (entry.Length > MaxPartBytes)
{
throw new XlsxReadException("A part of the workbook is too large: " + entry.FullName);
}
return XmlReader.Create(entry.Open(), new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null, IgnoreWhitespace = false });
}
private static string FirstSheetPath(ZipArchive zip)
{
var workbook = zip.GetEntry("xl/workbook.xml") ?? throw new XlsxReadException("xl/workbook.xml is missing.");
string? relationship = null;
using (var reader = Open(workbook))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "sheet")
{
relationship = reader.GetAttribute("id", RelationshipNamespace);
break;
}
}
}
if (relationship is null)
{
throw new XlsxReadException("The workbook has no sheet.");
}
var rels = zip.GetEntry("xl/_rels/workbook.xml.rels");
if (rels is not null)
{
using var reader = Open(rels);
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "Relationship" && reader.GetAttribute("Id") == relationship
&& reader.GetAttribute("Target") is { } target)
{
target = target.Replace('\\', '/');
return target.StartsWith('/') ? target.TrimStart('/') : "xl/" + target;
}
}
}
return "xl/worksheets/sheet1.xml";
}
private static List<string> SharedStrings(ZipArchive zip)
{
var strings = new List<string>();
var entry = zip.GetEntry("xl/sharedStrings.xml");
if (entry is null)
{
return strings;
}
using var reader = Open(entry);
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "si")
{
strings.Add(ReadText(reader));
}
}
return strings;
}
// The concatenated <t> of an <si> or <is> element, without the phonetic runs; the reader ends on its end tag.
private static string ReadText(XmlReader reader)
{
if (reader.IsEmptyElement)
{
return string.Empty;
}
var depth = reader.Depth;
var text = new System.Text.StringBuilder();
var skip = -1;
while (reader.Read() && !(reader.NodeType == XmlNodeType.EndElement && reader.Depth == depth))
{
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "rPh" && !reader.IsEmptyElement)
{
skip = reader.Depth;
}
else if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == skip)
{
skip = -1;
}
else if (skip < 0 && reader.NodeType == XmlNodeType.Element && reader.LocalName == "t" && !reader.IsEmptyElement)
{
text.Append(reader.ReadElementContentAsString());
if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == depth)
{
break;
}
}
}
return text.ToString();
}
// The indexes of the cell styles (cellXfs) whose number format shows a date.
private static HashSet<int> DateStyles(ZipArchive zip)
{
var styles = new HashSet<int>();
var entry = zip.GetEntry("xl/styles.xml");
if (entry is null)
{
return styles;
}
var custom = new HashSet<int>();
using var reader = Open(entry);
var inCellXfs = false;
var index = 0;
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "numFmt"
&& int.TryParse(reader.GetAttribute("numFmtId"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var id)
&& IsDateFormat(reader.GetAttribute("formatCode")))
{
custom.Add(id);
}
else if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "cellXfs")
{
inCellXfs = !reader.IsEmptyElement;
}
else if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "cellXfs")
{
inCellXfs = false;
}
else if (inCellXfs && reader.NodeType == XmlNodeType.Element && reader.LocalName == "xf")
{
if (int.TryParse(reader.GetAttribute("numFmtId"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var format)
&& (DateFormats.Contains(format) || custom.Contains(format)))
{
styles.Add(index);
}
index++;
}
}
return styles;
}
// A custom format shows a date when, outside quoted text and brackets, it has a day, month or year code.
private static bool IsDateFormat(string? code)
{
if (string.IsNullOrEmpty(code))
{
return false;
}
var quoted = false;
var bracket = false;
foreach (var c in code)
{
switch (c)
{
case '"':
quoted = !quoted;
break;
case '[' when !quoted:
bracket = true;
break;
case ']' when !quoted:
bracket = false;
break;
case 'd' or 'D' or 'y' or 'Y' or 'm' or 'M' when !quoted && !bracket:
return true;
}
}
return false;
}
private static List<IReadOnlyList<string>> ReadSheet(ZipArchiveEntry sheet, List<string> strings, HashSet<int> dateStyles, CancellationToken cancellationToken)
{
var rows = new List<IReadOnlyList<string>>();
using var reader = Open(sheet);
List<string>? row = null;
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "row")
{
cancellationToken.ThrowIfCancellationRequested();
row = [];
if (reader.IsEmptyElement)
{
row = null;
}
}
else if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "row" && row is not null)
{
while (row.Count > 0 && row[^1].Length == 0)
{
row.RemoveAt(row.Count - 1);
}
if (row.Count > 0)
{
rows.Add(row);
}
row = null;
}
else if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "c" && row is not null)
{
var column = ColumnOf(reader.GetAttribute("r"));
var type = reader.GetAttribute("t");
var style = int.TryParse(reader.GetAttribute("s"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var s) ? s : -1;
var value = reader.IsEmptyElement ? string.Empty : ReadCell(reader, type, strings, dateStyles.Contains(style));
if (column < 0)
{
column = row.Count;
}
while (row.Count < column)
{
row.Add(string.Empty);
}
if (row.Count == column)
{
row.Add(value);
}
else
{
row[column] = value;
}
}
}
return rows;
}
// The value of a <c> element; the reader ends on its end tag.
private static string ReadCell(XmlReader reader, string? type, List<string> strings, bool date)
{
var depth = reader.Depth;
string? raw = null;
string? inline = null;
while (reader.Read() && !(reader.NodeType == XmlNodeType.EndElement && reader.Depth == depth))
{
if (reader.NodeType != XmlNodeType.Element)
{
continue;
}
if (reader.LocalName == "v" && !reader.IsEmptyElement)
{
raw = reader.ReadElementContentAsString();
if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == depth)
{
break;
}
}
else if (reader.LocalName == "is")
{
inline = ReadText(reader);
}
}
return type switch
{
"inlineStr" => inline ?? string.Empty,
"s" => int.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out var index) && index >= 0 && index < strings.Count ? strings[index] : string.Empty,
"b" => raw == "1" ? "true" : "false",
"str" or "e" => raw ?? string.Empty,
_ => Number(raw, date),
};
}
private static string Number(string? raw, bool date)
{
if (string.IsNullOrEmpty(raw))
{
return string.Empty;
}
if (date && double.TryParse(raw, NumberStyles.Float, CultureInfo.InvariantCulture, out var serial) && serial is > 0 and < 2958466)
{
var day = Epoch.AddDays(Math.Floor(serial));
return day.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
}
return decimal.TryParse(raw, NumberStyles.Float, CultureInfo.InvariantCulture, out var number)
? number.ToString(CultureInfo.InvariantCulture)
: raw;
}
}
@@ -0,0 +1,231 @@
@page "/amministrazione/import-export"
@attribute [Authorize]
@using Khaemhat.Application.ImportExport
@inject ShellSession Session
@inject ImportService Imports
@inject ToastService Toasts
@inject DialogService Dialogs
@inject IJSRuntime JS
@* The guided import and export (SPEC §11.7, §12.12, mockup 077, ADR 0031): entity and file, mapping of the columns,
check of every row as if typed in its record, import of the rows without errors; on the side, the export with the
same columns and the empty templates. *@
<KhPageTitle Text="@T["ImportExport.Title"]" Icon="upload" />
@if (Session.Company is null)
{
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["ImportExport.NoCompany"]</h1></div>
}
else if (Targets.Count == 0)
{
<div class="kh-message">
<KhIcon Name="lock" Class="lg" />
<h1>@T["Pages.AccessDenied.Title"]</h1>
<p class="lead">@T["ImportExport.NoTargets"]</p>
</div>
}
else
{
<div class="kh-import">
<div class="kh-import-side">
<KhPanel Title="@T["ImportExport.Wizard"]" Icon="upload">
<KhVSteps Items="Steps" Current="_step" Label="@T["ImportExport.Steps.Label"]" />
<div class="kh-import-options">
<KhSelect TValue="string" Label="@T["ImportExport.Target"]" Name="target" Options="TargetChoices" Value="_targetKey" ValueChanged="SetTargetAsync"
Span="12" Disabled="_busy" />
@if (IsRecordTarget)
{
<KhSelect TValue="ExistingCodeAction" Label="@T["ImportExport.Existing"]" Name="existing" Options="ExistingChoices" Value="_options.Existing"
ValueChanged="SetExisting" Span="6" Disabled="_busy" />
<KhSelect TValue="MissingCodeAction" Label="@T["ImportExport.Missing"]" Name="missing" Options="MissingChoices" Value="_options.Missing"
ValueChanged="SetMissing" Span="6" Disabled="_busy" />
}
else if (IsPrices)
{
<KhSelect TValue="ExistingCodeAction" Label="@T["ImportExport.Existing"]" Name="existing" Options="ExistingChoices" Value="_options.Existing"
ValueChanged="SetExisting" Span="12" Disabled="_busy" />
}
@if (IsParties)
{
<KhCheck Label="@T["ImportExport.VerifyVat"]" Name="vies" Value="_options.VerifyVat" ValueChanged="SetVerifyVat" Span="12" Disabled="_busy" />
<KhCheck Label="@T["ImportExport.FillFromPostalCode"]" Name="cap" Value="_options.FillFromPostalCode" ValueChanged="SetFillFromPostalCode" Span="12"
Disabled="_busy" />
}
<div class="f c12">
<label for="kh-import-file">@T["ImportExport.File"]</label>
<InputFile id="kh-import-file" class="in" OnChange="ReadAsync" accept=".csv,.txt,.xlsx,.json" disabled="@_busy" />
<span class="hint">@T["ImportExport.FileHint"]</span>
</div>
</div>
</KhPanel>
<KhPanel Title="@T["ImportExport.Export.Title"]" Icon="download">
<p class="muted kh-import-lead">@T["ImportExport.Export.Lead"]</p>
<div class="kh-seg" role="radiogroup" aria-label="@T["ImportExport.Export.Format"]">
@foreach (var format in Formats)
{
<button type="button" role="radio" class="@(_format == format ? "on" : null)" aria-checked="@(_format == format ? "true" : "false")"
@onclick="() => _format = format">@FormatName(format)</button>
}
</div>
<div class="kh-import-actions">
<button type="button" class="btn" disabled="@_busy" @onclick="TemplateAsync"><KhIcon Name="file" /> @T["ImportExport.Export.Template"]</button>
<button type="button" class="btn" disabled="@(_busy || !CanExport)" title="@ExportHint" @onclick="ExportAsync"><KhIcon Name="download" /> @T["ImportExport.Export.Run"]</button>
</div>
</KhPanel>
</div>
<div class="kh-import-main">
@if (_file is null)
{
<KhPanel Title="@T["ImportExport.Formats.Title"]" Icon="info">
<p class="kh-import-lead">@T["ImportExport.Formats.Lead"]</p>
<ul class="kh-import-list">
<li>@T["ImportExport.Formats.Csv"]</li>
<li>@T["ImportExport.Formats.Xlsx"]</li>
<li>@T["ImportExport.Formats.Json"]</li>
</ul>
@if (!Target.CanApply)
{
<div class="callout info"><KhIcon Name="info" /> <span>@T.Format("ImportExport.Formats.CheckOnly", CheckOnlyMilestone)</span></div>
}
<h3 class="kh-import-h">@T.Format("ImportExport.Formats.Columns", TargetName(Target.Key))</h3>
<div class="kh-import-chips">
@foreach (var field in Target.Fields)
{
<span class="chip @(field.Required ? null : "soft")" title="@FieldName(field.Key)"><span class="mono">@field.Key</span>@RequiredMark(field)</span>
}
</div>
</KhPanel>
}
else if (_step == 1)
{
<KhPanel Title="@T["ImportExport.Mapping.Title"]" Icon="columns" Tight="true">
<Actions>
<button type="button" class="btn" disabled="@_busy" @onclick="ChangeFile"><KhIcon Name="x" /> @T["ImportExport.Mapping.ChangeFile"]</button>
<button type="button" class="btn primary" disabled="@_busy" @onclick="CheckAsync"><KhIcon Name="check" /> @T["ImportExport.Mapping.Check"]</button>
</Actions>
<ChildContent>
<p class="muted kh-pad">@T["ImportExport.Mapping.Lead"]</p>
@if (MissingRequired.Count > 0)
{
<div class="callout warn kh-import-callout"><KhIcon Name="alert" /> <span>@T.Format("ImportExport.Mapping.RequiredMissing", string.Join(", ", MissingRequired))</span></div>
}
@if (_file.Sections is { Count: > 0 } sections)
{
<div class="callout info kh-import-callout"><KhIcon Name="info" /> <span>@T.Format("ImportExport.Mapping.Sections", SectionsText(sections))</span></div>
}
<table class="grid kh-import-map" aria-label="@T["ImportExport.Mapping.Title"]">
<thead>
<tr>
<th>@T["ImportExport.Mapping.Header"]</th>
<th>@T["ImportExport.Mapping.Sample"]</th>
<th>@T["ImportExport.Mapping.Field"]</th>
</tr>
</thead>
<tbody>
@for (var i = 0; i < _file.Headers.Count; i++)
{
var column = i;
<tr>
<td><b>@_file.Headers[column]</b></td>
<td class="muted">@Sample(column)</td>
<td>
<select class="in" aria-label="@_file.Headers[column]" @onchange="e => SetMapping(column, e.Value as string)">
<option value="" selected="@(_mapping[column] is null)">@T["ImportExport.Mapping.Ignore"]</option>
@foreach (var field in Target.Fields)
{
<option value="@field.Key" selected="@(_mapping[column] == field.Key)">@FieldName(field.Key)@RequiredMark(field)</option>
}
</select>
</td>
</tr>
}
</tbody>
</table>
</ChildContent>
</KhPanel>
}
else if (_preview is { } preview)
{
<KhPanel Title="@PreviewTitle" Icon="check" Tight="true">
<Actions>
<div class="kh-seg" role="radiogroup" aria-label="@T["ImportExport.Preview.Title"]">
<button type="button" role="radio" class="@(_onlyProblems ? null : "on")" aria-checked="@(_onlyProblems ? "false" : "true")"
@onclick="() => _onlyProblems = false">@T["ImportExport.Preview.All"]</button>
<button type="button" role="radio" class="@(_onlyProblems ? "on" : null)" aria-checked="@(_onlyProblems ? "true" : "false")"
@onclick="() => _onlyProblems = true">@T["ImportExport.Preview.Problems"]</button>
</div>
@if (_report is null)
{
<button type="button" class="btn" disabled="@_busy" @onclick="BackToMapping"><KhIcon Name="columns" /> @T["ImportExport.Preview.Back"]</button>
}
<button type="button" class="btn" disabled="@(_busy || !HasProblems)" @onclick="ReportAsync"><KhIcon Name="download" /> @T["ImportExport.Preview.Report"]</button>
@if (_report is null)
{
<button type="button" class="btn primary" disabled="@(_busy || !preview.CanApply || preview.Importable == 0)" @onclick="ImportAsync">
<KhIcon Name="upload" /> @ImportLabel(preview.Importable)
</button>
}
else
{
<button type="button" class="btn primary" disabled="@_busy" @onclick="ChangeFile"><KhIcon Name="plus" /> @T["ImportExport.Done.Again"]</button>
}
</Actions>
<ChildContent>
@if (_report is { } report)
{
<div class="callout ok kh-import-callout">
<KhIcon Name="check" />
<span><b>@T["ImportExport.Done.Title"]</b> · @T.Format("ImportExport.Done.Lead", TargetName(report.Target), report.Created, report.Updated, report.Skipped, report.Failed)</span>
</div>
}
else if (!preview.CanApply)
{
<div class="callout info kh-import-callout"><KhIcon Name="info" /> <span>@T.Format("ImportExport.Formats.CheckOnly", CheckOnlyMilestone)</span></div>
}
@if (VisibleRows.Count == 0)
{
<p class="muted kh-pad">@T["ImportExport.Preview.NoRows"]</p>
}
else
{
<table class="grid kh-import-preview" aria-label="@T["ImportExport.Preview.Title"]">
<thead>
<tr>
<th class="num">@T["ImportExport.Preview.Line"]</th>
@foreach (var key in PreviewFields)
{
<th>@FieldName(key)</th>
}
<th>@T["ImportExport.Preview.Outcome"]</th>
</tr>
</thead>
<tbody>
@foreach (var row in VisibleRows)
{
var cells = CellsOf(row.Line);
<tr class="@RowClass(row)">
<td class="num muted">@row.Line</td>
@foreach (var key in PreviewFields)
{
<td class="@CellClass(row, key)">@CellOf(row, cells, key)</td>
}
<td class="kh-import-outcome">
<KhBadge Tone="ToneOf(row)">@OutcomeText(row)</KhBadge>
@foreach (var message in row.Messages)
{
<span class="kh-import-msg @(message.IsWarning ? "warn" : "err")">@MessageText(message)</span>
}
</td>
</tr>
}
</tbody>
</table>
}
</ChildContent>
</KhPanel>
}
</div>
</div>
}
@@ -0,0 +1,391 @@
using Khaemhat.Application.ImportExport;
using Khaemhat.Application.Security;
using Khaemhat.Web.Shell;
using Khaemhat.Web.Ui;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.JSInterop;
namespace Khaemhat.Web.Components.Pages.Admin;
/// <summary>The state and the actions of the guided import and export (mockup 077).</summary>
public partial class ImportExportPage
{
/// <summary>The largest file accepted, in megabytes.</summary>
public const int MaxMegabytes = 25;
private const int MaxPreviewRows = 500;
private const int MaxPreviewFields = 6;
private static readonly TransferFormat[] Formats = [TransferFormat.Csv, TransferFormat.Xlsx, TransferFormat.Json];
private ImportOptions _options = new();
private string _targetKey = "clienti";
private TransferFormat _format = TransferFormat.Csv;
private ImportFile? _file;
private long _fileBytes;
private string?[] _mapping = [];
private Dictionary<int, ImportRow> _rows = [];
private ImportPreview? _preview;
private ImportReport? _report;
private bool _onlyProblems;
private bool _busy;
private int _step;
private IReadOnlyList<IImportTarget> Targets =>
[.. Imports.Targets.Where(t => Session.Permissions.Allows(t.Permission) || Session.Permissions.Allows(t.ExportPermission))];
private IImportTarget Target => Targets.FirstOrDefault(t => t.Key == _targetKey) ?? Targets[0];
private bool IsParties => Target is PartiesImportTarget;
private bool IsRecordTarget => Target is PartiesImportTarget or ItemsImportTarget;
private bool IsPrices => Target is PricesImportTarget;
private bool CanExport => Target.CanExport && Session.Permissions.Flags.CanExport && Session.Permissions.Allows(Target.ExportPermission);
private string? ExportHint => !Target.CanExport ? T["ImportExport.Export.Nothing"] : !Session.Permissions.Flags.CanExport ? T["ImportExport.Export.NotAllowed"] : null;
private string CheckOnlyMilestone => Target is ChartOfAccountsImportTarget ? "M7" : "M6";
private IReadOnlyList<KhOption<string>> TargetChoices => [.. Targets.Select(t => new KhOption<string>(t.Key, TargetName(t.Key)))];
private IReadOnlyList<KhOption<ExistingCodeAction>> ExistingChoices =>
[.. Enum.GetValues<ExistingCodeAction>().Select(v => new KhOption<ExistingCodeAction>(v, T["ImportExport.ExistingChoices." + v]))];
private IReadOnlyList<KhOption<MissingCodeAction>> MissingChoices =>
[.. Enum.GetValues<MissingCodeAction>().Select(v => new KhOption<MissingCodeAction>(v, T["ImportExport.MissingChoices." + v]))];
private IReadOnlyList<KhStep> Steps
{
get
{
var preview = _preview;
return
[
new(T["ImportExport.Steps.Origin"], _file is { } file
? T.Format("ImportExport.Steps.OriginDetail", file.Name, file.Count.ToString("N0", T.Culture), Size(_fileBytes))
: T["ImportExport.Steps.OriginEmpty"]),
new(T["ImportExport.Steps.Mapping"], _file is { } mapped
? T.Format("ImportExport.Steps.MappingDetail", _mapping.Count(m => m is not null), mapped.Headers.Count)
: T["ImportExport.Steps.MappingEmpty"]),
new(T["ImportExport.Steps.Check"], preview is null
? T["ImportExport.Steps.CheckEmpty"]
: T.Format("ImportExport.Steps.CheckDetail", Number(preview.Rows.Count - preview.Errors - preview.Warnings), Number(preview.Warnings), Number(preview.Errors))),
new(T["ImportExport.Steps.Import"], _report is { } report
? T.Format("ImportExport.Steps.ImportDone", Number(report.Created), Number(report.Updated))
: preview is null ? T["ImportExport.Steps.ImportEmpty"]
: preview.CanApply ? T.Format("ImportExport.Steps.ImportReady", Number(preview.Importable))
: T["ImportExport.Steps.ImportCheckOnly"]),
];
}
}
private IReadOnlyList<string> MissingRequired =>
[.. Target.Fields.Where(f => f.Required && !_mapping.Contains(f.Key)).Select(f => FieldName(f.Key))];
// The first mapped columns, then the columns that have a remark somewhere, so that every remark is next to its cell.
private IReadOnlyList<string> PreviewFields
{
get
{
var mapped = Target.Fields.Select(f => f.Key).Where(k => _mapping.Contains(k)).ToList();
var remarked = AllRows.SelectMany(r => r.Messages).Select(m => m.Field).ToHashSet(StringComparer.Ordinal);
var shown = mapped.Take(MaxPreviewFields).ToHashSet(StringComparer.Ordinal);
shown.UnionWith(mapped.Where(remarked.Contains).Take(MaxPreviewFields));
return [.. mapped.Where(shown.Contains)];
}
}
private bool HasProblems => (_report?.Rows ?? _preview?.Rows ?? []).Any(r => r.Messages.Count > 0);
private IReadOnlyList<ImportRowResult> AllRows => _report?.Rows ?? _preview?.Rows ?? [];
private IReadOnlyList<ImportRowResult> VisibleRows =>
[.. AllRows.Where(r => !_onlyProblems || r.Messages.Count > 0).Take(MaxPreviewRows)];
private string PreviewTitle
{
get
{
var total = AllRows.Count(r => !_onlyProblems || r.Messages.Count > 0);
return total > MaxPreviewRows
? T.Format("ImportExport.Preview.Subtitle", Number(MaxPreviewRows), Number(total))
: T.Format("ImportExport.Preview.SubtitleAll", Number(total));
}
}
private string TargetName(string key) => T["ImportExport.Targets." + key];
private string FieldName(string key) => T.Contains("ImportExport.Fields." + key) ? T["ImportExport.Fields." + key] : key;
private static string RequiredMark(ImportField field) => field.Required ? " *" : string.Empty;
private static string FormatName(TransferFormat format) => format.ToString().ToUpperInvariant();
private string Number(int value) => value.ToString("N0", T.Culture);
private string Size(long bytes) => bytes >= 1024 * 1024
? (bytes / 1024d / 1024d).ToString("0.0", T.Culture) + " MB"
: Math.Max(1, (bytes + 512) / 1024).ToString(T.Culture) + " KB";
private string ImportLabel(int rows) => rows == 1 ? T["ImportExport.Preview.ImportOne"] : T.Format("ImportExport.Preview.Import", Number(rows));
private string SectionsText(IReadOnlyDictionary<string, int> sections) =>
string.Join(", ", sections.Select(s => s.Key + " (" + Number(s.Value) + ")"));
private string? Sample(int column) => _file is { Count: > 0 } file && column < file.Rows[0].Count ? file.Rows[0][column] : null;
private IReadOnlyDictionary<string, string>? CellsOf(int line) => _rows.TryGetValue(line, out var row) ? row.Values : null;
// The cell of the file, or the value the check proposes for it (the city from the postal code).
private static string? CellOf(ImportRowResult row, IReadOnlyDictionary<string, string>? cells, string key) =>
cells?.GetValueOrDefault(key) ?? row.Messages.FirstOrDefault(m => m.Field == key && m.IsWarning && m.Value is not null)?.Value;
private static string? RowClass(ImportRowResult row) => row.Outcome switch
{
ImportOutcome.Error => "kh-import-err",
ImportOutcome.Warning => "kh-import-warn",
_ => null,
};
private static string? CellClass(ImportRowResult row, string key) =>
row.Messages.FirstOrDefault(m => m.Field == key) is { } message ? (message.IsWarning ? "kh-import-cell-warn" : "kh-import-cell-err") : null;
private static KhTone ToneOf(ImportRowResult row) => row.Outcome switch
{
ImportOutcome.Error => KhTone.Error,
ImportOutcome.Warning => KhTone.Warning,
_ => row.Action == ImportAction.Skip ? KhTone.Neutral : KhTone.Ok,
};
private string OutcomeText(ImportRowResult row) => row.Outcome switch
{
ImportOutcome.Error => T["ImportExport.Preview.Error"],
ImportOutcome.Warning when row.Messages.Count == 1 => T["ImportExport.Preview.Warning"],
ImportOutcome.Warning => T.Format("ImportExport.Preview.Warnings", row.Messages.Count),
_ => T["ImportExport.Preview." + row.Action],
};
private string MessageText(ImportMessage message)
{
var text = !T.Contains(message.Code) ? message.Code
: message.Value is null ? T[message.Code]
: T.Format(message.Code, message.Value);
return message.Field.Length == 0 ? text : T.Format("ImportExport.MessageField", FieldName(message.Field), text);
}
private void Reset()
{
_file = null;
_fileBytes = 0;
_mapping = [];
_rows = [];
_preview = null;
_report = null;
_onlyProblems = false;
_step = 0;
}
private Task SetTargetAsync(string? key)
{
_targetKey = key ?? Targets[0].Key;
_options = new ImportOptions();
if (_file is { } file)
{
_mapping = [.. ImportService.SuggestMapping(Target, file.Headers)];
_preview = null;
_report = null;
_step = 1;
}
return Task.CompletedTask;
}
private void SetExisting(ExistingCodeAction value) => _options = _options with { Existing = value };
private void SetMissing(MissingCodeAction value) => _options = _options with { Missing = value };
private void SetVerifyVat(bool value) => _options = _options with { VerifyVat = value };
private void SetFillFromPostalCode(bool value) => _options = _options with { FillFromPostalCode = value };
private void SetMapping(int column, string? key)
{
var field = string.IsNullOrEmpty(key) ? null : key;
if (field is not null)
{
// A field goes to one column only: the column that had it loses it.
for (var i = 0; i < _mapping.Length; i++)
{
if (i != column && _mapping[i] == field)
{
_mapping[i] = null;
}
}
}
_mapping[column] = field;
_preview = null;
}
private void ChangeFile() => Reset();
private void BackToMapping()
{
_preview = null;
_report = null;
_step = 1;
}
private async Task ReadAsync(InputFileChangeEventArgs e)
{
Reset();
if (e.File.Size > MaxMegabytes * 1024L * 1024L)
{
Toasts.Show(ToastKind.Error, e.File.Name, T.Format("ImportExport.TooLarge", MaxMegabytes));
return;
}
_busy = true;
try
{
await using var source = e.File.OpenReadStream(MaxMegabytes * 1024L * 1024L);
var file = await ImportFileReader.ReadAsync(e.File.Name, source);
_file = file;
_fileBytes = e.File.Size;
_mapping = [.. ImportService.SuggestMapping(Target, file.Headers)];
_step = 1;
}
catch (ImportFileException ex)
{
Toasts.Show(ToastKind.Error, e.File.Name, T[ex.Code]);
}
catch (IOException ex)
{
Toasts.Show(ToastKind.Error, e.File.Name, ex.Message);
}
finally
{
_busy = false;
}
}
private async Task CheckAsync()
{
if (Session.Actor is not { } actor || Session.Company is not { } company || _file is not { } file)
{
return;
}
_busy = true;
try
{
_rows = ImportService.Rows(file, _mapping).ToDictionary(r => r.Line);
_preview = await Imports.PreviewAsync(actor, company.Code, Target.Key, file, _mapping, _options);
_report = null;
_onlyProblems = _preview.Errors + _preview.Warnings > 0 && _preview.Rows.Count > MaxPreviewRows;
_step = 2;
}
catch (AccessDeniedException)
{
Toasts.Show(ToastKind.Error, T["Pages.AccessDenied.Title"], T["ImportExport.NoTargets"]);
}
finally
{
_busy = false;
}
}
private async Task ImportAsync()
{
if (Session.Actor is not { } actor || Session.Company is not { } company || _file is not { } file || _preview is not { } preview)
{
return;
}
if (!await Dialogs.ConfirmAsync(new(ImportLabel(preview.Importable), T.Format("ImportExport.Preview.Confirm", Number(preview.Importable)),
ImportLabel(preview.Importable), T["Common.Cancel"])))
{
return;
}
_busy = true;
try
{
_report = await Imports.ImportAsync(actor, company.Code, Target.Key, file, _mapping, _options);
_onlyProblems = _report.Rows.Any(r => r.Messages.Count > 0);
_step = 3;
Toasts.Show(ToastKind.Success, T.Format("ImportExport.Done.Toast", Number(_report.Created + _report.Updated)),
T.Format("ImportExport.Done.Lead", TargetName(_report.Target), _report.Created, _report.Updated, _report.Skipped, _report.Failed));
}
catch (AccessDeniedException)
{
Toasts.Show(ToastKind.Error, T["Pages.AccessDenied.Title"], T["ImportExport.NoTargets"]);
}
catch (ImportFileException ex)
{
Toasts.Show(ToastKind.Error, TargetName(Target.Key), T[ex.Code]);
}
finally
{
_busy = false;
}
}
private async Task ReportAsync()
{
using var buffer = new MemoryStream();
IReadOnlyList<string> labels =
[
T["ImportExport.ReportColumns.Line"], T["ImportExport.ReportColumns.Key"], T["ImportExport.ReportColumns.Field"], T["ImportExport.ReportColumns.Outcome"],
T["ImportExport.ReportColumns.Message"],
];
await ImportService.WriteErrorReportAsync(
AllRows,
(_, message) => (T[message.IsWarning ? "ImportExport.Outcome.Warning" : "ImportExport.Outcome.Error"], MessageText(message)),
labels,
buffer);
var name = "report-" + Path.GetFileNameWithoutExtension(_file?.Name ?? Target.Key) + ".csv";
await DownloadAsync(buffer, name, ImportService.MediaType(TransferFormat.Csv));
}
private async Task TemplateAsync()
{
using var buffer = new MemoryStream();
await ImportService.WriteTemplateAsync(Target, _format, buffer);
await DownloadAsync(buffer, ImportService.FileName(Target.Key, _format, null), ImportService.MediaType(_format));
}
private async Task ExportAsync()
{
if (Session.Actor is not { } actor || Session.Company is not { } company)
{
return;
}
_busy = true;
try
{
using var buffer = new MemoryStream();
var count = await Imports.ExportAsync(actor, company.Code, Target.Key, _format, buffer);
await DownloadAsync(buffer, ImportService.FileName(Target.Key, _format, DateOnly.FromDateTime(DateTime.Now)), ImportService.MediaType(_format));
Toasts.Show(ToastKind.Success, TargetName(Target.Key), T.Format("ImportExport.Export.Done", Number(count)));
}
catch (AccessDeniedException)
{
Toasts.Show(ToastKind.Error, T["Pages.AccessDenied.Title"], T["ImportExport.Export.NotAllowed"]);
}
finally
{
_busy = false;
}
}
private async Task DownloadAsync(MemoryStream buffer, string name, string mediaType)
{
buffer.Position = 0;
using var stream = new DotNetStreamReference(buffer, leaveOpen: true);
await JS.InvokeVoidAsync("khaemhat.download", name, mediaType, stream);
}
}
@@ -147,6 +147,17 @@ internal static class KhaemhatServices
services.AddSingleton<Khaemhat.Application.Parties.PartyService>();
services.AddSingleton<Khaemhat.Application.Items.ItemService>();
services.AddSingleton<Khaemhat.Application.Items.PriceListService>();
// Guided import and export (ADR 0031): the entities in the order of the screen.
services.AddSingleton<Khaemhat.Application.ImportExport.IImportTarget>(sp => ActivatorUtilities.CreateInstance<Khaemhat.Application.ImportExport.PartiesImportTarget>(
sp, Khaemhat.Core.Parties.PartyKind.Customer));
services.AddSingleton<Khaemhat.Application.ImportExport.IImportTarget>(sp => ActivatorUtilities.CreateInstance<Khaemhat.Application.ImportExport.PartiesImportTarget>(
sp, Khaemhat.Core.Parties.PartyKind.Supplier));
services.AddSingleton<Khaemhat.Application.ImportExport.IImportTarget, Khaemhat.Application.ImportExport.ItemsImportTarget>();
services.AddSingleton<Khaemhat.Application.ImportExport.IImportTarget, Khaemhat.Application.ImportExport.PricesImportTarget>();
services.AddSingleton<Khaemhat.Application.ImportExport.IImportTarget, Khaemhat.Application.ImportExport.OpeningStockImportTarget>();
services.AddSingleton<Khaemhat.Application.ImportExport.IImportTarget, Khaemhat.Application.ImportExport.ChartOfAccountsImportTarget>();
services.AddSingleton<Khaemhat.Application.ImportExport.ImportService>();
services.AddSingleton<ExchangeRateService>();
services.AddHttpClient<EcbRatesClient>(c => c.Timeout = TimeSpan.FromSeconds(30));
services.AddHttpClient<ViesClient>(c => c.Timeout = TimeSpan.FromSeconds(20));
@@ -0,0 +1,237 @@
{
"ImportExport": {
"Title": "Import / export dati",
"NoCompany": "Scegli un'azienda per importare o esportare i dati.",
"NoTargets": "Il tuo ruolo non permette di importare dati in questa azienda.",
"Wizard": "Importazione guidata",
"Steps": {
"Label": "Passi dell'importazione",
"Origin": "Origine",
"OriginEmpty": "Scegli entità e file",
"OriginDetail": "{0} · {1} righe · {2}",
"Mapping": "Mappatura colonne",
"MappingEmpty": "Dopo la scelta del file",
"MappingDetail": "{0} di {1} colonne abbinate",
"Check": "Validazione",
"CheckEmpty": "Dopo la mappatura",
"CheckDetail": "OK {0} · avvisi {1} · errori {2}",
"Import": "Importazione",
"ImportEmpty": "Dopo la validazione",
"ImportReady": "Righe pronte: {0}",
"ImportCheckOnly": "Solo verifica per ora",
"ImportDone": "Creati {0} · aggiornati {1}"
},
"Target": "Entità",
"Targets": {
"clienti": "Clienti",
"fornitori": "Fornitori",
"articoli": "Articoli",
"listini": "Prezzi di listino e netti cliente",
"giacenze-iniziali": "Giacenze iniziali",
"piano-dei-conti": "Piano dei conti"
},
"Existing": "Se il codice esiste",
"ExistingChoices": {
"Update": "Aggiorna",
"Skip": "Salta la riga"
},
"Missing": "Codice mancante",
"MissingChoices": {
"Generate": "Genera automatico",
"Refuse": "Errore sulla riga"
},
"VerifyVat": "Verifica P.IVA su VIES (UE)",
"FillFromPostalCode": "Completa comune da CAP",
"File": "File da importare",
"FileHint": "CSV, XLSX o JSON; la prima riga contiene le intestazioni.",
"Reading": "Lettura del file...",
"TooLarge": "Il file supera {0} MB.",
"Formats": {
"Title": "Formati e colonne",
"Lead": "Scegli l'entità e il file: le colonne con il nome indicato qui sotto (o un nome simile) si abbinano da sole, le altre si abbinano nel passo successivo.",
"Csv": "CSV: separatore punto e virgola (anche virgola o tabulazione), UTF-8 o Windows-1252, numeri e date all'italiana.",
"Xlsx": "XLSX: il primo foglio della cartella, intestazioni nella prima riga.",
"Json": "JSON: un elenco di oggetti con le colonne come chiavi; per il piano dei conti anche il file khaemhat-coa.json.",
"Columns": "Colonne di {0}",
"RequiredMark": "obbligatoria",
"CheckOnly": "Per ora questa entità si verifica soltanto: la scrittura arriva con {0}. Il controllo serve a preparare il file in anticipo."
},
"Mapping": {
"Title": "Mappatura colonne",
"Lead": "Per ogni colonna del file scegli il campo di destinazione; le colonne senza campo si ignorano.",
"Header": "Colonna del file",
"Sample": "Esempio (riga 2)",
"Field": "Campo",
"Ignore": "Ignora",
"Check": "Verifica le righe",
"ChangeFile": "Cambia file",
"RequiredMissing": "Campi obbligatori non abbinati: {0}.",
"Sections": "Il file contiene anche: {0}. Queste sezioni si importano con la contabilità (M7)."
},
"Preview": {
"Title": "Anteprima e validazione",
"Subtitle": "Anteprima e validazione (prime {0} di {1})",
"SubtitleAll": "Anteprima e validazione ({0} righe)",
"All": "Tutte",
"Problems": "Solo problemi",
"Line": "Riga",
"Key": "Codice",
"Outcome": "Esito",
"Ok": "OK",
"Warnings": "{0} avvisi",
"Warning": "1 avviso",
"Error": "Errore",
"Create": "Nuovo",
"Update": "Aggiorna",
"Skip": "Saltata",
"NoRows": "Nessuna riga da mostrare.",
"Back": "Mappatura",
"Report": "Scarica report errori",
"Import": "Importa {0} righe",
"ImportOne": "Importa 1 riga",
"Confirm": "Righe da importare: {0}. Le righe con errori restano fuori e si trovano nel report.",
"Importing": "Importazione in corso..."
},
"Done": {
"Title": "Importazione completata",
"Lead": "{0}: creati {1}, aggiornati {2}, saltati {3}, con errori {4}.",
"Again": "Nuova importazione",
"Toast": "Righe importate: {0}"
},
"Export": {
"Title": "Esporta e modelli",
"Lead": "L'esportazione usa le stesse colonne dell'import: il file si può correggere e importare di nuovo.",
"Format": "Formato",
"Template": "Scarica modello",
"Run": "Esporta",
"Done": "Record esportati: {0}",
"NotAllowed": "Il tuo utente non può esportare dati.",
"Nothing": "Per questa entità c'è solo il modello: non ci sono ancora dati da esportare."
},
"ReportColumns": {
"Line": "riga",
"Key": "codice",
"Field": "colonna",
"Outcome": "esito",
"Message": "messaggio"
},
"Outcome": {
"Error": "errore",
"Warning": "avviso"
},
"MessageField": "{0}: {1}",
"Fields": {
"codice": "Codice",
"ragione_sociale": "Ragione sociale",
"nome": "Nome",
"cognome": "Cognome",
"tipo_soggetto": "Tipo soggetto",
"partita_iva": "Partita IVA",
"codice_fiscale": "Codice fiscale",
"rea": "REA",
"indirizzo": "Indirizzo",
"civico": "Civico",
"cap": "CAP",
"comune": "Comune",
"provincia": "Provincia",
"nazione": "Nazione",
"telefono": "Telefono",
"email": "Email",
"pec": "PEC",
"sito": "Sito web",
"codice_destinatario": "Codice destinatario",
"categoria": "Categoria",
"agente": "Agente",
"pagamento": "Pagamento",
"listino": "Listino",
"sconto1": "Sconto 1",
"sconto2": "Sconto 2",
"fido": "Fido",
"iban": "IBAN",
"note": "Note",
"descrizione": "Descrizione",
"descrizione_estesa": "Descrizione estesa",
"tipo": "Tipo",
"um": "Unità di misura",
"iva_vendite": "IVA vendite",
"iva_acquisti": "IVA acquisti",
"ean": "Codice a barre",
"nc8": "Nomenclatura combinata",
"marca": "Marca",
"produttore": "Produttore",
"peso_netto": "Peso netto",
"peso_lordo": "Peso lordo",
"a_magazzino": "Gestito a magazzino",
"magazzino": "Deposito",
"scorta_minima": "Scorta minima",
"punto_riordino": "Punto di riordino",
"lotto_riordino": "Lotto di riordino",
"prezzo": "Prezzo",
"costo_standard": "Costo standard",
"conto_ricavo": "Conto ricavo",
"conto_costo": "Conto costo",
"articolo": "Articolo",
"cliente": "Cliente",
"valido_dal": "Valido dal",
"deposito": "Deposito",
"quantita": "Quantità",
"costo_unitario": "Costo unitario",
"livello": "Livello",
"padre": "Conto padre",
"natura": "Natura",
"voce_cee": "Voce CEE",
"riclassifica": "Riclassifica",
"flag": "Attributi"
}
},
"import": {
"file": {
"format": "Il file non è CSV, XLSX o JSON.",
"empty": "Il file non ha intestazioni o righe.",
"unreadable": "Il file non si riesce a leggere: è danneggiato o non è nel formato atteso.",
"too-large": "Il file ha troppe righe: al massimo 50.000 per importazione."
},
"target": {
"unknown": "Entità sconosciuta o non attiva con la licenza.",
"check-only": "Per ora questa entità si verifica soltanto."
},
"value": {
"required": "Valore obbligatorio.",
"number": "Non è un numero.",
"date": "Non è una data.",
"boolean": "Scrivi sì o no.",
"choice": "Valore non previsto: usa {0}.",
"code-unknown": "Il codice {0} non esiste.",
"positive": "Deve essere maggiore di zero."
},
"code": {
"missing": "Manca il codice e le opzioni non lo generano.",
"repeated": "Il codice {0} è già in una riga precedente del file.",
"exists": "Il codice {0} esiste già: riga saltata come richiesto."
},
"party": {
"other-kind": "Il codice {0} appartiene a un'anagrafica di altro tipo."
},
"filled": {
"city": "Comune completato dal CAP: {0}.",
"postal-code": "CAP completato dal comune: {0}."
},
"price": {
"target": "Indica il listino oppure il cliente, non entrambi."
},
"stock": {
"not-stocked": "L'articolo {0} non è merce gestita a magazzino."
},
"write": {
"failed": "Riga non scritta: il dato è cambiato nel frattempo o una regola l'ha rifiutata."
},
"coa": {
"level": "Livello non valido: il codice ha da 1 a 3 parti separate da punto ({0}).",
"parent": "Il conto padre deve essere {0} e deve trovarsi nel file.",
"nature": "La natura deve essere quella del conto padre ({0}).",
"postable": "Un conto con sottoconti non può essere movimentabile.",
"leaf": "Conto senza sottoconti non movimentabile: manca la lettera M negli attributi.",
"flag": "Attributo {0} sconosciuto: usa M, I, P, C, X."
}
}
}
+2 -1
View File
@@ -144,7 +144,8 @@
"Licenses": "Licenze e moduli",
"Jobs": "Attività programmate",
"Log": "Log",
"Status": "Stato del sistema"
"Status": "Stato del sistema",
"ImportExport": "Import / export dati"
}
},
"Tabs": {
+1
View File
@@ -29,6 +29,7 @@ public static class HelpLinks
("/report", "Report"),
("/tabelle", "Tabelle-azienda"),
("/automazioni", "Automazioni"),
("/amministrazione/import-export", "Import-Export"),
("/amministrazione/licenze", "Licenze-e-moduli"),
("/amministrazione/log", "Log"),
("/amministrazione/attivita", "Attivita-programmate"),
+10 -5
View File
@@ -95,11 +95,13 @@ public static class MenuCatalog
("Shell.Menu.CompanyTables.Currencies", "valute"), ("Shell.Menu.CompanyTables.ExchangeRates", "cambi")),
Area("Shell.Menu.Automation", "zap", "/automazioni", ModuleCodes.Automation, null, "M12",
("Shell.Menu.Automation.Rules", "regole"), ("Shell.Menu.Automation.Procedures", "procedure")),
Area("Shell.Menu.Admin", "shield", "/amministrazione", ModuleCodes.Core, null, "M13",
MenuAudience.InstanceAccounts,
("Shell.Menu.Admin.Companies", "aziende"), ("Shell.Menu.Admin.Users", "utenti"), ("Shell.Menu.Admin.Roles", "ruoli"),
("Shell.Menu.Admin.Licenses", "licenze"), ("Shell.Menu.Admin.Jobs", "attivita"), ("Shell.Menu.Admin.Log", "log"),
("Shell.Menu.Admin.Status", "stato")),
WithChild(
Area("Shell.Menu.Admin", "shield", "/amministrazione", ModuleCodes.Core, null, "M13",
MenuAudience.InstanceAccounts,
("Shell.Menu.Admin.Companies", "aziende"), ("Shell.Menu.Admin.Users", "utenti"), ("Shell.Menu.Admin.Roles", "ruoli"),
("Shell.Menu.Admin.Licenses", "licenze"), ("Shell.Menu.Admin.Jobs", "attivita"), ("Shell.Menu.Admin.Log", "log"),
("Shell.Menu.Admin.Status", "stato")),
new MenuItem("Shell.Menu.Admin.ImportExport", "shield", "/amministrazione/import-export", ModuleCodes.Core, null, null, MenuAudience.InstanceAccounts)),
]),
];
@@ -118,6 +120,9 @@ public static class MenuCatalog
public static MenuItem? FindArea(string path) =>
Sections.SelectMany(s => s.Items).Where(i => i.Matches(path)).OrderByDescending(i => i.Href.Length).FirstOrDefault();
// An entry delivered before the rest of its area (the guided import of M4 under the administration of M13).
private static MenuItem WithChild(MenuItem area, MenuItem child) => area with { Children = [.. area.Children, child] };
private static MenuItem Area(string key, string icon, string href, string module, string? permission, string? milestone,
params (string Key, string Slug)[] children) =>
Area(key, icon, href, module, permission, milestone, MenuAudience.Everyone, children);
+23
View File
@@ -332,3 +332,26 @@ h1[tabindex="-1"]:focus { outline: none; box-shadow: none; }
/* Stronger than the striped and hovered rows, so every pending cell shows. */
.grid tbody tr td.kh-changed { background: var(--kh-warn-soft); font-weight: 600; }
.grid td.kh-derived { color: var(--kh-text-2); font-style: italic; }
/* Guided import and export (mockup 077): the wizard and the export on the left, mapping or preview on the right. */
.kh-import { display: grid; grid-template-columns: 330px minmax(0, 1fr); gap: var(--kh-gap); align-items: start; }
.kh-import-side { display: flex; flex-direction: column; gap: var(--kh-gap); }
.kh-import-main { min-width: 0; }
.kh-import-options { display: grid; grid-template-columns: repeat(12, 1fr); gap: 10px 12px; margin-top: 14px; padding-top: 14px; border-top: 1px solid var(--kh-border); }
.kh-import-options .f { display: flex; flex-direction: column; gap: 4px; }
.kh-import-options input[type=file].in { padding: 4px; height: auto; }
.kh-import-lead { margin: 0 0 10px; }
.kh-import-list { margin: 0 0 12px; padding-left: 18px; display: grid; gap: 4px; }
.kh-import-h { font-size: 13px; margin: 14px 0 8px; }
.kh-import-chips { display: flex; flex-wrap: wrap; gap: 6px; }
.kh-import-chips .chip.soft { background: var(--kh-surface-3); color: var(--kh-text-2); }
.kh-import-actions { display: flex; gap: 8px; margin-top: 12px; flex-wrap: wrap; }
.kh-import-callout { margin: 0 12px 10px; }
.kh-import-map td select.in { min-width: 220px; }
.kh-import-preview td.kh-import-outcome { white-space: normal; min-width: 220px; }
.kh-import-msg { display: block; font-size: 11.5px; margin-top: 3px; }
.kh-import-msg.err { color: var(--kh-err); }
.kh-import-msg.warn { color: var(--kh-warn-text, var(--kh-text-2)); }
.grid tbody tr td.kh-import-cell-err { background: var(--kh-err-soft); }
.grid tbody tr td.kh-import-cell-warn { background: var(--kh-warn-soft); }
@media (max-width: 1100px) { .kh-import { grid-template-columns: 1fr; } }
@@ -187,6 +187,7 @@ a.kh-tilelink:hover { border-color: var(--kh-accent); }
.kh-steps { list-style: none; margin: 0; }
.steps.kh-steps { padding: 4px 0; }
.vsteps.kh-steps { padding: 6px 0; }
.vsteps.kh-steps .vs { display: block; }
button.tab { border: 0; border-bottom: 2px solid transparent; background: none; font: inherit; cursor: pointer; }
button.tab.active { border-bottom-color: var(--kh-accent); }
@@ -0,0 +1,173 @@
using System.Text;
using Khaemhat.Application.ImportExport;
using Khaemhat.Core.Accounting;
namespace Khaemhat.Application.Tests;
/// <summary>The pure parts of the guided import (issue #44, ADR 0031): values, files, mapping and the chart of accounts.</summary>
[TestClass]
public sealed class ImportRulesTests
{
[TestMethod]
[DataRow("1.234,56", "1234.56")]
[DataRow("1234,56", "1234.56")]
[DataRow("1234.56", "1234.56")]
[DataRow("1,234.56", "1234.56")]
[DataRow("1.234.567", "1234567")]
[DataRow("€ 12,5", "12.5")]
[DataRow("22 %", "22")]
[DataRow("-3", "-3")]
[DataRow("1E3", "1000")]
public void TryNumber_ReadsItalianAndMachineNotation(string text, string expected)
{
Assert.IsTrue(ImportValues.TryNumber(text, out var value), text);
Assert.AreEqual(decimal.Parse(expected, System.Globalization.CultureInfo.InvariantCulture), value);
}
[TestMethod]
[DataRow("")]
[DataRow("dodici")]
[DataRow("12a")]
public void TryNumber_RefusesText(string text) => Assert.IsFalse(ImportValues.TryNumber(text, out _));
[TestMethod]
[DataRow("12/11/2026")]
[DataRow("12/11/26")]
[DataRow("2026-11-12")]
[DataRow("20261112")]
[DataRow("12.11.2026")]
[DataRow("2026-11-12T08:30:00")]
[DataRow("46338")]
public void TryDate_ReadsTheCommonForms(string text)
{
Assert.IsTrue(ImportValues.TryDate(text, out var value), text);
Assert.AreEqual(new DateOnly(2026, 11, 12), value);
}
[TestMethod]
public void TryBoolean_AndChoice_IgnoreCaseAndAccents()
{
Assert.IsTrue(ImportValues.TryBoolean("Sì", out var yes) && yes);
Assert.IsTrue(ImportValues.TryBoolean("VERO", out var vero) && vero);
Assert.IsTrue(ImportValues.TryBoolean("x", out var x) && x);
Assert.IsTrue(ImportValues.TryBoolean("FALSO", out var no) && !no);
Assert.IsFalse(ImportValues.TryBoolean("forse", out _));
Assert.AreEqual(4, ImportValues.Choice("Extra UE", PartiesImportTarget.SubjectWords));
Assert.AreEqual(2, ImportValues.Choice("P.A.", PartiesImportTarget.SubjectWords));
Assert.AreEqual(-1, ImportValues.Choice("altro", PartiesImportTarget.SubjectWords));
Assert.AreEqual("partita_iva", ImportValues.Normalize(" Partita IVA "));
Assert.AreEqual("citta", ImportValues.Normalize("Città"));
}
[TestMethod]
public void Csv_GuessesSeparatorAndEncoding_AndRemovesTheFormulaGuard()
{
var utf8 = ImportFileReader.ReadCsv("clienti.csv", [.. Encoding.UTF8.GetPreamble(), .. Encoding.UTF8.GetBytes("Codice;Città;Note\r\nC1;Forlì;'=SOMMA\r\n;;\r\nC2;Aosta\r\n")]);
Assert.AreEqual("UTF-8", utf8.Encoding);
Assert.AreEqual(';', utf8.Separator);
CollectionAssert.AreEqual(new[] { "Codice", "Città", "Note" }, utf8.Headers.ToArray());
Assert.AreEqual(2, utf8.Count, "The empty row is skipped.");
Assert.AreEqual("=SOMMA", utf8.Rows[0][2], "The apostrophe of the export goes away.");
Assert.AreEqual(string.Empty, utf8.Rows[1][2], "Short rows are padded.");
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var ansi = ImportFileReader.ReadCsv("vecchio.csv", Encoding.GetEncoding(1252).GetBytes("codice,città\nA,Forlì\n"));
Assert.AreEqual("Windows-1252", ansi.Encoding);
Assert.AreEqual(',', ansi.Separator);
Assert.AreEqual("Forlì", ansi.Rows[0][1]);
Assert.AreEqual(ImportErrors.FileEmpty, Assert.ThrowsExactly<ImportFileException>(() => ImportFileReader.ReadCsv("vuoto.csv", [])).Code);
}
[TestMethod]
public async Task Json_ReadsArraysAndTheChartFile()
{
var array = await ReadJsonAsync("""[{"codice":"A","prezzo":12.5,"attivo":true},{"codice":"B","note":null}]""");
CollectionAssert.AreEqual(new[] { "codice", "prezzo", "attivo", "note" }, array.Headers.ToArray());
CollectionAssert.AreEqual(new[] { "A", "12.5", "true", string.Empty }, array.Rows[0].ToArray());
Assert.IsNull(array.Sections);
var chart = await ReadJsonAsync("""{"format":"khaemhat-coa","version":1,"accounts":[{"codice":"01"}],"statementLines":[{},{}],"mappings":[]}""");
Assert.AreEqual(1, chart.Count);
Assert.AreEqual(2, chart.Sections!["statementLines"]);
Assert.AreEqual(0, chart.Sections["mappings"]);
var wrong = await Assert.ThrowsExactlyAsync<ImportFileException>(() => ReadJsonAsync("""{"codice":"A"}"""));
Assert.AreEqual(ImportErrors.FileUnreadable, wrong.Code);
var format = await Assert.ThrowsExactlyAsync<ImportFileException>(() => ImportFileReader.ReadAsync("dati.pdf", new MemoryStream([1, 2])));
Assert.AreEqual(ImportErrors.FileFormat, format.Code);
}
[TestMethod]
public void Mapping_UsesNamesThenAliases_EachFieldOnce()
{
var target = new ChartOfAccountsImportTarget(null!);
var mapping = ImportService.SuggestMapping(target, ["Conto", "Descrizione", "Codice", "Natura", "Colore", "descr"]);
CollectionAssert.AreEqual(new[] { null, "descrizione", "codice", "natura", null, null }, mapping.ToArray(), "The exact name wins over the alias.");
var file = new ImportFile("x.csv", TransferFormat.Csv, "UTF-8", ';', ["Codice", "Descrizione"], [["01", " Attivo "], ["", ""]]);
var rows = ImportService.Rows(file, ["codice", "descrizione"]);
Assert.AreEqual(2, rows[0].Line, "The header is line 1.");
Assert.AreEqual("Attivo", rows[0]["descrizione"]);
Assert.IsNull(rows[1]["codice"], "Empty cells are left out.");
}
[TestMethod]
public void Chart_AcceptsATreeOfThreeLevels()
{
var (results, accounts) = ChartOfAccountsImportValidator.Check(
[
Row(2, ("codice", "01"), ("descrizione", "Attivo"), ("natura", "attivo")),
Row(3, ("codice", "01.10"), ("descrizione", "Crediti"), ("livello", "2")),
Row(4, ("codice", "01.10.001"), ("descrizione", "Clienti Italia"), ("tipo", "clienti"), ("flag", "M,P")),
Row(5, ("codice", "02"), ("descrizione", "Costi"), ("natura", "costo")),
Row(6, ("codice", "02.01"), ("descrizione", "Acquisti"), ("padre", "02"), ("flag", "MI")),
]);
Assert.IsTrue(results.All(r => r.Outcome == ImportOutcome.Ok), string.Join("; ", results.SelectMany(r => r.Messages).Select(m => m.Field + ":" + m.Code)));
Assert.HasCount(5, accounts);
var customers = accounts.Single(a => a.Code == "01.10.001");
Assert.AreEqual(3, customers.Level);
Assert.AreEqual("01.10", customers.ParentCode);
Assert.AreEqual(AccountNature.Asset, customers.Nature, "The nature comes from the ancestor.");
Assert.AreEqual(AccountType.Customers, customers.Type);
Assert.IsTrue(customers.Postable && customers.SubLedger && !customers.VatRelevant);
Assert.IsTrue(accounts.Single(a => a.Code == "02.01").VatRelevant);
}
[TestMethod]
public void Chart_RefusesWhatTheTreeDoesNotAllow()
{
var (results, accounts) = ChartOfAccountsImportValidator.Check(
[
Row(2, ("codice", "01"), ("descrizione", "Attivo"), ("natura", "attivo"), ("flag", "M")),
Row(3, ("codice", "01.01"), ("descrizione", "Cassa"), ("natura", "passivo"), ("flag", "M")),
Row(4, ("codice", "03.01"), ("descrizione", "Orfano"), ("natura", "ricavo"), ("flag", "M")),
Row(5, ("codice", "01.01.01.01"), ("descrizione", "Troppo"), ("flag", "M")),
Row(6, ("codice", "01"), ("descrizione", "Doppio"), ("natura", "attivo")),
Row(7, ("codice", "04"), ("descrizione", "Senza natura")),
Row(8, ("codice", "05"), ("descrizione", "Lettera"), ("natura", "ordine"), ("flag", "MZ")),
Row(9, ("codice", "01.02"), ("descrizione", "Foglia"), ("livello", "3")),
]);
string[] Codes(int line) => [.. results.Single(r => r.Line == line).Messages.Select(m => m.Code)];
CollectionAssert.Contains(Codes(2), ImportErrors.AccountPostable);
CollectionAssert.Contains(Codes(3), ImportErrors.AccountNature);
CollectionAssert.Contains(Codes(4), ImportErrors.AccountParent);
CollectionAssert.Contains(Codes(5), ImportErrors.AccountLevel);
CollectionAssert.Contains(Codes(6), ImportErrors.CodeRepeated);
CollectionAssert.Contains(Codes(7), ImportErrors.Required);
CollectionAssert.Contains(Codes(8), ImportErrors.AccountFlag);
CollectionAssert.Contains(Codes(9), ImportErrors.AccountLevel);
Assert.IsTrue(results.Single(r => r.Line == 9).Messages.Any(m => m.Code == ImportErrors.AccountLeaf && m.IsWarning));
Assert.IsFalse(accounts.Any(a => a.Code is "01" or "01.01" or "03.01"), "Only rows without errors become accounts.");
}
private static ImportRow Row(int line, params (string Key, string Value)[] cells) => new(line, cells.ToDictionary(c => c.Key, c => c.Value));
private static async Task<ImportFile> ReadJsonAsync(string json)
{
using var stream = new MemoryStream(Encoding.UTF8.GetBytes(json));
return await ImportFileReader.ReadAsync("dati.json", stream);
}
}
@@ -0,0 +1,64 @@
using System.IO.Compression;
using System.Text;
using Khaemhat.Infrastructure.Files;
namespace Khaemhat.Infrastructure.Tests.Files;
/// <summary>The XLSX reader of the guided import (issue #44): what the writer produces comes back as text.</summary>
[TestClass]
public sealed class XlsxReaderTests
{
[TestMethod]
[DataRow(false)]
[DataRow(true)]
public async Task ReadsBackWhatTheWriterWrites(bool sharedStrings)
{
using var buffer = new MemoryStream();
await using (var writer = await XlsxWriter.CreateAsync(buffer, new XlsxOptions { UseSharedStrings = sharedStrings }, leaveOpen: true))
{
await writer.StartSheetAsync("clienti", [new("codice"), new("prezzo"), new("dal"), new("attivo"), new("note")]);
await writer.WriteRowAsync(["C001", 1234.5m, new DateOnly(2026, 11, 12), true, null]);
await writer.WriteRowAsync([null, null, null, null, null]);
await writer.WriteRowAsync(["C002", -3m, null, false, "Via \"Roma\" & co. <1>"]);
await writer.CompleteAsync();
}
buffer.Position = 0;
var rows = await XlsxReader.ReadAsync(buffer);
Assert.HasCount(3, rows, "Header and two rows: the empty row is skipped.");
CollectionAssert.AreEqual(new[] { "codice", "prezzo", "dal", "attivo", "note" }, rows[0].ToArray());
Assert.AreEqual("C001", rows[1][0]);
Assert.AreEqual("1234.5", rows[1][1], "Numbers come in invariant notation.");
Assert.AreEqual("2026-11-12", rows[1][2], "Date-styled numbers come back as ISO dates.");
Assert.AreEqual("true", rows[1][3]);
Assert.AreEqual("-3", rows[2][1]);
Assert.AreEqual(string.Empty, rows[2][2], "A gap between cells is an empty cell.");
Assert.AreEqual("false", rows[2][3]);
Assert.AreEqual("Via \"Roma\" & co. <1>", rows[2][4]);
}
[TestMethod]
public async Task NotAWorkbook_IsRefused()
{
using var text = new MemoryStream(Encoding.UTF8.GetBytes("codice;descrizione\nA;B\n"));
await Assert.ThrowsExactlyAsync<XlsxReadException>(() => XlsxReader.ReadAsync(text));
using var zip = new MemoryStream();
using (var archive = new ZipArchive(zip, ZipArchiveMode.Create, leaveOpen: true))
{
archive.CreateEntry("readme.txt");
}
zip.Position = 0;
await Assert.ThrowsExactlyAsync<XlsxReadException>(() => XlsxReader.ReadAsync(zip));
}
[TestMethod]
[DataRow("A1", 0)]
[DataRow("C7", 2)]
[DataRow("Z10", 25)]
[DataRow("AA1", 26)]
[DataRow("AB12", 27)]
public void ColumnOf_ReadsTheLetters(string reference, int column) => Assert.AreEqual(column, XlsxReader.ColumnOf(reference));
}
@@ -0,0 +1,178 @@
using System.Text;
using Khaemhat.Application.ImportExport;
using Khaemhat.Application.Items;
using Khaemhat.Application.Parties;
using Khaemhat.Application.Querying;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Security;
using Khaemhat.Core.Tables;
using Khaemhat.Web.Tests.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace Khaemhat.Web.Tests.ImportExport;
/// <summary>The guided import and export on a real instance (issue #44, ADR 0031).</summary>
[TestClass]
public sealed class ImportServiceTests
{
private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
[TestMethod]
public async Task Customers_AreCheckedAsTypedInTheRecord_AndOnlyRowsWithoutErrorsAreWritten()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var imports = app.Services.GetRequiredService<ImportService>();
var parties = app.Services.GetRequiredService<PartyService>();
var file = Csv(
"Codice;Ragione sociale;P.IVA;CAP;Comune;Pagamento;Tipo soggetto;Cognome;Nome;IBAN",
"CLI001;Rossi Impianti S.r.l.;01234567897;47121;;;impresa;;;IT60 X054 2811 1010 0000 0123 456",
"CLI002;;;;;;privato;Bianchi;Anna;",
"CLI001;Doppione S.r.l.;02345678904;;;;;;;",
";Verdi S.p.A.;02345678904;;;XX;;;;",
";Neri S.r.l.;01234567890;;;;;;;");
var mapping = ImportService.SuggestMapping(imports.Target("clienti"), file.Headers);
Assert.IsFalse(mapping.Contains(null), "Every header of the file has a field: " + string.Join(", ", mapping));
var preview = await imports.PreviewAsync(Root, company, "clienti", file, mapping, new ImportOptions());
string[] Codes(int line) => [.. preview.Rows.Single(r => r.Line == line).Messages.Select(m => m.Field + ":" + m.Code)];
Assert.AreEqual(ImportAction.Create, preview.Rows[0].Action);
CollectionAssert.Contains(Codes(3), "codice_fiscale:" + PartyService.TaxCodeMissing, "A private customer without tax code is a warning.");
CollectionAssert.Contains(Codes(4), "codice:" + ImportErrors.CodeRepeated);
CollectionAssert.Contains(Codes(5), "pagamento:" + ImportErrors.CodeUnknown);
Assert.IsTrue(Codes(6).Any(c => c.StartsWith("partita_iva:", StringComparison.Ordinal)), "The VAT number check of the fiscal pack: " + string.Join(", ", Codes(6)));
Assert.AreEqual(2, preview.Creates);
Assert.AreEqual(3, preview.Errors);
var report = await imports.ImportAsync(Root, company, "clienti", file, mapping, new ImportOptions());
Assert.AreEqual(2, report.Created);
Assert.AreEqual(3, report.Failed);
var rossi = (await parties.SearchAsync(Root, company, PartyArchive.Customers, "CLI001")).Single();
var record = (await parties.GetAsync(Root, company, rossi.Id))!;
Assert.AreEqual("Rossi Impianti S.r.l.", record.Party.Name);
Assert.AreEqual("IT60X0542811101000000123456", record.BankAccounts.Single().Iban);
Assert.AreEqual("Bianchi Anna", (await parties.SearchAsync(Root, company, PartyArchive.Customers, "CLI002")).Single().Name);
// Updating: empty cells keep what is there; skipping leaves the record alone; a supplier cannot take a customer's code.
var update = Csv("codice;telefono;ragione_sociale", "CLI001;0543 123456;");
var updated = await imports.ImportAsync(Root, company, "clienti", update, ["codice", "telefono", "ragione_sociale"], new ImportOptions());
Assert.AreEqual(1, updated.Updated);
record = (await parties.GetAsync(Root, company, rossi.Id))!;
StringAssert.Contains(record.Party.Phone, "123456");
Assert.AreEqual("Rossi Impianti S.r.l.", record.Party.Name);
var skipped = await imports.PreviewAsync(Root, company, "clienti", update, ["codice", "telefono", null], new ImportOptions { Existing = ExistingCodeAction.Skip });
Assert.AreEqual(ImportErrors.CodeExists, skipped.Rows.Single().Messages.Single().Code);
Assert.AreEqual(1, skipped.Skips);
var supplier = await imports.PreviewAsync(Root, company, "fornitori", update, ["codice", "telefono", null], new ImportOptions());
Assert.AreEqual(ImportErrors.OtherKind, supplier.Rows.Single().Messages.Single().Code);
var refused = await imports.PreviewAsync(Root, company, "fornitori", Csv("ragione_sociale;partita_iva", "Bianchi Forniture;02345678904"), ["ragione_sociale", "partita_iva"],
new ImportOptions { Missing = MissingCodeAction.Refuse });
Assert.AreEqual(ImportErrors.CodeMissing, refused.Rows.Single().Messages.Single().Code);
await app.StopAsync();
}
}
[TestMethod]
public async Task Items_Prices_AndTheExport_GoRoundTrip()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var imports = app.Services.GetRequiredService<ImportService>();
var tables = app.Services.GetRequiredService<TableService>();
await tables.SaveAsync(Root, company, new ItemCategory { Code = "VALV", Description = "Valvolame" });
var baseList = (await tables.ListAsync<PriceList>(Root, company, new ListQuery { Limit = 100 })).Items.Single(l => l.IsBase).Code;
var parties = app.Services.GetRequiredService<PartyService>();
var customer = await parties.NewAsync(Root, company, PartyKind.Customer);
(customer.Party.Code, customer.Party.Name, customer.Party.VatNumber) = ("C1", "Rossi Impianti S.r.l.", "01234567897");
await parties.SaveAsync(Root, company, customer);
var items = Csv(
"codice;descrizione;categoria;um;prezzo;tipo;a_magazzino",
"A-1;Valvola a sfera;VALV;PZ;12,50;merce;sì",
";Manodopera;VALV;PZ;38;servizio;",
"A-2;;VALV;PZ;1;merce;forse");
var mapping = ImportService.SuggestMapping(imports.Target("articoli"), items.Headers);
var report = await imports.ImportAsync(Root, company, "articoli", items, mapping, new ImportOptions());
Assert.AreEqual(2, report.Created);
var bad = report.Rows.Single(r => r.Line == 4).Messages.Select(m => m.Field + ":" + m.Code).ToList();
CollectionAssert.Contains(bad, "descrizione:" + ImportErrors.Required);
CollectionAssert.Contains(bad, "a_magazzino:" + ImportErrors.Boolean);
var itemService = app.Services.GetRequiredService<ItemService>();
var labour = (await itemService.SearchAsync(Root, company, "Manodopera")).Single();
StringAssert.StartsWith(labour.Code, "VALV", "The code comes from the rule of the items.");
Assert.IsFalse(labour.Stocked, "A service is not stocked.");
var prices = Csv(
"articolo;listino;cliente;prezzo;valido_dal",
$"A-1;{baseList};;10;01/01/2026",
"A-1;;C1;9,5;",
$"A-1;{baseList};C1;5;",
$"A-9;{baseList};;5;");
var pricesMapping = ImportService.SuggestMapping(imports.Target("listini"), prices.Headers);
var priced = await imports.ImportAsync(Root, company, "listini", prices, pricesMapping, new ImportOptions());
Assert.AreEqual(2, priced.Created);
CollectionAssert.Contains(priced.Rows.Single(r => r.Line == 4).Messages.Select(m => m.Code).ToList(), ImportErrors.PriceTarget);
CollectionAssert.Contains(priced.Rows.Single(r => r.Line == 5).Messages.Select(m => m.Code).ToList(), ImportErrors.CodeUnknown);
var again = await imports.PreviewAsync(Root, company, "listini", prices, pricesMapping, new ImportOptions());
Assert.AreEqual(ImportAction.Update, again.Rows[0].Action, "The same item, list and day replace the price.");
// The export has the columns of the import: imported again, every row updates and nothing fails.
foreach (var format in new[] { TransferFormat.Csv, TransferFormat.Xlsx, TransferFormat.Json })
{
using var buffer = new MemoryStream();
Assert.AreEqual(2, await imports.ExportAsync(Root, company, "articoli", format, buffer));
buffer.Position = 0;
var exported = await ImportFileReader.ReadAsync(ImportService.FileName("articoli", format, new DateOnly(2026, 11, 12)), buffer);
CollectionAssert.AreEqual(imports.Target("articoli").Fields.Select(f => f.Key).ToArray(), exported.Headers.ToArray(), format.ToString());
var back = await imports.PreviewAsync(Root, company, "articoli", exported, ImportService.SuggestMapping(imports.Target("articoli"), exported.Headers),
new ImportOptions());
Assert.AreEqual(0, back.Errors, format + ": " + string.Join("; ", back.Rows.SelectMany(r => r.Messages).Select(m => m.Field + ":" + m.Code)));
Assert.AreEqual(2, back.Updates, format.ToString());
}
using var priceExport = new MemoryStream();
Assert.AreEqual(2, await imports.ExportAsync(Root, company, "listini", TransferFormat.Csv, priceExport));
var priceText = Encoding.UTF8.GetString(priceExport.ToArray());
StringAssert.Contains(priceText, "A-1;" + baseList + ";;10;01/01/2026");
StringAssert.Contains(priceText, "A-1;;C1;9,5;");
using var template = new MemoryStream();
await ImportService.WriteTemplateAsync(imports.Target("listini"), TransferFormat.Csv, template);
Assert.AreEqual("articolo;listino;cliente;prezzo;valido_dal", Encoding.UTF8.GetString(template.ToArray()).Trim('', '\r', '\n'));
await app.StopAsync();
}
}
[TestMethod]
public async Task OpeningStock_IsOnlyChecked_UntilTheStockEntriesExist()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var imports = app.Services.GetRequiredService<ImportService>();
var tables = app.Services.GetRequiredService<TableService>();
await tables.SaveAsync(Root, company, new ItemCategory { Code = "VALV", Description = "Valvolame" });
var items = Csv("codice;descrizione;categoria;tipo", "A-1;Valvola;VALV;merce", "S-1;Manodopera;VALV;servizio");
await imports.ImportAsync(Root, company, "articoli", items, ImportService.SuggestMapping(imports.Target("articoli"), items.Headers), new ImportOptions());
var stock = Csv("articolo;deposito;quantita;costo_unitario", "A-1;;5;3,20", "S-1;;1;", "A-1;;0;", "B-9;;1;");
var mapping = ImportService.SuggestMapping(imports.Target("giacenze-iniziali"), stock.Headers);
var preview = await imports.PreviewAsync(Root, company, "giacenze-iniziali", stock, mapping, new ImportOptions());
Assert.IsFalse(preview.CanApply);
Assert.AreEqual(ImportOutcome.Ok, preview.Rows[0].Outcome, string.Join("; ", preview.Rows[0].Messages.Select(m => m.Field + ":" + m.Code)));
Assert.AreEqual(ImportErrors.NotStocked, preview.Rows[1].Messages.Single().Code);
CollectionAssert.Contains(preview.Rows[2].Messages.Select(m => m.Code).ToList(), ImportErrors.Positive);
Assert.AreEqual(ImportErrors.CodeUnknown, preview.Rows[3].Messages.Single().Code);
var refused = await Assert.ThrowsExactlyAsync<ImportFileException>(() => imports.ImportAsync(Root, company, "giacenze-iniziali", stock, mapping, new ImportOptions()));
Assert.AreEqual(ImportErrors.CheckOnly, refused.Code);
await app.StopAsync();
}
}
private static ImportFile Csv(params string[] lines) =>
ImportFileReader.ReadCsv("prova.csv", Encoding.UTF8.GetBytes(string.Join("\r\n", lines) + "\r\n"));
}
@@ -271,6 +271,6 @@ public sealed partial class LocalizationRulesTests
[GeneratedRegex(@"&[a-zA-Z]+;|&#\d+;")]
private static partial Regex EntityPattern();
[GeneratedRegex("\"((?:Shell|Pages|Auth|Common|Ui|Dashboard|Parties|Items)\\.[A-Za-z0-9_.]+)\"")]
[GeneratedRegex("\"((?:Shell|Pages|Auth|Common|Ui|Dashboard|Parties|Items|ImportExport)\\.[A-Za-z0-9_.]+)\"")]
private static partial Regex KeyPattern();
}