From caa33a2ceed821e2e7763b97b8e6536f8dc886a0 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Thu, 12 Nov 2026 11:52:59 +0100 Subject: [PATCH] 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 --- CHANGELOG.md | 7 + docs/STATUS.md | 10 +- docs/adr/0031-import-e-export-guidato.md | 69 +++ docs/wiki/Import-Export.md | 236 +++++++--- .../ImportExport/CheckOnlyImportTargets.cs | 332 +++++++++++++ .../ImportExport/ImportFileReader.cs | 255 ++++++++++ .../ImportExport/ImportModel.cs | 197 ++++++++ .../ImportExport/ImportService.cs | 375 +++++++++++++++ .../ImportExport/ImportTarget.cs | 442 ++++++++++++++++++ .../ImportExport/ImportValues.cs | 274 +++++++++++ .../ImportExport/ItemsImportTarget.cs | 274 +++++++++++ .../ImportExport/PartiesImportTarget.cs | 429 +++++++++++++++++ .../ImportExport/PricesImportTarget.cs | 187 ++++++++ .../Parties/PartyService.cs | 16 +- src/Khaemhat.Core/Accounting/AccountType.cs | 26 ++ .../Files/XlsxReader.cs | 414 ++++++++++++++++ .../Pages/Admin/ImportExportPage.razor | 231 +++++++++ .../Pages/Admin/ImportExportPage.razor.cs | 391 ++++++++++++++++ src/Khaemhat.Web/Hosting/KhaemhatServices.cs | 11 + .../Resources/it-IT/ImportExport.json | 237 ++++++++++ src/Khaemhat.Web/Resources/it-IT/Shell.json | 3 +- src/Khaemhat.Web/Shell/HelpLinks.cs | 1 + src/Khaemhat.Web/Shell/MenuCatalog.cs | 15 +- src/Khaemhat.Web/wwwroot/app.css | 23 + src/Khaemhat.Web/wwwroot/css/interactive.css | 1 + .../ImportRulesTests.cs | 173 +++++++ .../Files/XlsxReaderTests.cs | 64 +++ .../ImportExport/ImportServiceTests.cs | 178 +++++++ .../Shell/LocalizationRulesTests.cs | 2 +- 29 files changed, 4783 insertions(+), 90 deletions(-) create mode 100644 docs/adr/0031-import-e-export-guidato.md create mode 100644 src/Khaemhat.Application/ImportExport/CheckOnlyImportTargets.cs create mode 100644 src/Khaemhat.Application/ImportExport/ImportFileReader.cs create mode 100644 src/Khaemhat.Application/ImportExport/ImportModel.cs create mode 100644 src/Khaemhat.Application/ImportExport/ImportService.cs create mode 100644 src/Khaemhat.Application/ImportExport/ImportTarget.cs create mode 100644 src/Khaemhat.Application/ImportExport/ImportValues.cs create mode 100644 src/Khaemhat.Application/ImportExport/ItemsImportTarget.cs create mode 100644 src/Khaemhat.Application/ImportExport/PartiesImportTarget.cs create mode 100644 src/Khaemhat.Application/ImportExport/PricesImportTarget.cs create mode 100644 src/Khaemhat.Core/Accounting/AccountType.cs create mode 100644 src/Khaemhat.Infrastructure/Files/XlsxReader.cs create mode 100644 src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor create mode 100644 src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor.cs create mode 100644 src/Khaemhat.Web/Resources/it-IT/ImportExport.json create mode 100644 tests/Khaemhat.Application.Tests/ImportRulesTests.cs create mode 100644 tests/Khaemhat.Infrastructure.Tests/Files/XlsxReaderTests.cs create mode 100644 tests/Khaemhat.Web.Tests/ImportExport/ImportServiceTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 7203944..4654fc8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -68,6 +68,13 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`. - 120 articoli di esempio con listini *Pubblico* e *Rivenditori*, prezzi dell'anno precedente, fornitori, UM e codici alternativi, sostitutivi e prezzi netti di un cliente; `scripts/seed.sh --demo [--scale N]` carica i dati di esempio da riga di comando e moltiplica il catalogo per le prove di prestazione. +- Import/export guidato (ADR 0031) in *Amministrazione → Import / export dati*: CSV (separatore e codifica dedotti), + XLSX (lettore interno, primo foglio) e JSON per clienti, fornitori, articoli e prezzi di listino e netti cliente; + mappatura automatica delle colonne con alias, validazione riga per riga con le regole della scheda, esiti *nuovo*, + *aggiorna*, *avviso*, *errore*, opzioni per codici esistenti o mancanti, VIES e comune da CAP, report errori CSV, + esito nel log. Export con le stesse colonne dell'import e modelli vuoti. Giacenze iniziali e piano dei conti (tracciato + `codice;descrizione;livello;padre;natura;tipo;voce_cee;riclassifica;flag` e `khaemhat-coa.json`) si verificano + già, la scrittura arriva con M6 e M7. ### Changed - Tabella *Listini*: nuovi campi *Listino base* (uno solo) e *Derivato da*; la migrazione marca come base il listino diff --git a/docs/STATUS.md b/docs/STATUS.md index fe26fec..7fb69b1 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -8,10 +8,10 @@ Fatti: pacchetto fiscale (#37), validatori e VIES (#40), tabelle azienda, profil (#38, #39), dati di base e `scripts/seed.sh --base` (#45) con province e comuni ISTAT e CAP GeoNames (ADR 0028; mancano le banche ABI/CAB, senza fonte con licenza compatibile), codici automatici e compilazione automatica (#43), anagrafiche con radar, scheda, controlli, VIES e 21 anagrafiche di esempio (#41, ADR 0029), articoli e listini con prezzi a validità, listini derivati, -aggiornamento massivo, codici delle anagrafiche, 120 articoli di esempio e `seed --demo [--scale N]` (#42, ADR 0030). -ADR 0025-0030. -**Prossimo passo:** import/export guidato (#44), chiusura M4 come `v0.4.0` (#46). #35 (PNG ad alta risoluzione) resta -aperta e non blocca. +aggiornamento massivo, codici delle anagrafiche, 120 articoli di esempio e `seed --demo [--scale N]` (#42, ADR 0030), +import/export guidato CSV/XLSX/JSON con tracciato del piano dei conti (#44, ADR 0031; giacenze e piano dei conti solo +verifica fino a M6/M7). ADR 0025-0031. +**Prossimo passo:** chiusura M4 come `v0.4.0` (#46). #35 (PNG ad alta risoluzione) resta aperta e non blocca. Da recuperare: misure di riferimento su PostgreSQL in `docs/DATA-MODEL.md` §6.1; indicatore di robustezza della password (mockup 003); schede *Layout salvati* (M4) e *Notifiche* (con le e-mail, M5) del profilo; rinomina e filtro predefinito nei radar. @@ -19,7 +19,7 @@ filtro predefinito nei radar. ## Fatto - Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E6. -- ADR 0001-0030. +- ADR 0001-0031. - Mockup in `docs/mockups/` (22 in alta risoluzione + galleria, 88 miniature, `mockup.css`, indice). - Icone in `assets/`; deploy in `deploy/` (compose Unraid, `.env.example`, template Unraid). - Documentazione tecnica: `ARCHITECTURE.md`, `DATA-MODEL.md` (provvisorio, sarà generato), `MODULES.md`, `API.md`, diff --git a/docs/adr/0031-import-e-export-guidato.md b/docs/adr/0031-import-e-export-guidato.md new file mode 100644 index 0000000..1ee4eff --- /dev/null +++ b/docs/adr/0031-import-e-export-guidato.md @@ -0,0 +1,69 @@ +# ADR 0031 - Import e export guidato: entità, tracciati, controlli come da scheda + +- **Stato:** accettata +- **Data:** 2026-11-12 +- **Modifica:** SPEC §11.7, §12.12, mockup 077; milestone M4, issue #44 + +## Contesto + +SPEC §12.12 chiede una procedura guidata di import/export (CSV, XLSX, JSON) per anagrafiche, articoli, listini, +giacenze iniziali, piano dei conti, saldi e partite di apertura, con mappatura delle colonne, validazione riga per +riga, report degli errori e un tracciato proprio del piano dei conti (`codice;descrizione;livello;padre;natura;tipo; +voce_cee;riclassifica;flag` e `khaemhat-coa.json`). Restavano aperti: dove sta la procedura, quali entità esistono già +in M4, come si controllano le righe, che cosa succede ai codici esistenti o mancanti, i valori ammessi di `natura`, +`tipo` e `flag`, come si legge un XLSX senza librerie esterne, chi può esportare. + +## Decisione + +1. **Dove.** Pagina `/amministrazione/import-export` (voce *Import / export dati* sotto *Amministrazione*, visibile + agli account di istanza), consegnata in M4 prima del resto dell'area (M13). Una persona dell'azienda la apre se ha + il permesso di scrittura o di export di almeno un'entità. +2. **Entità.** `IImportTarget` descrive un'entità: chiave, modulo di licenza, permesso di import e di export, colonne + (con alias per l'abbinamento automatico), verifica, scrittura ed export. In M4: `clienti`, `fornitori`, + `articoli`, `listini` (prezzi di listino e netti cliente), `giacenze-iniziali`, `piano-dei-conti`. Le ultime due + **si verificano soltanto** finché non esistono i movimenti di magazzino (M6) e la contabilità (M7): la procedura + prepara il file in anticipo, la scrittura arriva con il modulo. Saldi e partite di apertura arrivano con M7 e M9. +3. **Le righe passano dalla scheda.** Clienti, fornitori e articoli si leggono per codice (o si creano con i valori + proposti dalla scheda), si riempiono con le celle **non vuote** della riga e si controllano e salvano con + `PartyService` e `ItemService`: stesse regole, stessi codici di errore, stesso storico. Una cella vuota lascia il + valore che c'è. I codici di altre tabelle (categoria, pagamento, listino, agente, UM, IVA, deposito) devono + esistere. I prezzi si scrivono con `PriceListService` in una sola transazione (stessa voce e stessa data: + sostituisce; data nuova: aggiunge, come la griglia dei listini, ADR 0030). +4. **Opzioni.** *Se il codice esiste*: aggiorna (predefinito) o salta la riga (avviso). *Codice mancante*: genera con + le regole dei codici automatici (ADR 0027) o errore. Un codice scritto per un record nuovo rispetta la regola + (*codice manuale ammesso*). Un codice ripetuto nel file è un errore dalla seconda riga; un codice di un'anagrafica di + altro tipo è un errore. *Verifica P.IVA su VIES* chiama VIES durante l'import (spento: nessuna chiamata, qualunque + sia l'opzione automatica dell'azienda). *Completa comune da CAP* propone comune e provincia da un CAP con un solo + comune, o il CAP da un comune con un solo CAP, come avviso. +5. **Esiti.** Ogni riga ha *OK*, *avviso* (importabile) o *errore* (esclusa), con colonna, codice del testo e valore. + Si importano solo le righe senza errori; le altre finiscono nel **report errori** (CSV con riga, codice, colonna, + esito, messaggio). L'esito dell'import va nel log, sezione *Sistema*. +6. **Valori.** Numeri all'italiana (`1.234,56`) o con il punto decimale (`1234.56`, come li scrivono XLSX e JSON); + date `gg/mm/aaaa`, ISO, `aaaammgg` o numero seriale del foglio; sì/no come `sì`, `x`, `1`, `VERO`, `true` e i + contrari; le parole di una scelta senza badare a maiuscole, accenti e punteggiatura. +7. **Piano dei conti.** Codice di 1-3 parti separate da punto (mastro, conto, sottoconto); `livello` è il numero di + parti; `padre` è il codice senza l'ultima parte e deve essere nel file; la `natura` (`attivo`, `passivo`, `costo`, + `ricavo`, `ordine`) si eredita dal padre e non può essere diversa; `tipo` è `generico`, `clienti`, `fornitori`, + `banca`, `cassa`, `iva`, `erario` (nuovo `AccountType` in `Khaemhat.Core.Accounting`); `flag` è un insieme di lettere: + `M` movimentabile (solo conti senza sottoconti), `I` rilevante IVA, `P` con partitario, `C` chiusura automatica, + `X` disattivato. `khaemhat-coa.json` è un oggetto `{format, version, accounts, statementLines, journalTemplates, + mappings}`: `accounts` ha le stesse colonne, le altre sezioni si contano e si importano in M7. Il controllo è puro + (`ChartOfAccountsImportValidator`) perché M7 scriva esattamente ciò che accetta. +8. **File.** CSV in UTF-8 (con o senza BOM) o, se non è UTF-8 valido, Windows-1252; separatore `;`, `,` o tabulazione + dedotto dall'intestazione; l'apostrofo che l'export mette davanti al testo che inizia con `=`, `+`, `-`, `@` si + toglie. XLSX: primo foglio letto da `XlsxReader` (System.IO.Compression e XmlReader, DTD vietate, stringhe + condivise, celle in linea, numeri formattati come data restituiti come data). JSON: elenco di oggetti. Al più + 50.000 righe e 25 MB. +9. **Export e modelli.** L'export scrive le stesse colonne dell'import in CSV (`;`, UTF-8 con BOM, numeri e date + all'italiana), XLSX o JSON, così il file si corregge e si reimporta; richiede il permesso di export dell'entità e + il flag utente *Può esportare dati*. Il **modello** è il file con le sole intestazioni (in JSON un oggetto con i + valori vuoti). + +## Conseguenze + +- L'import non ha regole proprie: ogni regola nuova di una scheda vale subito anche per i file. +- Un file di un altro gestionale con codici propri richiede che la regola dei codici ammetta il codice manuale. +- M6 e M7 aggiungono la scrittura di giacenze e piano dei conti senza cambiare tracciati né controlli; M7 e M9 + aggiungono saldi e partite come nuove entità. +- Le righe si scrivono una alla volta (anagrafiche e articoli): un errore a metà non annulla le righe già scritte, + che il report indica come create o aggiornate. diff --git a/docs/wiki/Import-Export.md b/docs/wiki/Import-Export.md index 8d09698..70e4508 100644 --- a/docs/wiki/Import-Export.md +++ b/docs/wiki/Import-Export.md @@ -1,103 +1,163 @@ # Import/Export -> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M4; saldi e partite di apertura in M12) -> **Modulo di licenza:** CORE (piano dei conti, saldi e partite: ACCT/FIN) · **Livello richiesto:** amministratore · **Specifica:** SPEC §11.7, §12.12 +> **Stato:** completa per M4 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (scrittura di giacenze iniziali in M6, piano dei conti in M7; saldi e partite di apertura in M7 e M9) +> **Modulo di licenza:** CORE (piano dei conti: ACCT) · **Livello richiesto:** amministratore, oppure permesso di scrittura o di export dell'entità · **Specifica:** SPEC §11.7, §12.12 · **Decisione:** ADR 0031 ## A cosa serve La procedura guidata di **Import/Export** porta in Khaemhat i dati che arrivano da un altro gestionale o da un foglio di calcolo e li esporta in formati aperti. È lo strumento per l'**avviamento** di un'azienda: anagrafiche, -articoli, listini, giacenze iniziali, piano dei conti, saldi iniziali e partite aperte. +articoli, prezzi, giacenze iniziali e piano dei conti. ## Dove si trova -**Amministrazione → Import/Export** (titolo: *Import / export dati*). Ogni importazione si apre in una scheda -propria (es. *Import clienti*). +**Amministrazione → Import / export dati** (indirizzo `/amministrazione/import-export`). Il tasto **F1** apre questa +pagina. ## Schermata ![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) diff --git a/src/Khaemhat.Application/ImportExport/CheckOnlyImportTargets.cs b/src/Khaemhat.Application/ImportExport/CheckOnlyImportTargets.cs new file mode 100644 index 0000000..108a6b3 --- /dev/null +++ b/src/Khaemhat.Application/ImportExport/CheckOnlyImportTargets.cs @@ -0,0 +1,332 @@ +using Khaemhat.Application.Modules; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Accounting; +using Khaemhat.Core.Items; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.ImportExport; + +/// An account of the chart read from a file. +/// The code, parts separated by points (01.02.003). +/// The description. +/// The level, 1 to 3: the number of parts of the code. +/// The code without its last part. +/// The nature. +/// The use. +/// Postings go on it (only leaves). +/// Relevant for VAT. +/// With a sub-ledger of customers or suppliers. +/// Closed by the year end. +/// Not used any more. +public sealed record ImportedAccount( + string Code, string Description, int Level, string? ParentCode, AccountNature Nature, AccountType Type, bool Postable, bool VatRelevant, bool SubLedger, + bool ClosesAutomatically, bool Disabled); + +/// +/// The checks of a chart of accounts from a file (SPEC §12.12, ADR 0031): codes of one to three parts separated by +/// points, each account under the account whose code is its own without the last part, with the same nature; only +/// leaves are postable. Pure, so that M7 writes what this checks. +/// +public static class ChartOfAccountsImportValidator +{ + /// The words of natura, in the order of . + public static readonly IReadOnlyList NatureWords = ["attivo", "passivo", "costo", "ricavo", "ordine"]; + + /// The words of tipo, in the order of . + public static readonly IReadOnlyList TypeWords = ["generico", "clienti", "fornitori", "banca", "cassa", "iva", "erario"]; + + /// The flag letters: postable, VAT relevant, sub-ledger, automatic closing, disabled. + public const string FlagLetters = "MIPCX"; + + /// The deepest level. + public const int MaxLevel = 3; + + /// The columns of the chart. + public static IReadOnlyList Fields { get; } = + [ + new("codice", ImportFieldKind.Code, Required: true, Aliases: ["conto", "codice_conto", "cod_conto"]), + new("descrizione", Required: true, Aliases: ["descr", "denominazione"]), + new("livello", ImportFieldKind.Number, Aliases: ["liv"]), + new("padre", ImportFieldKind.Code, Aliases: ["conto_padre", "mastro"]), + new("natura", ImportFieldKind.Choice, Aliases: ["sezione"], Choices: NatureWords), + new("tipo", ImportFieldKind.Choice, Aliases: ["tipo_conto"], Choices: TypeWords), + new("voce_cee", Aliases: ["cee", "voce_bilancio"]), + new("riclassifica", Aliases: ["riclassificazione"]), + new("flag", Aliases: ["flags", "attributi"]), + ]; + + /// Checks the rows of a chart. + /// The rows. + /// A result per row, and the accounts without errors. + public static (IReadOnlyList Results, IReadOnlyList Accounts) Check(IReadOnlyList rows) + { + ArgumentNullException.ThrowIfNull(rows); + + // First pass: every code with its nature as written, to check parents wherever they are in the file. + var natures = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var row in rows) + { + if (row["codice"] is { } code) + { + natures.TryAdd(code, Choice(row["natura"], NatureWords) is { } n ? (AccountNature)n : null); + } + } + + var parents = natures.Keys.Select(ParentOf).Where(p => p is not null).ToHashSet(StringComparer.OrdinalIgnoreCase); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + var results = new List(rows.Count); + var accounts = new List(); + foreach (var row in rows) + { + var messages = new List(); + var cells = new CellReader(row, messages); + var code = row["codice"]; + messages.AddRange(Fields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required))); + if (code is null) + { + results.Add(new(row.Line, row["descrizione"] ?? string.Empty, ImportAction.Skip, messages)); + continue; + } + + if (!seen.Add(code)) + { + results.Add(new(row.Line, code, ImportAction.Skip, [new("codice", ImportErrors.CodeRepeated, Value: code)])); + continue; + } + + var parts = code.Split('.'); + var level = parts.Length; + if (level > MaxLevel || parts.Any(p => p.Length == 0 || !p.All(char.IsAsciiLetterOrDigit))) + { + messages.Add(new("codice", ImportErrors.AccountLevel, Value: code)); + } + else if (cells.Number("livello") is { } written && written != level) + { + messages.Add(new("livello", ImportErrors.AccountLevel, Value: level.ToString(System.Globalization.CultureInfo.InvariantCulture))); + } + + var parent = ParentOf(code); + if (row["padre"] is { } named && !string.Equals(named, parent, StringComparison.OrdinalIgnoreCase)) + { + messages.Add(new("padre", ImportErrors.AccountParent, Value: parent ?? string.Empty)); + } + else if (parent is not null && !natures.ContainsKey(parent)) + { + messages.Add(new("padre", ImportErrors.AccountParent, Value: parent)); + } + + var nature = NatureOf(code, natures); + if (nature is null) + { + messages.Add(new("natura", cells.Has("natura") ? ImportErrors.Choice : ImportErrors.Required, Value: cells.Has("natura") ? string.Join(", ", NatureWords) : null)); + } + else if (parent is not null && natures.ContainsKey(parent) && NatureOf(parent, natures) is { } parentNature && parentNature != nature) + { + messages.Add(new("natura", ImportErrors.AccountNature, Value: NatureWords[(int)parentNature])); + } + + var type = cells.Choice(Fields[5]) is { } t ? (AccountType)t : AccountType.Generic; + var flags = (row["flag"] ?? string.Empty).ToUpperInvariant().Where(c => !char.IsWhiteSpace(c) && c is not ',' and not ';').ToList(); + if (flags.FirstOrDefault(c => !FlagLetters.Contains(c, StringComparison.Ordinal)) is var bad && bad != default) + { + messages.Add(new("flag", ImportErrors.AccountFlag, Value: bad.ToString())); + } + + var postable = flags.Contains('M'); + var leaf = !parents.Contains(code); + if (postable && !leaf) + { + messages.Add(new("flag", ImportErrors.AccountPostable)); + } + else if (!postable && leaf && level > 1) + { + messages.Add(new("flag", ImportErrors.AccountLeaf, IsWarning: true)); + } + + if (messages.All(m => m.IsWarning) && nature is { } valid) + { + accounts.Add(new(code, row["descrizione"] ?? string.Empty, level, parent, valid, type, postable, flags.Contains('I'), flags.Contains('P'), flags.Contains('C'), + flags.Contains('X'))); + } + + results.Add(new(row.Line, code, messages.Any(m => !m.IsWarning) ? ImportAction.Skip : ImportAction.Create, messages)); + } + + return (results, accounts); + } + + /// The code without its last part, or for a first level account. + /// The code. + /// The parent code. + public static string? ParentOf(string code) + { + ArgumentNullException.ThrowIfNull(code); + var point = code.LastIndexOf('.'); + return point <= 0 ? null : code[..point]; + } + + // The nature written on the account, else the one of the nearest ancestor that has one. + private static AccountNature? NatureOf(string code, Dictionary natures) + { + for (var current = code; current is not null; current = ParentOf(current)) + { + if (natures.TryGetValue(current, out var nature) && nature is not null) + { + return nature; + } + } + + return null; + } + + private static int? Choice(string? text, IReadOnlyList words) => text is null ? null : ImportValues.Choice(text, words) is var i and >= 0 ? i : null; +} + +/// +/// The chart of accounts (piano-dei-conti): CSV, XLSX or khaemhat-coa.json. Until the ledger exists (M7) +/// the file is only checked; M7 writes the accounts this check accepts. +/// +/// Checks the permission. +public sealed class ChartOfAccountsImportTarget(PermissionService permissions) : IImportTarget +{ + /// The permission to change the chart of accounts. + public const string WritePermission = "ledger.account.write"; + + /// + public string Key => "piano-dei-conti"; + + /// + public string ModuleCode => ModuleCodes.Accounting; + + /// + public string Permission => WritePermission; + + /// + public string ExportPermission => "ledger.account.read"; + + /// + public bool CanApply => false; + + /// + public bool CanExport => false; + + /// + public IReadOnlyList Fields => ChartOfAccountsImportValidator.Fields; + + /// + public async Task> CheckAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false); + return ChartOfAccountsImportValidator.Check(rows).Results; + } + + /// + public Task> ApplyAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) => + throw new InvalidOperationException(ImportErrors.CheckOnly); + + /// + public Task>> ExportAsync(ImportContext context, CancellationToken cancellationToken) => + Task.FromResult>>([]); +} + +/// +/// The opening stock (giacenze-iniziali): item, warehouse, quantity and unit cost. Until the stock entries exist +/// (M6) the file is only checked; M6 writes the opening entry from the rows this check accepts. +/// +/// Opens the company databases. +/// Checks the permission. +public sealed class OpeningStockImportTarget(IUnitOfWorkFactory factory, PermissionService permissions) : IImportTarget +{ + private static readonly ImportField[] StockFields = + [ + new("articolo", ImportFieldKind.Code, Required: true, Aliases: ["codice_articolo", "codice", "cod_articolo", "sku"]), + new("deposito", ImportFieldKind.Code, Aliases: ["magazzino", "codice_magazzino"]), + new("quantita", ImportFieldKind.Number, Required: true, Aliases: ["qta", "qty", "giacenza", "esistenza"]), + new("costo_unitario", ImportFieldKind.Number, Aliases: ["costo", "valore_unitario", "prezzo_acquisto"]), + ]; + + /// + public string Key => "giacenze-iniziali"; + + /// + public string ModuleCode => ModuleCodes.Core; + + /// + public string Permission => "inventory.entry.write"; + + /// + public string ExportPermission => "inventory.stock.read"; + + /// + public bool CanApply => false; + + /// + public bool CanExport => false; + + /// + public IReadOnlyList Fields => StockFields; + + /// + public async Task> CheckAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(rows); + var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false); + await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var items = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items; + var codes = new CodeIndex(items.Select(i => (i.Code, i.Id))); + var byId = items.ToDictionary(i => i.Id); + var warehouses = await CodeIndex.LoadAsync(uow, cancellationToken).ConfigureAwait(false); + var seen = new HashSet<(long, long)>(); + var results = new List(rows.Count); + foreach (var row in rows) + { + var messages = new List(); + var cells = new CellReader(row, messages); + messages.AddRange(StockFields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required))); + var item = cells.Code("articolo", codes) is { } id ? byId[id] : null; + var warehouse = cells.Code("deposito", warehouses) ?? (cells.Has("deposito") ? null : item?.WarehouseId); + if (item is not null && (item.Kind != ItemKind.Goods || !item.Stocked)) + { + messages.Add(new("articolo", ImportErrors.NotStocked, Value: item.Code)); + } + + if (item is not null && warehouse is null && !cells.Has("deposito")) + { + messages.Add(new("deposito", ImportErrors.Required)); + } + + if (cells.Number("quantita") is <= 0) + { + messages.Add(new("quantita", ImportErrors.Positive)); + } + + if (cells.Number("costo_unitario") is < 0) + { + messages.Add(new("costo_unitario", Items.ItemService.NotNegative)); + } + + var label = row["articolo"] ?? string.Empty; + if (item is not null && warehouse is { } w && !seen.Add((item.Id, w))) + { + messages.Add(new("articolo", ImportErrors.CodeRepeated, Value: label)); + } + + results.Add(new(row.Line, label, messages.Any(m => !m.IsWarning) ? ImportAction.Skip : ImportAction.Create, messages)); + } + + return results; + } + + /// + public Task> ApplyAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) => + throw new InvalidOperationException(ImportErrors.CheckOnly); + + /// + public Task>> ExportAsync(ImportContext context, CancellationToken cancellationToken) => + Task.FromResult>>([]); +} diff --git a/src/Khaemhat.Application/ImportExport/ImportFileReader.cs b/src/Khaemhat.Application/ImportExport/ImportFileReader.cs new file mode 100644 index 0000000..17673e7 --- /dev/null +++ b/src/Khaemhat.Application/ImportExport/ImportFileReader.cs @@ -0,0 +1,255 @@ +using System.Globalization; +using System.Text; +using System.Text.Json; +using Khaemhat.Infrastructure.Files; + +namespace Khaemhat.Application.ImportExport; + +/// A file the import cannot use; is one of the import.file.* codes. +public sealed class ImportFileException : Exception +{ + /// Creates the exception. + public ImportFileException() + { + Code = ImportErrors.FileUnreadable; + } + + /// Creates the exception. + /// What went wrong. + public ImportFileException(string message) + : base(message) + { + Code = ImportErrors.FileUnreadable; + } + + /// Creates the exception. + /// What went wrong. + /// The cause. + public ImportFileException(string message, Exception innerException) + : base(message, innerException) + { + Code = ImportErrors.FileUnreadable; + } + + /// Creates the exception with a code. + /// The text code. + /// What went wrong. + /// The cause. + public ImportFileException(string code, string message, Exception? innerException) + : base(message, innerException) + { + Code = code; + } + + /// The text code. + public string Code { get; } +} + +/// +/// Reads the files of the guided import (SPEC §12.12): CSV (UTF-8 with or without byte order mark, else Windows-1252; +/// separator ;, , or tab guessed from the header), XLSX (first sheet) and JSON (an array of objects, or the +/// object of khaemhat-coa.json with its accounts). The first row holds the headers. +/// +public static class ImportFileReader +{ + /// The most data rows an import takes. + public const int MaxRows = 50_000; + + /// The format name written in khaemhat-coa.json. + public const string ChartFormat = "khaemhat-coa"; + + private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); + + /// The format of a file from its name. + /// The name. + /// The format, or when not supported. + public static TransferFormat? FormatOf(string? fileName) => Path.GetExtension(fileName ?? string.Empty).ToUpperInvariant() switch + { + ".CSV" or ".TXT" => TransferFormat.Csv, + ".XLSX" => TransferFormat.Xlsx, + ".JSON" => TransferFormat.Json, + _ => null, + }; + + /// Reads a file. + /// The name, which gives the format. + /// The content. + /// Cancellation. + /// The file with headers and rows. + /// The format is not supported, or the file is empty, damaged or too large. + public static async Task ReadAsync(string fileName, Stream content, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(fileName); + ArgumentNullException.ThrowIfNull(content); + var format = FormatOf(fileName) ?? throw new ImportFileException(ImportErrors.FileFormat, "Not CSV, XLSX or JSON: " + fileName, null); + using var buffer = new MemoryStream(); + await content.CopyToAsync(buffer, cancellationToken).ConfigureAwait(false); + buffer.Position = 0; + return format switch + { + TransferFormat.Xlsx => await ReadXlsxAsync(fileName, buffer, cancellationToken).ConfigureAwait(false), + TransferFormat.Json => ReadJson(fileName, buffer.ToArray()), + _ => ReadCsv(fileName, buffer.ToArray()), + }; + } + + /// Reads CSV bytes. + /// The name. + /// The content. + /// The file. + /// Empty or too large. + public static ImportFile ReadCsv(string fileName, byte[] bytes) + { + ArgumentNullException.ThrowIfNull(bytes); + string text; + string encoding; + var start = bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF ? 3 : 0; + try + { + text = StrictUtf8.GetString(bytes, start, bytes.Length - start); + encoding = "UTF-8"; + } + catch (DecoderFallbackException) + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + text = Encoding.GetEncoding(1252).GetString(bytes); + encoding = "Windows-1252"; + } + + var separator = Guess(text); + var lines = CsvReader.Parse(text, separator); + return Build(fileName, TransferFormat.Csv, encoding, separator, lines, null); + } + + private static async Task ReadXlsxAsync(string fileName, Stream content, CancellationToken cancellationToken) + { + try + { + var rows = await XlsxReader.ReadAsync(content, cancellationToken).ConfigureAwait(false); + return Build(fileName, TransferFormat.Xlsx, null, null, rows, null); + } + catch (XlsxReadException ex) + { + throw new ImportFileException(ImportErrors.FileUnreadable, ex.Message, ex); + } + } + + private static ImportFile ReadJson(string fileName, byte[] bytes) + { + JsonDocument document; + try + { + document = JsonDocument.Parse(bytes, new JsonDocumentOptions { MaxDepth = 16, AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip }); + } + catch (JsonException ex) + { + throw new ImportFileException(ImportErrors.FileUnreadable, ex.Message, ex); + } + + using (document) + { + var root = document.RootElement; + Dictionary? sections = null; + JsonElement records; + if (root.ValueKind == JsonValueKind.Array) + { + records = root; + } + else if (root.ValueKind == JsonValueKind.Object && root.TryGetProperty("accounts", out var accounts) && accounts.ValueKind == JsonValueKind.Array) + { + records = accounts; + sections = new Dictionary(StringComparer.Ordinal); + foreach (var property in root.EnumerateObject()) + { + if (property.Name != "accounts" && property.Value.ValueKind == JsonValueKind.Array) + { + sections[property.Name] = property.Value.GetArrayLength(); + } + } + } + else + { + throw new ImportFileException(ImportErrors.FileUnreadable, "Neither an array of objects nor a chart of accounts.", null); + } + + var headers = new List(); + var index = new Dictionary(StringComparer.Ordinal); + var objects = new List>(); + foreach (var element in records.EnumerateArray()) + { + if (element.ValueKind != JsonValueKind.Object) + { + throw new ImportFileException(ImportErrors.FileUnreadable, "An entry is not an object.", null); + } + + var values = new Dictionary(StringComparer.Ordinal); + foreach (var property in element.EnumerateObject()) + { + if (index.TryAdd(property.Name, headers.Count)) + { + headers.Add(property.Name); + } + + values[property.Name] = Cell(property.Value); + } + + objects.Add(values); + } + + var rows = new List> { headers }; + rows.AddRange(objects.Select(o => (IReadOnlyList)[.. headers.Select(h => o.GetValueOrDefault(h, string.Empty))])); + return Build(fileName, TransferFormat.Json, "UTF-8", null, rows, sections); + } + } + + private static string Cell(JsonElement value) => value.ValueKind switch + { + JsonValueKind.String => value.GetString() ?? string.Empty, + JsonValueKind.Number => value.GetRawText(), + JsonValueKind.True => "true", + JsonValueKind.False => "false", + JsonValueKind.Null or JsonValueKind.Undefined => string.Empty, + _ => value.GetRawText(), + }; + + private static ImportFile Build(string fileName, TransferFormat format, string? encoding, char? separator, IReadOnlyList> lines, + IReadOnlyDictionary? sections) + { + if (lines.Count == 0 || lines[0].All(string.IsNullOrWhiteSpace)) + { + throw new ImportFileException(ImportErrors.FileEmpty, "No header.", null); + } + + if (lines.Count - 1 > MaxRows) + { + throw new ImportFileException(ImportErrors.FileTooLarge, "More than " + MaxRows.ToString(CultureInfo.InvariantCulture) + " rows.", null); + } + + var headers = lines[0].Select((h, i) => string.IsNullOrWhiteSpace(h) ? "colonna_" + (i + 1).ToString(CultureInfo.InvariantCulture) : h.Trim()).ToList(); + var rows = new List>(lines.Count - 1); + foreach (var line in lines.Skip(1)) + { + if (line.All(string.IsNullOrWhiteSpace)) + { + continue; + } + + rows.Add([.. Enumerable.Range(0, headers.Count).Select(i => i < line.Count ? Unprotect(line[i]) : string.Empty)]); + } + + return new ImportFile(Path.GetFileName(fileName), format, encoding, separator, headers, rows, sections); + } + + // The apostrophe the export puts before text that a spreadsheet would read as a formula (CsvWriter). + private static string Unprotect(string cell) => + cell.Length > 1 && cell[0] == '\'' && cell[1] is '=' or '+' or '-' or '@' ? cell[1..].Trim() : cell.Trim(); + + private static char Guess(string text) + { + var end = text.IndexOfAny(['\r', '\n']); + var first = end < 0 ? text : text[..end]; + return Separators.OrderByDescending(s => first.Count(c => c == s)).First(); + } + + private static readonly char[] Separators = [';', ',', '\t']; +} diff --git a/src/Khaemhat.Application/ImportExport/ImportModel.cs b/src/Khaemhat.Application/ImportExport/ImportModel.cs new file mode 100644 index 0000000..dcda65b --- /dev/null +++ b/src/Khaemhat.Application/ImportExport/ImportModel.cs @@ -0,0 +1,197 @@ +using Khaemhat.Application.Security; + +namespace Khaemhat.Application.ImportExport; + +/// The formats of the guided import and export (SPEC §12.12). +public enum TransferFormat +{ + /// Text with ;, UTF-8 (other separators and Windows-1252 are recognized when reading). + Csv = 0, + + /// Excel workbook, first sheet, headers in the first row. + Xlsx = 1, + + /// JSON: an array of objects keyed by column, or the object of khaemhat-coa.json. + Json = 2, +} + +/// The kind of value of a column, for reading and writing it. +public enum ImportFieldKind +{ + /// Free text. + Text = 0, + + /// A code of another archive or table. + Code = 1, + + /// A decimal number (Italian or invariant notation). + Number = 2, + + /// A date (dd/MM/yyyy, ISO or a spreadsheet serial). + Date = 3, + + /// Yes or no. + Boolean = 4, + + /// One of a list of words. + Choice = 5, +} + +/// A column an entity accepts. +/// The column name used in files and templates (partita_iva). +/// The kind of value. +/// Whether a new record needs it. +/// Other headers recognized by the automatic mapping, already normalized. +/// The words accepted for . +public sealed record ImportField(string Key, ImportFieldKind Kind = ImportFieldKind.Text, bool Required = false, IReadOnlyList? Aliases = null, + IReadOnlyList? Choices = null); + +/// A file read for the import. +/// The file name. +/// The format. +/// The text encoding (CSV), such as UTF-8. +/// The separator (CSV). +/// The headers of the columns. +/// The rows under the headers, each as long as the headers. +/// For khaemhat-coa.json: the other sections with their number of entries. +public sealed record ImportFile(string Name, TransferFormat Format, string? Encoding, char? Separator, IReadOnlyList Headers, + IReadOnlyList> Rows, IReadOnlyDictionary? Sections = null) +{ + /// The number of data rows. + public int Count => Rows.Count; +} + +/// What happens to a row whose code is already in the archive. +public enum ExistingCodeAction +{ + /// The record is updated with the non empty cells of the row. + Update = 0, + + /// The row is skipped. + Skip = 1, +} + +/// What happens to a row without a code. +public enum MissingCodeAction +{ + /// The code comes from the automatic code rules. + Generate = 0, + + /// The row is an error. + Refuse = 1, +} + +/// The options of an import (mockup 077, step 1). +public sealed record ImportOptions +{ + /// Rows whose code exists. + public ExistingCodeAction Existing { get; init; } = ExistingCodeAction.Update; + + /// Rows without a code. + public MissingCodeAction Missing { get; init; } = MissingCodeAction.Generate; + + /// Check the VAT numbers of EU parties on VIES while importing. + public bool VerifyVat { get; init; } + + /// Fill the city from the postal code (and the postal code from the city) when one is missing. + public bool FillFromPostalCode { get; init; } = true; +} + +/// Who imports, where and how: what a target needs besides the rows. +/// Who imports. +/// The company. +/// The options. +public sealed record ImportContext(Actor Actor, string CompanyCode, ImportOptions Options); + +/// A row of the file with the cells of the mapped columns by field key. +/// The line in the file, counting the header as line 1. +/// The trimmed cells by field key; empty cells are left out. +public sealed record ImportRow(int Line, IReadOnlyDictionary Values) +{ + /// The cell of a field, or when empty or not mapped. + /// The field. + /// The text. + public string? this[string key] => Values.TryGetValue(key, out var value) ? value : null; +} + +/// The outcome of a row in the preview (mockup 077: OK, avviso, errore). +public enum ImportOutcome +{ + /// Importable. + Ok = 0, + + /// Importable, with a correction proposed or a remark. + Warning = 1, + + /// Not importable. + Error = 2, +} + +/// What the import does with a row. +public enum ImportAction +{ + /// A new record. + Create = 0, + + /// An existing record changes. + Update = 1, + + /// Nothing (existing code to skip, or an error). + Skip = 2, +} + +/// A remark on a row: a text code with the field it concerns. +/// The field key, or empty for the whole row. +/// The text code (an error code of the services or import.*). +/// A warning instead of an error. +/// A value to show in the text ({0}), such as the code not found or the city proposed. +public sealed record ImportMessage(string Field, string Code, bool IsWarning = false, string? Value = null); + +/// The check of a row. +/// The line in the file. +/// The code or description that identifies the row in the preview. +/// What the import will do. +/// The remarks. +public sealed record ImportRowResult(int Line, string Key, ImportAction Action, IReadOnlyList Messages) +{ + /// The outcome from the remarks. + public ImportOutcome Outcome => + Messages.Any(m => !m.IsWarning) ? ImportOutcome.Error : Messages.Count > 0 ? ImportOutcome.Warning : ImportOutcome.Ok; +} + +/// The preview of an import (mockup 077, steps 3 and 4). +/// The entity. +/// The checked rows, in file order. +/// Whether the entity can be written now (opening stock and chart of accounts only check, until M6 and M7). +public sealed record ImportPreview(string Target, IReadOnlyList Rows, bool CanApply) +{ + /// Rows that will create a record. + public int Creates => Rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Create); + + /// Rows that will update a record. + public int Updates => Rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Update); + + /// Rows skipped on purpose. + public int Skips => Rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Skip); + + /// Rows with errors. + public int Errors => Rows.Count(r => r.Outcome == ImportOutcome.Error); + + /// Rows with warnings only. + public int Warnings => Rows.Count(r => r.Outcome == ImportOutcome.Warning); + + /// Rows the import writes. + public int Importable => Creates + Updates; +} + +/// The result of an import. +/// The entity. +/// Records created. +/// Records updated. +/// Rows skipped on purpose. +/// Every row with its final outcome; rows refused while writing carry their errors. +public sealed record ImportReport(string Target, int Created, int Updated, int Skipped, IReadOnlyList Rows) +{ + /// Rows not imported because of errors. + public int Failed => Rows.Count(r => r.Outcome == ImportOutcome.Error); +} diff --git a/src/Khaemhat.Application/ImportExport/ImportService.cs b/src/Khaemhat.Application/ImportExport/ImportService.cs new file mode 100644 index 0000000..ed29dca --- /dev/null +++ b/src/Khaemhat.Application/ImportExport/ImportService.cs @@ -0,0 +1,375 @@ +using System.Text.Json; +using Khaemhat.Application.Licensing; +using Khaemhat.Application.Security; +using Khaemhat.Core.Logging; +using Khaemhat.Infrastructure.Files; +using Microsoft.Extensions.Logging; + +namespace Khaemhat.Application.ImportExport; + +/// +/// The guided import and export (SPEC §11.7, §12.12, mockup 077, ADR 0031): the entities the licence allows, the +/// automatic mapping of the columns, the preview that checks every row as if typed in its record, the import of the +/// rows without errors, the error report, the export with the same columns and the empty templates. +/// +public sealed partial class ImportService +{ + private static readonly JsonWriterOptions JsonOptions = new() { Indented = true }; + + private readonly IReadOnlyList _targets; + private readonly ILicenseGate _license; + private readonly PermissionService _permissions; + private readonly ILogger _logger; + + /// Creates the service. + /// The entities. + /// The licence. + /// The permissions and the user flags. + /// The log. + public ImportService(IEnumerable targets, ILicenseGate license, PermissionService permissions, ILogger logger) + { + ArgumentNullException.ThrowIfNull(targets); + ArgumentNullException.ThrowIfNull(license); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(logger); + _targets = [.. targets]; + _license = license; + _permissions = permissions; + _logger = logger; + } + + /// The entities whose module is licensed, in the order of the screen. + public IReadOnlyList Targets => [.. _targets.Where(t => _license.IsModuleActive(t.ModuleCode))]; + + /// A licensed entity by key. + /// The key. + /// The entity. + /// Unknown or not licensed (). + public IImportTarget Target(string key) => + Targets.FirstOrDefault(t => string.Equals(t.Key, key, StringComparison.OrdinalIgnoreCase)) + ?? throw new ImportFileException(ImportErrors.TargetUnknown, "Unknown import: " + key, null); + + /// + /// The field of each column of a file, by name or alias ignoring case, accents and punctuation; a field goes to one + /// column only. + /// + /// The entity. + /// The headers. + /// The field key per column, or for columns to ignore. + public static IReadOnlyList SuggestMapping(IImportTarget target, IReadOnlyList headers) + { + ArgumentNullException.ThrowIfNull(target); + ArgumentNullException.ThrowIfNull(headers); + var taken = new HashSet(StringComparer.Ordinal); + var mapping = new string?[headers.Count]; + for (var pass = 0; pass < 2; pass++) + { + for (var i = 0; i < headers.Count; i++) + { + if (mapping[i] is not null) + { + continue; + } + + var header = ImportValues.Normalize(headers[i]); + var field = target.Fields.FirstOrDefault(f => !taken.Contains(f.Key) + && (pass == 0 ? f.Key == header : (f.Aliases ?? []).Any(a => ImportValues.Normalize(a) == header))); + if (field is not null) + { + mapping[i] = field.Key; + taken.Add(field.Key); + } + } + } + + return mapping; + } + + /// The rows of a file with the cells of the mapped columns. + /// The file. + /// The field key per column, or . + /// The rows, line numbers counting the header as line 1. + public static IReadOnlyList Rows(ImportFile file, IReadOnlyList mapping) + { + ArgumentNullException.ThrowIfNull(file); + ArgumentNullException.ThrowIfNull(mapping); + var rows = new List(file.Count); + for (var r = 0; r < file.Count; r++) + { + var values = new Dictionary(StringComparer.Ordinal); + var cells = file.Rows[r]; + for (var c = 0; c < mapping.Count && c < cells.Count; c++) + { + if (mapping[c] is { } key && !string.IsNullOrWhiteSpace(cells[c])) + { + values.TryAdd(key, cells[c].Trim()); + } + } + + rows.Add(new ImportRow(r + 2, values)); + } + + return rows; + } + + /// Checks a file without writing (steps 2 and 3 of the screen). + /// Who imports. + /// The company. + /// The entity. + /// The file. + /// The field per column. + /// The options. + /// Cancellation. + /// The preview. + public async Task PreviewAsync(Actor actor, string companyCode, string targetKey, ImportFile file, IReadOnlyList mapping, ImportOptions options, + CancellationToken cancellationToken = default) + { + var target = Target(targetKey); + var context = new ImportContext(actor, companyCode, options ?? new ImportOptions()); + var rows = await target.CheckAsync(context, Rows(file, mapping), cancellationToken).ConfigureAwait(false); + return new ImportPreview(target.Key, rows, target.CanApply); + } + + /// Imports the rows without errors (step 4); rows with errors are left out and reported. + /// Who imports. + /// The company. + /// The entity. + /// The file. + /// The field per column. + /// The options. + /// Cancellation. + /// What was done. + /// The entity is only checked for now (). + public async Task ImportAsync(Actor actor, string companyCode, string targetKey, ImportFile file, IReadOnlyList mapping, ImportOptions options, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(file); + var target = Target(targetKey); + if (!target.CanApply) + { + throw new ImportFileException(ImportErrors.CheckOnly, "Only checked for now: " + target.Key, null); + } + + var context = new ImportContext(actor, companyCode, options ?? new ImportOptions()); + var rows = await target.ApplyAsync(context, Rows(file, mapping), cancellationToken).ConfigureAwait(false); + var report = new ImportReport( + target.Key, + rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Create), + rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Update), + rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Skip), + rows); + using (_logger.BeginScope(LogSections.Scope(LogSection.System))) + { + LogImported(_logger, target.Key, file.Name, companyCode, actor.UserName, report.Created, report.Updated, report.Skipped, report.Failed); + } + + return report; + } + + /// Writes the rows with errors and warnings as CSV (button Scarica report errori). + /// The checked rows. + /// The text of a remark, in the language of the user. + /// The headers: line, key, column, outcome, message. + /// Where to write. + /// Cancellation. + /// A task. + public static async Task WriteErrorReportAsync(IReadOnlyList rows, Func text, + IReadOnlyList labels, Stream output, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(rows); + ArgumentNullException.ThrowIfNull(text); + ArgumentNullException.ThrowIfNull(labels); + await using var csv = new CsvWriter(output, CsvOptions.Italian, leaveOpen: true); + await csv.WriteRowAsync(labels, cancellationToken).ConfigureAwait(false); + foreach (var row in rows) + { + foreach (var message in row.Messages) + { + var (outcome, line) = text(row, message); + await csv.WriteRowAsync([row.Line, row.Key, message.Field, outcome, line], cancellationToken).ConfigureAwait(false); + } + } + + await csv.FlushAsync(cancellationToken).ConfigureAwait(false); + } + + /// Exports an entity with the columns of its import, so that the file can be imported again. + /// Who exports: needs the export permission of the entity and the can export flag. + /// The company. + /// The entity. + /// The format. + /// Where to write. + /// Cancellation. + /// The number of records written. + /// The user cannot export. + public async Task ExportAsync(Actor actor, string companyCode, string targetKey, TransferFormat format, Stream output, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var target = Target(targetKey); + if (!(await _permissions.GetAsync(actor, cancellationToken).ConfigureAwait(false)).Flags.CanExport) + { + throw new AccessDeniedException(SecurityErrors.PermissionDenied, "The user cannot export."); + } + + var rows = target.CanExport + ? await target.ExportAsync(new ImportContext(actor, companyCode, new ImportOptions()), cancellationToken).ConfigureAwait(false) + : []; + await WriteAsync(target, format, rows, output, cancellationToken).ConfigureAwait(false); + using (_logger.BeginScope(LogSections.Scope(LogSection.System))) + { + LogExported(_logger, target.Key, format, companyCode, actor.UserName, rows.Count); + } + + return rows.Count; + } + + /// Writes the empty template of an entity: the headers only (for JSON, one object with empty values). + /// The entity. + /// The format. + /// Where to write. + /// Cancellation. + /// A task. + public static Task WriteTemplateAsync(IImportTarget target, TransferFormat format, Stream output, CancellationToken cancellationToken = default) => + WriteAsync(target, format, [], output, cancellationToken); + + /// The name of an export or template file (clienti-2026-11-12.csv, modello-clienti.xlsx). + /// The entity. + /// The format. + /// The day of an export, or for a template. + /// The file name. + public static string FileName(string targetKey, TransferFormat format, DateOnly? date) + { + var extension = format switch + { + TransferFormat.Xlsx => ".xlsx", + TransferFormat.Json => ".json", + _ => ".csv", + }; + return date is { } day + ? targetKey + "-" + day.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture) + extension + : "modello-" + targetKey + extension; + } + + /// The media type of a format. + /// The format. + /// The media type. + public static string MediaType(TransferFormat format) => format switch + { + TransferFormat.Xlsx => XlsxWriter.MediaType, + TransferFormat.Json => "application/json", + _ => "text/csv", + }; + + private static async Task WriteAsync(IImportTarget target, TransferFormat format, IReadOnlyList> rows, Stream output, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(target); + ArgumentNullException.ThrowIfNull(output); + var headers = target.Fields.Select(f => f.Key).ToList(); + switch (format) + { + case TransferFormat.Xlsx: + await using (var xlsx = await XlsxWriter.CreateAsync(output, leaveOpen: true, cancellationToken: cancellationToken).ConfigureAwait(false)) + { + await xlsx.StartSheetAsync(target.Key, [.. target.Fields.Select(Column)], cancellationToken).ConfigureAwait(false); + foreach (var row in rows) + { + await xlsx.WriteRowAsync(row, cancellationToken).ConfigureAwait(false); + } + + await xlsx.CompleteAsync(cancellationToken).ConfigureAwait(false); + } + + break; + case TransferFormat.Json: + await WriteJsonAsync(target, headers, rows, output, cancellationToken).ConfigureAwait(false); + break; + default: + await using (var csv = new CsvWriter(output, CsvOptions.Italian, leaveOpen: true)) + { + await csv.WriteRowAsync(headers, cancellationToken).ConfigureAwait(false); + foreach (var row in rows) + { + await csv.WriteRowAsync(row, cancellationToken).ConfigureAwait(false); + } + + await csv.FlushAsync(cancellationToken).ConfigureAwait(false); + } + + break; + } + } + + private static XlsxColumn Column(ImportField field) => new(field.Key, field.Kind switch + { + ImportFieldKind.Text => 28, + ImportFieldKind.Number or ImportFieldKind.Date => 14, + _ => 16, + }); + + private static async Task WriteJsonAsync(IImportTarget target, List headers, IReadOnlyList> rows, Stream output, + CancellationToken cancellationToken) + { + await using var json = new Utf8JsonWriter(output, JsonOptions); + var chart = target is ChartOfAccountsImportTarget; + if (chart) + { + json.WriteStartObject(); + json.WriteString("format", ImportFileReader.ChartFormat); + json.WriteNumber("version", 1); + json.WritePropertyName("accounts"); + } + + json.WriteStartArray(); + IEnumerable> objects = rows.Count > 0 ? rows : [new object?[headers.Count]]; + foreach (var row in objects) + { + json.WriteStartObject(); + for (var i = 0; i < headers.Count; i++) + { + var value = i < row.Count ? row[i] : null; + switch (value) + { + case null: + json.WriteString(headers[i], string.Empty); + break; + case decimal number: + json.WriteNumber(headers[i], number); + break; + case bool flag: + json.WriteBoolean(headers[i], flag); + break; + case DateOnly day: + json.WriteString(headers[i], day.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture)); + break; + default: + json.WriteString(headers[i], Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture)); + break; + } + } + + json.WriteEndObject(); + } + + json.WriteEndArray(); + if (chart) + { + foreach (var section in new[] { "statementLines", "journalTemplates", "mappings" }) + { + json.WriteStartArray(section); + json.WriteEndArray(); + } + + json.WriteEndObject(); + } + + await json.FlushAsync(cancellationToken).ConfigureAwait(false); + } + + [LoggerMessage(EventId = 7101, Level = LogLevel.Information, + Message = "Import {Target} from {File} in {Company} by {User}: {Created} created, {Updated} updated, {Skipped} skipped, {Failed} with errors")] + private static partial void LogImported(ILogger logger, string target, string file, string company, string user, int created, int updated, int skipped, int failed); + + [LoggerMessage(EventId = 7102, Level = LogLevel.Information, Message = "Export {Target} as {Format} from {Company} by {User}: {Count} records")] + private static partial void LogExported(ILogger logger, string target, TransferFormat format, string company, string user, int count); +} diff --git a/src/Khaemhat.Application/ImportExport/ImportTarget.cs b/src/Khaemhat.Application/ImportExport/ImportTarget.cs new file mode 100644 index 0000000..ccd0664 --- /dev/null +++ b/src/Khaemhat.Application/ImportExport/ImportTarget.cs @@ -0,0 +1,442 @@ +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.ImportExport; + +/// +/// An entity of the guided import and export (SPEC §12.12): its columns, the check of the rows as if typed in its +/// record, the writing through its own service, and the export with the same columns so that a file exported can be +/// imported again. +/// +public interface IImportTarget +{ + /// The key in addresses and texts (clienti, piano-dei-conti). + string Key { get; } + + /// The licence module the entity belongs to. + string ModuleCode { get; } + + /// The permission to import it (the write permission of its record). + string Permission { get; } + + /// The permission to export it (besides the can export flag of the user). + string ExportPermission { get; } + + /// Whether rows can be written now; otherwise the file is only checked (opening stock until M6, chart of accounts until M7). + bool CanApply { get; } + + /// Whether there are records to export now. + bool CanExport { get; } + + /// The columns, in the order of templates and exports. + IReadOnlyList Fields { get; } + + /// Checks the rows without writing. + /// Who, where, how. + /// The rows. + /// Cancellation. + /// A result per row, in order. + Task> CheckAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken); + + /// Writes the rows without errors, each like a save of its record. + /// Who, where, how. + /// The rows. + /// Cancellation. + /// A result per row, in order, with what was done. + Task> ApplyAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken); + + /// The records as rows of cells in the order of . + /// Who, where. + /// Cancellation. + /// The rows. + Task>> ExportAsync(ImportContext context, CancellationToken cancellationToken); +} + +/// Reads the cells of a row as values, adding a remark for every cell that is not what its field wants. +/// The row. +/// Where the remarks go. +public sealed class CellReader(ImportRow row, List messages) +{ + /// The row. + public ImportRow Row => row; + + /// The remarks so far. + public List Messages => messages; + + /// Whether the cell has a value. + /// The field. + /// when not empty. + public bool Has(string key) => row[key] is not null; + + /// The text of a cell. + /// The field. + /// The text, or . + public string? Text(string key) => row[key]; + + /// A number. + /// The field. + /// The number, or when empty or wrong (with a remark). + public decimal? Number(string key) + { + if (row[key] is not { } text) + { + return null; + } + + if (ImportValues.TryNumber(text, out var value)) + { + return value; + } + + messages.Add(new(key, ImportErrors.Number, Value: text)); + return null; + } + + /// A date. + /// The field. + /// The date, or when empty or wrong (with a remark). + public DateOnly? Date(string key) + { + if (row[key] is not { } text) + { + return null; + } + + if (ImportValues.TryDate(text, out var value)) + { + return value; + } + + messages.Add(new(key, ImportErrors.Date, Value: text)); + return null; + } + + /// Yes or no. + /// The field. + /// The value, or when empty or wrong (with a remark). + public bool? Boolean(string key) + { + if (row[key] is not { } text) + { + return null; + } + + if (ImportValues.TryBoolean(text, out var value)) + { + return value; + } + + messages.Add(new(key, ImportErrors.Boolean, Value: text)); + return null; + } + + /// One of the words of a field. + /// The field with its choices. + /// The position of the word, or when empty or unknown (with a remark). + public int? Choice(ImportField field) + { + ArgumentNullException.ThrowIfNull(field); + if (row[field.Key] is not { } text) + { + return null; + } + + var choices = field.Choices ?? []; + var index = ImportValues.Choice(text, choices); + if (index >= 0) + { + return index; + } + + messages.Add(new(field.Key, ImportErrors.Choice, Value: string.Join(", ", choices))); + return null; + } + + /// The id of a code of another archive or table. + /// The field. + /// The codes. + /// The id, or when empty or unknown (with a remark). + public long? Code(string key, CodeIndex index) + { + ArgumentNullException.ThrowIfNull(index); + if (row[key] is not { } code) + { + return null; + } + + if (index.Find(code) is { } id) + { + return id; + } + + messages.Add(new(key, ImportErrors.CodeUnknown, Value: code)); + return null; + } +} + +/// The ids of the records of an archive or table by code, ignoring case. +public sealed class CodeIndex +{ + private readonly Dictionary _ids = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _codes = []; + + /// Creates an index. + /// The codes with their ids. + public CodeIndex(IEnumerable<(string Code, long Id)> entries) + { + ArgumentNullException.ThrowIfNull(entries); + foreach (var (code, id) in entries) + { + _ids.TryAdd(code, id); + _codes[id] = code; + } + } + + /// The number of codes. + public int Count => _ids.Count; + + /// Loads the codes of a table of the company. + /// The table. + /// The unit of work. + /// Cancellation. + /// The index. + public static async Task LoadAsync(IUnitOfWork uow, CancellationToken cancellationToken) + where T : CodedEntity, new() + { + ArgumentNullException.ThrowIfNull(uow); + var rows = await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false); + return new CodeIndex(rows.Items.Select(r => (r.Code, r.Id))); + } + + /// The id of a code. + /// The code. + /// The id, or . + public long? Find(string? code) => code is not null && _ids.TryGetValue(code.Trim(), out var id) ? id : null; + + /// The code of an id. + /// The id. + /// The code, or . + public string? CodeOf(long? id) => id is { } key && _codes.TryGetValue(key, out var code) ? code : null; + + /// Adds a code written meanwhile. + /// The code. + /// The id. + public void Add(string code, long id) + { + ArgumentNullException.ThrowIfNull(code); + _ids[code] = id; + _codes[id] = code; + } +} + +/// +/// The common steps of the entities written as records (parties, items): each row becomes a record, new or read by its +/// code, checked by the service of the record and saved by it, so the import obeys the same rules as the screen. +/// +/// The record. +/// What is loaded once per check or import (codes of tables and archives). +public abstract class RecordImportTarget : IImportTarget + where TRecord : class +{ + /// + public abstract string Key { get; } + + /// + public abstract string ModuleCode { get; } + + /// + public abstract string Permission { get; } + + /// + public abstract string ExportPermission { get; } + + /// + public bool CanApply => true; + + /// + public bool CanExport => true; + + /// + public abstract IReadOnlyList Fields { get; } + + /// The column with the code of the record. + protected virtual string CodeField => "codice"; + + /// + public Task> CheckAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) => + RunAsync(context, rows, write: false, cancellationToken); + + /// + public Task> ApplyAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) => + RunAsync(context, rows, write: true, cancellationToken); + + /// + public abstract Task>> ExportAsync(ImportContext context, CancellationToken cancellationToken); + + /// Loads what every row needs, checking a permission. + /// Who, where, how. + /// The permission demanded (to import or to export). + /// Cancellation. + /// The state. + protected abstract Task LoadAsync(ImportContext context, string permission, CancellationToken cancellationToken); + + /// The id of an existing record with a code, or ; a remark refuses the code (another kind). + /// The state. + /// The code. + /// Where remarks go. + /// The id. + protected abstract long? Existing(TState state, string code, List messages); + + /// A new record, or an existing one read by id. + /// Who, where. + /// The id, or for a new record. + /// Cancellation. + /// The record. + protected abstract Task OpenAsync(ImportContext context, long? id, CancellationToken cancellationToken); + + /// Copies the cells of a row into the record; a code given for a new record is set too. + /// Who, where, how. + /// The state. + /// The record. + /// The row with its remarks. + /// Whether the record is new. + /// Cancellation. + /// A task. + protected abstract Task FillAsync(ImportContext context, TState state, TRecord record, CellReader cells, bool isNew, CancellationToken cancellationToken); + + /// Checks a record with the rules of its service. + /// Who, where. + /// The record. + /// Whether the record is new (its code is checked against the code rules). + /// Cancellation. + /// The problems. + protected abstract Task> ValidateAsync(ImportContext context, TRecord record, bool isNew, CancellationToken cancellationToken); + + /// Saves a record with its service. + /// Who, where, how. + /// The record. + /// Cancellation. + /// The code and id given by the save. + protected abstract Task<(string Code, long Id)> SaveAsync(ImportContext context, TRecord record, CancellationToken cancellationToken); + + /// What identifies the row in the preview (code, else description). + /// The row. + /// The text. + protected abstract string Label(ImportRow row); + + /// Records a code saved, so that later rows find it. + /// The state. + /// The code. + /// The id. + protected abstract void Remember(TState state, string code, long id); + + /// The column of a field of the service (VatNumber, Fiscal.RecipientCode); empty for the row. + /// The field named by the service. + /// The column key. + protected abstract string ColumnOf(string serviceField); + + private async Task> RunAsync(ImportContext context, IReadOnlyList rows, bool write, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(rows); + var state = await LoadAsync(context, Permission, cancellationToken).ConfigureAwait(false); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + var results = new List(rows.Count); + foreach (var row in rows) + { + cancellationToken.ThrowIfCancellationRequested(); + var messages = new List(); + var cells = new CellReader(row, messages); + var code = row[CodeField]; + long? id = null; + if (code is not null) + { + if (!seen.Add(code)) + { + messages.Add(new(CodeField, ImportErrors.CodeRepeated, Value: code)); + results.Add(new(row.Line, Label(row), ImportAction.Skip, messages)); + continue; + } + + id = Existing(state, code, messages); + if (messages.Count > 0) + { + results.Add(new(row.Line, Label(row), ImportAction.Skip, messages)); + continue; + } + + if (id is not null && context.Options.Existing == ExistingCodeAction.Skip) + { + results.Add(new(row.Line, Label(row), ImportAction.Skip, [new(CodeField, ImportErrors.CodeExists, IsWarning: true, Value: code)])); + continue; + } + } + else if (context.Options.Missing == MissingCodeAction.Refuse) + { + messages.Add(new(CodeField, ImportErrors.CodeMissing)); + results.Add(new(row.Line, Label(row), ImportAction.Skip, messages)); + continue; + } + + var isNew = id is null; + var action = isNew ? ImportAction.Create : ImportAction.Update; + var record = await OpenAsync(context, id, cancellationToken).ConfigureAwait(false); + if (record is null) + { + messages.Add(new(CodeField, ImportErrors.WriteFailed, Value: code)); + results.Add(new(row.Line, Label(row), ImportAction.Skip, messages)); + continue; + } + + await FillAsync(context, state, record, cells, isNew, cancellationToken).ConfigureAwait(false); + if (isNew) + { + messages.AddRange(Fields.Where(f => f.Required && !cells.Has(f.Key) && messages.All(m => m.Field != f.Key)) + .Select(f => new ImportMessage(f.Key, ImportErrors.Required))); + } + + if (messages.All(m => m.IsWarning)) + { + messages.AddRange((await ValidateAsync(context, record, isNew, cancellationToken).ConfigureAwait(false)) + .Select(p => new ImportMessage(ColumnOf(p.Field), p.Code, p.IsWarning))); + } + + if (write && messages.All(m => m.IsWarning)) + { + try + { + var (savedCode, savedId) = await SaveAsync(context, record, cancellationToken).ConfigureAwait(false); + Remember(state, savedCode, savedId); + } + catch (ValidationFailedException ex) + { + messages.AddRange(ex.Errors.Select(TableErrors.Split).Select(e => new ImportMessage(ColumnOf(e.Field), e.Code))); + } + catch (Core.Common.ConcurrencyException) + { + messages.Add(new(string.Empty, ImportErrors.WriteFailed)); + } + } + + results.Add(new(row.Line, Label(row), messages.Any(m => !m.IsWarning) ? ImportAction.Skip : action, messages)); + } + + return results; + } +} + +/// Splits the Field:code errors of . +internal static class TableErrors +{ + /// Splits an error. + /// The error. + /// The field (empty for the record) and the code. + public static (string Field, string Code) Split(string error) + { + var colon = error.LastIndexOf(':'); + return colon < 0 ? (string.Empty, error) : (error[..colon], error[(colon + 1)..]); + } +} diff --git a/src/Khaemhat.Application/ImportExport/ImportValues.cs b/src/Khaemhat.Application/ImportExport/ImportValues.cs new file mode 100644 index 0000000..3c65a97 --- /dev/null +++ b/src/Khaemhat.Application/ImportExport/ImportValues.cs @@ -0,0 +1,274 @@ +using System.Globalization; +using System.Text; + +namespace Khaemhat.Application.ImportExport; + +/// The text codes of the import remarks (import.*), shown by the screen with the field and the value. +public static class ImportErrors +{ + /// The file is not CSV, XLSX or JSON. + public const string FileFormat = "import.file.format"; + + /// The file has no header or no rows. + public const string FileEmpty = "import.file.empty"; + + /// The file cannot be read (damaged spreadsheet, invalid JSON). + public const string FileUnreadable = "import.file.unreadable"; + + /// The file has more rows than an import takes. + public const string FileTooLarge = "import.file.too-large"; + + /// The entity is unknown or not licensed. + public const string TargetUnknown = "import.target.unknown"; + + /// The entity is only checked for now (opening stock until M6, chart of accounts until M7). + public const string CheckOnly = "import.target.check-only"; + + /// A required column of a new record is empty or not mapped. + public const string Required = "import.value.required"; + + /// Not a number. + public const string Number = "import.value.number"; + + /// Not a date. + public const string Date = "import.value.date"; + + /// Not yes or no. + public const string Boolean = "import.value.boolean"; + + /// Not one of the words accepted ({0} lists them). + public const string Choice = "import.value.choice"; + + /// A code of another archive or table that does not exist ({0}). + public const string CodeUnknown = "import.value.code-unknown"; + + /// The row has no code and the options do not generate it. + public const string CodeMissing = "import.code.missing"; + + /// The same code is on an earlier row of the file. + public const string CodeRepeated = "import.code.repeated"; + + /// The code exists and the options skip existing codes (a remark, not an error). + public const string CodeExists = "import.code.exists"; + + /// The code belongs to a party of another kind (a supplier among the customers). + public const string OtherKind = "import.party.other-kind"; + + /// The city was filled from the postal code ({0}). + public const string CityFilled = "import.filled.city"; + + /// The postal code was filled from the city ({0}). + public const string PostalCodeFilled = "import.filled.postal-code"; + + /// A price row names both a list and a customer, or neither. + public const string PriceTarget = "import.price.target"; + + /// Opening stock of an item that is not stocked goods. + public const string NotStocked = "import.stock.not-stocked"; + + /// The quantity must be more than zero. + public const string Positive = "import.value.positive"; + + /// The record could not be written (someone changed it meanwhile, or an unexpected rule). + public const string WriteFailed = "import.write.failed"; + + /// The level of an account is not 1 to 3, or not the number of parts of its code. + public const string AccountLevel = "import.coa.level"; + + /// The parent of an account is not the code without its last part, or is not in the file ({0}). + public const string AccountParent = "import.coa.parent"; + + /// An account has a nature other than its parent's. + public const string AccountNature = "import.coa.nature"; + + /// An account with sub-accounts is marked as postable. + public const string AccountPostable = "import.coa.postable"; + + /// A leaf account is not marked as postable (a remark). + public const string AccountLeaf = "import.coa.leaf"; + + /// A flag letter is not M, I, P, C or X ({0}). + public const string AccountFlag = "import.coa.flag"; +} + +/// The cells of the import as values, and the values of the export as cells. +public static class ImportValues +{ + private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT"); + + private static readonly string[] DateFormats = + ["dd/MM/yyyy", "d/M/yyyy", "dd/MM/yy", "d/M/yy", "dd-MM-yyyy", "d-M-yyyy", "dd.MM.yyyy", "yyyy-MM-dd", "yyyy/MM/dd", "yyyyMMdd", "yyyy-MM-ddTHH:mm:ss"]; + + private static readonly HashSet Yes = new(StringComparer.Ordinal) { "si", "s", "yes", "y", "x", "1", "true", "vero", "v" }; + + private static readonly HashSet No = new(StringComparer.Ordinal) { "no", "n", "0", "false", "falso", "f", "-" }; + + private static readonly DateTime Epoch = new(1899, 12, 30, 0, 0, 0, DateTimeKind.Unspecified); + + /// + /// A header or a word as compared by the mapping and the choices: lower case, no accents, every run of other + /// characters as one underscore (Partita IVA and partita-iva both give partita_iva). + /// + /// The text. + /// The normalized text. + public static string Normalize(string? text) + { + if (string.IsNullOrWhiteSpace(text)) + { + return string.Empty; + } + + var builder = new StringBuilder(text.Length); + var underscore = false; + foreach (var c in text.Trim().Normalize(NormalizationForm.FormD)) + { + if (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.NonSpacingMark) + { + continue; + } + + if (char.IsAsciiLetterOrDigit(c)) + { + if (underscore && builder.Length > 0) + { + builder.Append('_'); + } + + builder.Append(char.ToLowerInvariant(c)); + underscore = false; + } + else + { + underscore = true; + } + } + + return builder.ToString(); + } + + /// + /// Reads a number written the Italian way (1.234,56, € 12,5) or the machine way (1234.56): + /// with both marks the last one is the decimal one; a single point alone is the decimal mark (as spreadsheets and JSON + /// write it), several points alone group thousands; percent signs, currency signs and spaces are ignored. + /// + /// The cell. + /// The number. + /// when the cell is a number. + public static bool TryNumber(string? text, out decimal value) + { + value = 0; + if (string.IsNullOrWhiteSpace(text)) + { + return false; + } + + var clean = new StringBuilder(text.Length); + foreach (var c in text) + { + if (char.IsAsciiDigit(c) || c is ',' or '.' or '-' or '+' or 'e' or 'E') + { + clean.Append(c); + } + else if (!char.IsWhiteSpace(c) && c is not ('€' or '%' or '\'' or ' ' or ' ')) + { + return false; + } + } + + var s = clean.ToString(); + var comma = s.LastIndexOf(','); + var point = s.LastIndexOf('.'); + if (comma >= 0 && point >= 0) + { + s = comma > point ? s.Replace(".", string.Empty, StringComparison.Ordinal).Replace(',', '.') : s.Replace(",", string.Empty, StringComparison.Ordinal); + } + else if (comma >= 0) + { + s = s.Count(c => c == ',') > 1 ? s.Replace(",", string.Empty, StringComparison.Ordinal) : s.Replace(',', '.'); + } + else if (point >= 0 && s.Count(c => c == '.') > 1) + { + s = s.Replace(".", string.Empty, StringComparison.Ordinal); + } + + return decimal.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out value); + } + + /// Reads a date: dd/MM/yyyy and its variants, ISO, or a spreadsheet serial number. + /// The cell. + /// The date. + /// when the cell is a date. + public static bool TryDate(string? text, out DateOnly value) + { + value = default; + if (string.IsNullOrWhiteSpace(text)) + { + return false; + } + + var s = text.Trim(); + if (s.Length > 10 && s[10] is ' ' or 'T') + { + s = s[..10]; + } + + if (DateTime.TryParseExact(s, DateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out var day)) + { + value = DateOnly.FromDateTime(day); + return true; + } + + if (s.All(char.IsAsciiDigit) && s.Length <= 5 && int.TryParse(s, NumberStyles.None, CultureInfo.InvariantCulture, out var serial) && serial > 0) + { + value = DateOnly.FromDateTime(Epoch.AddDays(serial)); + return true; + } + + return false; + } + + /// Reads yes or no: sì, x, 1, VERO, true... and no, 0, FALSO... + /// The cell. + /// The value. + /// when the cell is yes or no. + public static bool TryBoolean(string? text, out bool value) + { + var word = Normalize(text); + value = Yes.Contains(word); + return value || No.Contains(word); + } + + /// Finds a word among the choices of a field, ignoring case, accents, spaces and punctuation (P.A. is pa). + /// The cell. + /// The words accepted, in the order of the values they stand for. + /// The position of the word, or -1. + public static int Choice(string? text, IReadOnlyList choices) + { + ArgumentNullException.ThrowIfNull(choices); + var word = Normalize(text).Replace("_", string.Empty, StringComparison.Ordinal); + for (var i = 0; i < choices.Count; i++) + { + if (Normalize(choices[i]).Replace("_", string.Empty, StringComparison.Ordinal) == word) + { + return i; + } + } + + return -1; + } + + /// A number for a text cell of the export, the Italian way without thousands marks (1234,5). + /// The number. + /// The text, or . + public static string? Text(decimal? value) => value?.ToString("0.############", Italian); + + /// A date for a text cell of the export (dd/MM/yyyy). + /// The date. + /// The text, or . + public static string? Text(DateOnly? value) => value?.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture); + + /// Yes or no for a text cell of the export. + /// The value. + /// sì or no. + public static string Text(bool value) => value ? "sì" : "no"; +} diff --git a/src/Khaemhat.Application/ImportExport/ItemsImportTarget.cs b/src/Khaemhat.Application/ImportExport/ItemsImportTarget.cs new file mode 100644 index 0000000..1ba8c8c --- /dev/null +++ b/src/Khaemhat.Application/ImportExport/ItemsImportTarget.cs @@ -0,0 +1,274 @@ +using Khaemhat.Application.Items; +using Khaemhat.Application.Modules; +using Khaemhat.Application.Querying; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Items; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.ImportExport; + +/// +/// The items (SPEC §12.12): each row is an item read by its code, or a new one with the values proposed by the record, +/// filled with the cells of the row, checked and saved by . Empty cells keep the values of an +/// existing item; units, bar codes, prices and suppliers of the record are left as they are. +/// +/// The items. +/// The automatic codes. +/// Opens the company databases (codes of the tables). +/// Checks the permission to import. +public sealed class ItemsImportTarget(ItemService items, CodeRuleService codes, IUnitOfWorkFactory factory, PermissionService permissions) + : RecordImportTarget +{ + /// The words of tipo, in the order of . + public static readonly IReadOnlyList KindWords = ["merce", "servizio", "spesa", "descrittivo", "cespite"]; + + private static readonly ImportField[] ItemFields = + [ + new("codice", ImportFieldKind.Code, Aliases: ["cod", "codice_articolo", "cod_articolo", "sku", "code"]), + new("descrizione", Required: true, Aliases: ["descr", "description", "nome"]), + new("descrizione_estesa", Aliases: ["descrizione_lunga", "note_descrizione"]), + new("tipo", ImportFieldKind.Choice, Aliases: ["tipologia", "tipo_articolo"], Choices: KindWords), + new("categoria", ImportFieldKind.Code, Aliases: ["famiglia", "categoria_merceologica"]), + new("um", ImportFieldKind.Code, Aliases: ["unita_misura", "unita_di_misura", "u_m"]), + new("iva_vendite", ImportFieldKind.Code, Aliases: ["iva", "aliquota_iva", "codice_iva"]), + new("iva_acquisti", ImportFieldKind.Code), + new("ean", Aliases: ["barcode", "codice_a_barre", "ean13", "gtin"]), + new("nc8", Aliases: ["nomenclatura", "codice_doganale", "taric"]), + new("marca", Aliases: ["brand"]), + new("produttore", Aliases: ["fabbricante", "manufacturer"]), + new("peso_netto", ImportFieldKind.Number), + new("peso_lordo", ImportFieldKind.Number, Aliases: ["peso"]), + new("a_magazzino", ImportFieldKind.Boolean, Aliases: ["gestito_a_magazzino", "movimenta_magazzino"]), + new("magazzino", ImportFieldKind.Code, Aliases: ["deposito"]), + new("scorta_minima", ImportFieldKind.Number, Aliases: ["scorta"]), + new("punto_riordino", ImportFieldKind.Number), + new("lotto_riordino", ImportFieldKind.Number), + new("prezzo", ImportFieldKind.Number, Aliases: ["prezzo_vendita", "prezzo_base", "price"]), + new("costo_standard", ImportFieldKind.Number, Aliases: ["costo"]), + new("conto_ricavo", Aliases: ["conto_ricavi"]), + new("conto_costo", Aliases: ["conto_costi"]), + new("note", Aliases: ["annotazioni", "notes"]), + ]; + + private static readonly Dictionary Columns = new(StringComparer.Ordinal) + { + ["Code"] = "codice", + ["Description"] = "descrizione", + ["ExtendedDescription"] = "descrizione_estesa", + ["Kind"] = "tipo", + ["CategoryId"] = "categoria", + ["UnitOfMeasureId"] = "um", + ["SalesTaxCodeId"] = "iva_vendite", + ["PurchaseTaxCodeId"] = "iva_acquisti", + ["Barcode"] = "ean", + ["CustomsCode"] = "nc8", + ["Brand"] = "marca", + ["Manufacturer"] = "produttore", + ["NetWeight"] = "peso_netto", + ["GrossWeight"] = "peso_lordo", + ["Stocked"] = "a_magazzino", + ["WarehouseId"] = "magazzino", + ["MinimumStock"] = "scorta_minima", + ["ReorderPoint"] = "punto_riordino", + ["ReorderLot"] = "lotto_riordino", + ["Price"] = "prezzo", + ["StandardCost"] = "costo_standard", + ["RevenueAccountCode"] = "conto_ricavo", + ["CostAccountCode"] = "conto_costo", + ["Notes"] = "note", + }; + + /// + public override string Key => "articoli"; + + /// + public override string ModuleCode => ModuleCodes.Core; + + /// + public override string Permission => ItemService.WritePermission; + + /// + public override string ExportPermission => ItemService.ReadPermission; + + /// + public override IReadOnlyList Fields => ItemFields; + + /// + public override async Task>> ExportAsync(ImportContext context, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + var state = await LoadAsync(context, ExportPermission, cancellationToken).ConfigureAwait(false); + var rows = new List>(); + var offset = 0; + while (true) + { + var page = await items.ListAsync(context.Actor, context.CompanyCode, new ListQuery { Offset = offset, Limit = 500, Sort = [new ListSort("code")] }, cancellationToken) + .ConfigureAwait(false); + foreach (var row in page.Items) + { + if (await items.GetAsync(context.Actor, context.CompanyCode, row.Id, cancellationToken).ConfigureAwait(false) is { } record) + { + rows.Add(Cells(state, record.Item)); + } + } + + offset += page.Items.Count; + if (page.Items.Count == 0 || offset >= page.Total) + { + break; + } + } + + return rows; + } + + /// + protected override async Task LoadAsync(ImportContext context, string permission, CancellationToken cancellationToken) + { + var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, permission, cancellationToken).ConfigureAwait(false); + await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var all = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items; + return new State + { + Items = new CodeIndex(all.Select(i => (i.Code, i.Id))), + Categories = await CodeIndex.LoadAsync(uow, cancellationToken).ConfigureAwait(false), + Units = await CodeIndex.LoadAsync(uow, cancellationToken).ConfigureAwait(false), + TaxCodes = await CodeIndex.LoadAsync(uow, cancellationToken).ConfigureAwait(false), + Warehouses = await CodeIndex.LoadAsync(uow, cancellationToken).ConfigureAwait(false), + }; + } + + /// + protected override long? Existing(State state, string code, List messages) + { + ArgumentNullException.ThrowIfNull(state); + return state.Items.Find(code); + } + + /// + protected override async Task OpenAsync(ImportContext context, long? id, CancellationToken cancellationToken) => + id is { } key + ? await items.GetAsync(context.Actor, context.CompanyCode, key, cancellationToken).ConfigureAwait(false) + : await items.NewAsync(context.Actor, context.CompanyCode, cancellationToken).ConfigureAwait(false); + + /// + protected override Task FillAsync(ImportContext context, State state, ItemRecord record, CellReader cells, bool isNew, CancellationToken cancellationToken) + { + var item = record.Item; + if (isNew && cells.Text("codice") is { } code) + { + item.Code = code; + } + + if (cells.Choice(ItemFields[3]) is { } kind) + { + item.Kind = (ItemKind)kind; + if (isNew && item.Kind != ItemKind.Goods) + { + item.Stocked = false; + } + } + + Set(cells, "descrizione", v => item.Description = v); + Set(cells, "descrizione_estesa", v => item.ExtendedDescription = v); + Set(cells, "ean", v => item.Barcode = v); + Set(cells, "nc8", v => item.CustomsCode = v); + Set(cells, "marca", v => item.Brand = v); + Set(cells, "produttore", v => item.Manufacturer = v); + Set(cells, "conto_ricavo", v => item.RevenueAccountCode = v); + Set(cells, "conto_costo", v => item.CostAccountCode = v); + Set(cells, "note", v => item.Notes = v); + item.CategoryId = cells.Code("categoria", state.Categories) ?? item.CategoryId; + item.UnitOfMeasureId = cells.Code("um", state.Units) ?? item.UnitOfMeasureId; + item.SalesTaxCodeId = cells.Code("iva_vendite", state.TaxCodes) ?? item.SalesTaxCodeId; + item.PurchaseTaxCodeId = cells.Code("iva_acquisti", state.TaxCodes) ?? item.PurchaseTaxCodeId; + item.WarehouseId = cells.Code("magazzino", state.Warehouses) ?? item.WarehouseId; + item.Stocked = cells.Boolean("a_magazzino") ?? item.Stocked; + item.NetWeight = cells.Number("peso_netto") ?? item.NetWeight; + item.GrossWeight = cells.Number("peso_lordo") ?? item.GrossWeight; + item.MinimumStock = cells.Number("scorta_minima") ?? item.MinimumStock; + item.ReorderPoint = cells.Number("punto_riordino") ?? item.ReorderPoint; + item.ReorderLot = cells.Number("lotto_riordino") ?? item.ReorderLot; + item.Price = cells.Number("prezzo") ?? item.Price; + item.StandardCost = cells.Number("costo_standard") ?? item.StandardCost; + return Task.CompletedTask; + } + + /// + protected override async Task> ValidateAsync(ImportContext context, ItemRecord record, bool isNew, CancellationToken cancellationToken) + { + var problems = (await items.ValidateAsync(context.Actor, context.CompanyCode, record, cancellationToken).ConfigureAwait(false)).ToList(); + if (isNew && record.Item.Code.Length > 0) + { + var rule = await codes.RuleAsync(context.CompanyCode, ItemService.CodeRule, cancellationToken).ConfigureAwait(false); + if (CodeRuleService.CheckManual(rule, record.Item.Code) is { } manual) + { + problems.Add(new(nameof(Item.Code), manual)); + } + } + + return problems; + } + + /// + protected override async Task<(string Code, long Id)> SaveAsync(ImportContext context, ItemRecord record, CancellationToken cancellationToken) + { + var saved = await items.SaveAsync(context.Actor, context.CompanyCode, record, cancellationToken).ConfigureAwait(false); + return (saved.Item.Code, saved.Item.Id); + } + + /// + protected override string Label(ImportRow row) + { + ArgumentNullException.ThrowIfNull(row); + return row["codice"] ?? row["descrizione"] ?? string.Empty; + } + + /// + protected override void Remember(State state, string code, long id) + { + ArgumentNullException.ThrowIfNull(state); + state.Items.Add(code, id); + } + + /// + protected override string ColumnOf(string serviceField) => Columns.GetValueOrDefault(serviceField ?? string.Empty, string.Empty); + + private static void Set(CellReader cells, string key, Action set) + { + if (cells.Text(key) is { } value) + { + set(value); + } + } + + private static object?[] Cells(State state, Item item) => + [ + item.Code, item.Description, item.ExtendedDescription, KindWords[(int)item.Kind], state.Categories.CodeOf(item.CategoryId), state.Units.CodeOf(item.UnitOfMeasureId), + state.TaxCodes.CodeOf(item.SalesTaxCodeId), state.TaxCodes.CodeOf(item.PurchaseTaxCodeId), item.Barcode, item.CustomsCode, item.Brand, item.Manufacturer, + item.NetWeight, item.GrossWeight, item.Stocked, state.Warehouses.CodeOf(item.WarehouseId), item.MinimumStock, item.ReorderPoint, item.ReorderLot, item.Price, + item.StandardCost, item.RevenueAccountCode, item.CostAccountCode, item.Notes, + ]; + + /// What a check or an import of items loads once. + public sealed class State + { + /// The items. + public required CodeIndex Items { get; init; } + + /// The categories. + public required CodeIndex Categories { get; init; } + + /// The units of measure. + public required CodeIndex Units { get; init; } + + /// The VAT codes. + public required CodeIndex TaxCodes { get; init; } + + /// The warehouses. + public required CodeIndex Warehouses { get; init; } + } +} diff --git a/src/Khaemhat.Application/ImportExport/PartiesImportTarget.cs b/src/Khaemhat.Application/ImportExport/PartiesImportTarget.cs new file mode 100644 index 0000000..a9a83ee --- /dev/null +++ b/src/Khaemhat.Application/ImportExport/PartiesImportTarget.cs @@ -0,0 +1,429 @@ +using System.Globalization; +using Khaemhat.Application.Parties; +using Khaemhat.Application.Querying; +using Khaemhat.Application.Tables; +using Khaemhat.Application.Modules; +using Khaemhat.Application.Security; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.ImportExport; + +/// +/// The customers or the suppliers (SPEC §12.12): each row is a party read by its code, or a new one, filled with the +/// cells of the row, checked and saved by , so the import obeys the rules of the record +/// (fiscal checks, automatic codes, duplicates). Empty cells keep the values of an existing party. +/// +/// Customers or suppliers. +/// The parties. +/// The automatic codes. +/// The places by postal code. +/// Opens the company databases (codes of the tables). +/// Checks the permission to import. +public sealed class PartiesImportTarget( + PartyKind kind, PartyService parties, CodeRuleService codes, AutoFillService autoFill, IUnitOfWorkFactory factory, PermissionService permissions) + : RecordImportTarget +{ + /// The words of tipo_soggetto, in the order of . + public static readonly IReadOnlyList SubjectWords = ["impresa", "privato", "pa", "ue", "extra-ue", "forfettario"]; + + private static readonly ImportField[] Common = + [ + new("codice", ImportFieldKind.Code, Aliases: ["cod", "codice_cliente", "codice_fornitore", "code"]), + new("ragione_sociale", Aliases: ["denominazione", "nome_ditta", "ragione", "rag_sociale", "name"]), + new("nome", Aliases: ["first_name"]), + new("cognome", Aliases: ["last_name"]), + new("tipo_soggetto", ImportFieldKind.Choice, Aliases: ["tipo", "soggetto"], Choices: SubjectWords), + new("partita_iva", Aliases: ["p_iva", "piva", "partitaiva", "vat", "vat_number"]), + new("codice_fiscale", Aliases: ["cf", "c_f", "cod_fiscale", "codicefiscale"]), + new("rea", Aliases: ["numero_rea"]), + new("indirizzo", Aliases: ["via", "address"]), + new("civico", Aliases: ["numero_civico", "n_civico"]), + new("cap", Aliases: ["c_a_p", "codice_postale", "postal_code"]), + new("comune", Aliases: ["citta", "localita", "city"]), + new("provincia", Aliases: ["prov", "pr", "sigla_provincia"]), + new("nazione", Aliases: ["paese", "stato", "country", "codice_nazione"]), + new("telefono", Aliases: ["tel", "phone"]), + new("email", Aliases: ["e_mail", "mail"]), + new("pec", Aliases: ["email_pec", "posta_certificata"]), + new("sito", Aliases: ["sito_web", "web", "website"]), + new("codice_destinatario", Aliases: ["codice_sdi", "sdi", "codice_univoco"]), + new("categoria", ImportFieldKind.Code), + ]; + + private static readonly ImportField[] CustomerFields = + [ + .. Common, + new("agente", ImportFieldKind.Code, Aliases: ["venditore"]), + new("pagamento", ImportFieldKind.Code, Aliases: ["condizioni_pagamento", "cod_pagamento"]), + new("listino", ImportFieldKind.Code), + new("sconto1", ImportFieldKind.Number, Aliases: ["sconto", "sconto_1"]), + new("sconto2", ImportFieldKind.Number, Aliases: ["sconto_2"]), + new("fido", ImportFieldKind.Number, Aliases: ["limite_fido", "fido_massimo"]), + new("iban", Aliases: ["codice_iban"]), + new("note", Aliases: ["annotazioni", "notes"]), + ]; + + private static readonly ImportField[] SupplierFields = + [ + .. Common, + new("pagamento", ImportFieldKind.Code, Aliases: ["condizioni_pagamento", "cod_pagamento"]), + new("iban", Aliases: ["codice_iban"]), + new("note", Aliases: ["annotazioni", "notes"]), + ]; + + private static readonly Dictionary Columns = new(StringComparer.Ordinal) + { + ["Code"] = "codice", + ["Name"] = "ragione_sociale", + ["FirstName"] = "nome", + ["LastName"] = "cognome", + ["SubjectType"] = "tipo_soggetto", + ["VatNumber"] = "partita_iva", + ["TaxCode"] = "codice_fiscale", + ["Rea"] = "rea", + ["Address"] = "indirizzo", + ["StreetNumber"] = "civico", + ["PostalCode"] = "cap", + ["City"] = "comune", + ["Province"] = "provincia", + ["CountryCode"] = "nazione", + ["Phone"] = "telefono", + ["Email"] = "email", + ["Pec"] = "pec", + ["Website"] = "sito", + ["CategoryId"] = "categoria", + ["SalespersonId"] = "agente", + ["Notes"] = "note", + ["Fiscal.RecipientCode"] = "codice_destinatario", + ["Sales.PaymentTermId"] = "pagamento", + ["Purchase.PaymentTermId"] = "pagamento", + ["Sales.PriceListId"] = "listino", + ["Sales.Discount1"] = "sconto1", + ["Sales.Discount2"] = "sconto2", + ["Sales.CreditLimit"] = "fido", + }; + + /// + public override string Key => kind == PartyKind.Supplier ? "fornitori" : "clienti"; + + /// + public override string ModuleCode => ModuleCodes.Core; + + /// + public override string Permission => PartyService.WritePermission; + + /// + public override string ExportPermission => "parties.party.export"; + + /// + public override IReadOnlyList Fields => kind == PartyKind.Supplier ? SupplierFields : CustomerFields; + + private bool IsCustomer => kind != PartyKind.Supplier; + + /// + public override async Task>> ExportAsync(ImportContext context, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + var state = await LoadAsync(context, ExportPermission, cancellationToken).ConfigureAwait(false); + var archive = IsCustomer ? PartyArchive.Customers : PartyArchive.Suppliers; + var rows = new List>(); + var offset = 0; + while (true) + { + var page = await parties.ListAsync(context.Actor, context.CompanyCode, archive, new ListQuery { Offset = offset, Limit = 500, Sort = [new ListSort("code")] }, + cancellationToken).ConfigureAwait(false); + foreach (var row in page.Items.Where(r => r.Kind == kind)) + { + if (await parties.GetAsync(context.Actor, context.CompanyCode, row.Id, cancellationToken).ConfigureAwait(false) is { } record) + { + rows.Add(Cells(state, record)); + } + } + + offset += page.Items.Count; + if (page.Items.Count == 0 || offset >= page.Total) + { + break; + } + } + + return rows; + } + + /// + protected override async Task LoadAsync(ImportContext context, string permission, CancellationToken cancellationToken) + { + var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, permission, cancellationToken).ConfigureAwait(false); + await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var all = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items; + return new State + { + Kinds = all.GroupBy(p => p.Code, StringComparer.OrdinalIgnoreCase).ToDictionary(g => g.Key, g => (g.First().Id, g.First().Kind), StringComparer.OrdinalIgnoreCase), + Categories = await CodeIndex.LoadAsync(uow, cancellationToken).ConfigureAwait(false), + Salespeople = await CodeIndex.LoadAsync(uow, cancellationToken).ConfigureAwait(false), + PaymentTerms = await CodeIndex.LoadAsync(uow, cancellationToken).ConfigureAwait(false), + PriceLists = await CodeIndex.LoadAsync(uow, cancellationToken).ConfigureAwait(false), + }; + } + + /// + protected override long? Existing(State state, string code, List messages) + { + if (!state.Kinds.TryGetValue(code, out var found)) + { + return null; + } + + if (found.Kind != kind) + { + messages.Add(new("codice", ImportErrors.OtherKind, Value: code)); + return null; + } + + return found.Id; + } + + /// + protected override Task OpenAsync(ImportContext context, long? id, CancellationToken cancellationToken) => + id is { } key + ? parties.GetAsync(context.Actor, context.CompanyCode, key, cancellationToken) + : NewAsync(context, cancellationToken); + + /// + protected override async Task FillAsync(ImportContext context, State state, PartyRecord record, CellReader cells, bool isNew, CancellationToken cancellationToken) + { + var party = record.Party; + if (isNew && cells.Text("codice") is { } code) + { + party.Code = code; + } + + if (cells.Choice(Fields.First(f => f.Key == "tipo_soggetto")) is { } subject) + { + party.SubjectType = (SubjectType)subject; + } + else if (isNew && !cells.Has("tipo_soggetto") && !cells.Has("ragione_sociale") && cells.Has("cognome")) + { + party.SubjectType = SubjectType.Person; + } + + Set(cells, "ragione_sociale", v => party.Name = v); + Set(cells, "nome", v => party.FirstName = v); + Set(cells, "cognome", v => party.LastName = v); + if (party.SubjectType == SubjectType.Person && !cells.Has("ragione_sociale") && (cells.Has("nome") || cells.Has("cognome"))) + { + party.Name = string.Empty; + } + + Set(cells, "partita_iva", v => party.VatNumber = v); + Set(cells, "codice_fiscale", v => party.TaxCode = v.ToUpperInvariant()); + Set(cells, "rea", v => party.Rea = v); + Set(cells, "indirizzo", v => party.Address = v); + Set(cells, "civico", v => party.StreetNumber = v); + Set(cells, "cap", v => party.PostalCode = v); + Set(cells, "comune", v => party.City = v); + Set(cells, "provincia", v => party.Province = v.ToUpperInvariant()); + Set(cells, "nazione", v => party.CountryCode = v.ToUpperInvariant()); + Set(cells, "telefono", v => party.Phone = v); + Set(cells, "email", v => party.Email = v); + Set(cells, "pec", v => party.Pec = v); + Set(cells, "sito", v => party.Website = v); + Set(cells, "codice_destinatario", v => record.Fiscal.RecipientCode = v.ToUpperInvariant()); + Set(cells, "note", v => party.Notes = v); + if (cells.Code("categoria", state.Categories) is { } category) + { + party.CategoryId = category; + } + + if (cells.Code("pagamento", state.PaymentTerms) is { } payment) + { + if (IsCustomer) + { + record.Sales.PaymentTermId = payment; + } + else + { + record.Purchase.PaymentTermId = payment; + } + } + + if (IsCustomer) + { + if (cells.Code("agente", state.Salespeople) is { } salesperson) + { + party.SalespersonId = salesperson; + } + + if (cells.Code("listino", state.PriceLists) is { } list) + { + record.Sales.PriceListId = list; + } + + record.Sales.Discount1 = cells.Number("sconto1") ?? record.Sales.Discount1; + record.Sales.Discount2 = cells.Number("sconto2") ?? record.Sales.Discount2; + record.Sales.CreditLimit = cells.Number("fido") ?? record.Sales.CreditLimit; + } + + if (cells.Text("iban") is { } text) + { + var iban = string.Concat(text.Where(c => !char.IsWhiteSpace(c))).ToUpperInvariant(); + if (!record.BankAccounts.Any(b => string.Equals(b.Iban, iban, StringComparison.OrdinalIgnoreCase))) + { + record.BankAccounts.Add(new PartyBankAccount { Iban = iban, IsDefault = !record.BankAccounts.Any(b => b.IsDefault) }); + } + } + + if (context.Options.FillFromPostalCode && (cells.Has("cap") || cells.Has("comune"))) + { + await FillPlaceAsync(context, state, party, cells, cancellationToken).ConfigureAwait(false); + } + } + + /// + protected override async Task> ValidateAsync(ImportContext context, PartyRecord record, bool isNew, CancellationToken cancellationToken) + { + var problems = (await parties.ValidateAsync(context.Actor, context.CompanyCode, record, cancellationToken).ConfigureAwait(false)).ToList(); + if (isNew && record.Party.Code.Length > 0 && CodeRuleService.CheckManual(await RuleAsync(context, cancellationToken).ConfigureAwait(false), record.Party.Code) is { } manual) + { + problems.Add(new(nameof(Party.Code), manual)); + } + + return problems; + } + + /// + protected override async Task<(string Code, long Id)> SaveAsync(ImportContext context, PartyRecord record, CancellationToken cancellationToken) + { + var saved = await parties.SaveAsync(context.Actor, context.CompanyCode, record, context.Options.VerifyVat, cancellationToken).ConfigureAwait(false); + return (saved.Party.Code, saved.Party.Id); + } + + /// + protected override string Label(ImportRow row) + { + ArgumentNullException.ThrowIfNull(row); + return row["codice"] ?? row["ragione_sociale"] ?? string.Join(' ', new[] { row["cognome"], row["nome"] }.Where(n => n is not null)); + } + + /// + protected override void Remember(State state, string code, long id) + { + ArgumentNullException.ThrowIfNull(state); + state.Kinds[code] = (id, kind); + } + + /// + protected override string ColumnOf(string serviceField) + { + ArgumentNullException.ThrowIfNull(serviceField); + if (Columns.TryGetValue(serviceField, out var column)) + { + return column; + } + + return serviceField.StartsWith("BankAccounts.", StringComparison.Ordinal) ? "iban" : string.Empty; + } + + private static void Set(CellReader cells, string key, Action set) + { + if (cells.Text(key) is { } value) + { + set(value); + } + } + + private object?[] Cells(State state, PartyRecord record) + { + var p = record.Party; + var common = new object?[] + { + p.Code, p.SubjectType == SubjectType.Person ? null : p.Name, p.FirstName, p.LastName, SubjectWords[(int)p.SubjectType], p.VatNumber, p.TaxCode, p.Rea, + p.Address, p.StreetNumber, p.PostalCode, p.City, p.Province, p.CountryCode, p.Phone, p.Email, p.Pec, p.Website, record.Fiscal.RecipientCode, + state.Categories.CodeOf(p.CategoryId), + }; + var iban = record.BankAccounts.OrderByDescending(b => b.IsDefault).FirstOrDefault()?.Iban; + return IsCustomer + ? + [ + .. common, state.Salespeople.CodeOf(p.SalespersonId), state.PaymentTerms.CodeOf(record.Sales.PaymentTermId), state.PriceLists.CodeOf(record.Sales.PriceListId), + record.Sales.Discount1, record.Sales.Discount2, record.Sales.CreditLimit, iban, p.Notes, + ] + : [.. common, state.PaymentTerms.CodeOf(record.Purchase.PaymentTermId), iban, p.Notes]; + } + + private async Task NewAsync(ImportContext context, CancellationToken cancellationToken) => + await parties.NewAsync(context.Actor, context.CompanyCode, kind, cancellationToken).ConfigureAwait(false); + + private async Task RuleAsync(ImportContext context, CancellationToken cancellationToken) => + await codes.RuleAsync(context.CompanyCode, PartyService.CodeRuleOf(kind), cancellationToken).ConfigureAwait(false); + + // City from the postal code and postal code from the city, only for Italian addresses and only when one place fits. + private async Task FillPlaceAsync(ImportContext context, State state, Party party, CellReader cells, CancellationToken cancellationToken) + { + if (!string.Equals(party.CountryCode, "IT", StringComparison.OrdinalIgnoreCase)) + { + return; + } + + if (party.PostalCode is { } cap && string.IsNullOrWhiteSpace(party.City)) + { + if (!state.ByPostalCode.TryGetValue(cap, out var places)) + { + places = await autoFill.PlacesByPostalCodeAsync(context.Actor, context.CompanyCode, cap, cancellationToken).ConfigureAwait(false); + state.ByPostalCode[cap] = places; + } + + if (places.Count == 1) + { + party.City = places[0].Name; + party.Province ??= places[0].ProvinceCode; + cells.Messages.Add(new("comune", ImportErrors.CityFilled, IsWarning: true, Value: places[0].Name)); + } + } + else if (party.City is { } city && string.IsNullOrWhiteSpace(party.PostalCode)) + { + var key = city.ToUpper(CultureInfo.InvariantCulture); + if (!state.ByName.TryGetValue(key, out var places)) + { + places = await autoFill.PlacesByNameAsync(context.Actor, context.CompanyCode, city, cancellationToken).ConfigureAwait(false); + state.ByName[key] = places; + } + + var exact = places.Where(p => string.Equals(p.Name, city, StringComparison.OrdinalIgnoreCase)).ToList(); + if (exact.Count == 1 && exact[0].PostalCode is { } postalCode) + { + party.PostalCode = postalCode; + party.Province ??= exact[0].ProvinceCode; + cells.Messages.Add(new("cap", ImportErrors.PostalCodeFilled, IsWarning: true, Value: postalCode)); + } + } + } + + /// What a check or an import of parties loads once. + public sealed class State + { + /// The id and kind of every party by code. + public required Dictionary Kinds { get; init; } + + /// The categories. + public required CodeIndex Categories { get; init; } + + /// The salespeople. + public required CodeIndex Salespeople { get; init; } + + /// The payment terms. + public required CodeIndex PaymentTerms { get; init; } + + /// The price lists. + public required CodeIndex PriceLists { get; init; } + + /// Places found by postal code. + public Dictionary> ByPostalCode { get; } = new(StringComparer.Ordinal); + + /// Places found by name. + public Dictionary> ByName { get; } = new(StringComparer.Ordinal); + } +} diff --git a/src/Khaemhat.Application/ImportExport/PricesImportTarget.cs b/src/Khaemhat.Application/ImportExport/PricesImportTarget.cs new file mode 100644 index 0000000..625fafb --- /dev/null +++ b/src/Khaemhat.Application/ImportExport/PricesImportTarget.cs @@ -0,0 +1,187 @@ +using Khaemhat.Application.Items; +using Khaemhat.Application.Modules; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Items; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.ImportExport; + +/// +/// The prices of the lists and the net prices of the customers (SPEC §12.12): each row is the price of an item in a list +/// or for a customer, valid from a day; the same item, list or customer and day replaces the price, another day adds a +/// dated price as the price grid does. All rows are written by in one transaction. +/// +/// The price lists. +/// Opens the company databases. +/// Checks the permission. +public sealed class PricesImportTarget(PriceListService prices, IUnitOfWorkFactory factory, PermissionService permissions) : IImportTarget +{ + private static readonly ImportField[] PriceFields = + [ + new("articolo", ImportFieldKind.Code, Required: true, Aliases: ["codice_articolo", "codice", "cod_articolo", "sku"]), + new("listino", ImportFieldKind.Code, Aliases: ["codice_listino", "cod_listino"]), + new("cliente", ImportFieldKind.Code, Aliases: ["codice_cliente", "cod_cliente"]), + new("prezzo", ImportFieldKind.Number, Required: true, Aliases: ["prezzo_netto", "price"]), + new("valido_dal", ImportFieldKind.Date, Aliases: ["validita", "data_inizio", "dal", "decorrenza"]), + ]; + + /// + public string Key => "listini"; + + /// + public string ModuleCode => ModuleCodes.Core; + + /// + public string Permission => ItemService.WritePermission; + + /// + public string ExportPermission => ItemService.ReadPermission; + + /// + public bool CanApply => true; + + /// + public bool CanExport => true; + + /// + public IReadOnlyList Fields => PriceFields; + + /// + public async Task> CheckAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) => + (await PlanAsync(context, rows, cancellationToken).ConfigureAwait(false)).Results; + + /// + public async Task> ApplyAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) + { + var plan = await PlanAsync(context, rows, cancellationToken).ConfigureAwait(false); + if (plan.Edits.Count == 0) + { + return plan.Results; + } + + try + { + await prices.SaveAsync(context.Actor, context.CompanyCode, [.. plan.Edits.Select(e => e.Edit)], cancellationToken).ConfigureAwait(false); + return plan.Results; + } + catch (ValidationFailedException ex) + { + // The rows were checked already: an error here is a change made meanwhile; it goes on its row and nothing is written. + var results = plan.Results.ToList(); + foreach (var (index, code) in ex.Errors.Select(TableErrors.Split)) + { + var position = int.TryParse(index, out var i) && i >= 0 && i < plan.Edits.Count ? plan.Edits[i].Result : -1; + if (position >= 0) + { + var row = results[position]; + results[position] = row with { Action = ImportAction.Skip, Messages = [.. row.Messages, new ImportMessage("prezzo", code)] }; + } + } + + return [.. results.Select(r => r.Outcome == ImportOutcome.Error ? r : r with { Action = ImportAction.Skip, Messages = [.. r.Messages, new ImportMessage(string.Empty, ImportErrors.WriteFailed)] })]; + } + } + + /// + public async Task>> ExportAsync(ImportContext context, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, ExportPermission, cancellationToken).ConfigureAwait(false); + await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var items = new CodeIndex((await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items.Select(i => (i.Code, i.Id))); + var parties = new CodeIndex((await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items.Select(p => (p.Code, p.Id))); + var lists = await CodeIndex.LoadAsync(uow, cancellationToken).ConfigureAwait(false); + var rows = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items; + return + [ + .. rows.Select(p => (IReadOnlyList)[items.CodeOf(p.ItemId), lists.CodeOf(p.PriceListId), parties.CodeOf(p.PartyId), p.Price, p.ValidFrom]) + .OrderBy(r => (string?)r[0], StringComparer.OrdinalIgnoreCase) + .ThenBy(r => (string?)r[1] ?? "~" + (string?)r[2], StringComparer.OrdinalIgnoreCase) + .ThenBy(r => (DateOnly?)r[4]), + ]; + } + + private async Task PlanAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(rows); + var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false); + await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var items = new CodeIndex((await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items.Select(i => (i.Code, i.Id))); + var allParties = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items; + var customers = new CodeIndex(allParties.Where(p => p.IsCustomer).Select(p => (p.Code, p.Id))); + var others = new HashSet(allParties.Where(p => !p.IsCustomer).Select(p => p.Code), StringComparer.OrdinalIgnoreCase); + var lists = await CodeIndex.LoadAsync(uow, cancellationToken).ConfigureAwait(false); + var existing = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items + .Select(p => (p.ItemId, p.PriceListId, p.PartyId, p.ValidFrom)).ToHashSet(); + + var seen = new HashSet<(long, long?, long?, DateOnly?)>(); + var results = new List(rows.Count); + var edits = new List<(PriceEdit Edit, int Result)>(); + foreach (var row in rows) + { + var messages = new List(); + var cells = new CellReader(row, messages); + var item = cells.Code("articolo", items); + long? list = null; + long? party = null; + if (cells.Has("listino") == cells.Has("cliente")) + { + messages.Add(new(cells.Has("listino") ? "cliente" : "listino", ImportErrors.PriceTarget)); + } + else if (cells.Has("listino")) + { + list = cells.Code("listino", lists); + } + else if (row["cliente"] is { } customer && others.Contains(customer)) + { + messages.Add(new("cliente", ImportErrors.OtherKind, Value: customer)); + } + else + { + party = cells.Code("cliente", customers); + } + + var price = cells.Number("prezzo"); + if (price < 0) + { + messages.Add(new("prezzo", ItemService.NotNegative)); + } + + var from = cells.Date("valido_dal"); + messages.AddRange(PriceFields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required))); + var label = row["articolo"] ?? string.Empty; + if (messages.Any(m => !m.IsWarning) || item is not { } itemId || price is not { } value) + { + results.Add(new(row.Line, label, ImportAction.Skip, messages)); + continue; + } + + var key = (itemId, list, party, from); + if (!seen.Add(key)) + { + messages.Add(new("articolo", ImportErrors.CodeRepeated, Value: label)); + results.Add(new(row.Line, label, ImportAction.Skip, messages)); + continue; + } + + var update = existing.Contains(key); + if (update && context.Options.Existing == ExistingCodeAction.Skip) + { + results.Add(new(row.Line, label, ImportAction.Skip, [new("articolo", ImportErrors.CodeExists, IsWarning: true, Value: label)])); + continue; + } + + edits.Add((new PriceEdit(itemId, list, party, value, from), results.Count)); + results.Add(new(row.Line, label, update ? ImportAction.Update : ImportAction.Create, messages)); + } + + return new Plan(results, edits); + } + + private sealed record Plan(IReadOnlyList Results, IReadOnlyList<(PriceEdit Edit, int Result)> Edits); +} diff --git a/src/Khaemhat.Application/Parties/PartyService.cs b/src/Khaemhat.Application/Parties/PartyService.cs index 553e4c8..c5ad394 100644 --- a/src/Khaemhat.Application/Parties/PartyService.cs +++ b/src/Khaemhat.Application/Parties/PartyService.cs @@ -362,7 +362,19 @@ public sealed class PartyService /// The saved record, read back. /// A rule failed; errors are Field:code. /// Someone else changed the party meanwhile. - public async Task SaveAsync(Actor actor, string companyCode, PartyRecord record, CancellationToken cancellationToken = default) + public Task SaveAsync(Actor actor, string companyCode, PartyRecord record, CancellationToken cancellationToken = default) => + SaveAsync(actor, companyCode, record, null, cancellationToken); + + /// Saves a party with its details, choosing whether to check an EU VAT number on VIES (the import asks it in its options). + /// Who saves. + /// The company. + /// The record. + /// Check on VIES; : as the automatic filling option of the company says. + /// Cancellation. + /// The saved record, read back. + /// A rule failed; errors are Field:code. + /// Someone else changed the party meanwhile. + public async Task SaveAsync(Actor actor, string companyCode, PartyRecord record, bool? verifyVat, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(record); var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false); @@ -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); } diff --git a/src/Khaemhat.Core/Accounting/AccountType.cs b/src/Khaemhat.Core/Accounting/AccountType.cs new file mode 100644 index 0000000..5f431dc --- /dev/null +++ b/src/Khaemhat.Core/Accounting/AccountType.cs @@ -0,0 +1,26 @@ +namespace Khaemhat.Core.Accounting; + +/// What a ledger account is used for, beyond its nature: the accounts the automatic postings look for. +public enum AccountType +{ + /// Any other account. + Generic = 0, + + /// The customers control account, with a sub-ledger per customer. + Customers = 1, + + /// The suppliers control account, with a sub-ledger per supplier. + Suppliers = 2, + + /// A bank account. + Bank = 3, + + /// Cash. + Cash = 4, + + /// VAT on sales or purchases, or the VAT settlement. + Vat = 5, + + /// Amounts due to or from the tax authority (withholdings, taxes). + Tax = 6, +} diff --git a/src/Khaemhat.Infrastructure/Files/XlsxReader.cs b/src/Khaemhat.Infrastructure/Files/XlsxReader.cs new file mode 100644 index 0000000..cb15e4f --- /dev/null +++ b/src/Khaemhat.Infrastructure/Files/XlsxReader.cs @@ -0,0 +1,414 @@ +using System.Globalization; +using System.IO.Compression; +using System.Xml; + +namespace Khaemhat.Infrastructure.Files; + +/// A spreadsheet that cannot be read: not an Office Open XML workbook, damaged, or too large. +public sealed class XlsxReadException : Exception +{ + /// Creates the exception. + public XlsxReadException() + { + } + + /// Creates the exception. + /// What went wrong. + public XlsxReadException(string message) + : base(message) + { + } + + /// Creates the exception. + /// What went wrong. + /// The cause. + public XlsxReadException(string message, Exception innerException) + : base(message, innerException) + { + } +} + +/// +/// Reads the first sheet of an Office Open XML workbook (.xlsx, SPEC §12.12) with and +/// : shared, inline and formula strings, numbers as written in the file (invariant culture), +/// booleans as true/false, and numbers with a date format as ISO dates (yyyy-MM-dd). Empty cells in +/// the middle of a row are kept by their column letter; empty rows are skipped. Formulas are not computed: the cached +/// value saved by the spreadsheet is read. +/// +public static class XlsxReader +{ + /// The largest uncompressed part read, against archives that expand to fill the memory. + public const long MaxPartBytes = 256L * 1024 * 1024; + + private const string RelationshipNamespace = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; + + // The built-in number formats that show a date (ECMA-376 §18.8.30). + private static readonly HashSet DateFormats = [14, 15, 16, 17, 18, 19, 20, 21, 22, 27, 30, 36, 45, 46, 47, 50, 57]; + + private static readonly DateTime Epoch = new(1899, 12, 30, 0, 0, 0, DateTimeKind.Unspecified); + + /// Reads the rows of the first sheet. + /// The workbook; it is copied to memory when not seekable. + /// Cancellation. + /// The rows, each with its cells from column A. + /// The file is not a readable workbook. + public static async Task>> ReadAsync(Stream content, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(content); + var source = content; + MemoryStream? copy = null; + if (!content.CanSeek) + { + copy = new MemoryStream(); + await content.CopyToAsync(copy, cancellationToken).ConfigureAwait(false); + copy.Position = 0; + source = copy; + } + + try + { + using var zip = new ZipArchive(source, ZipArchiveMode.Read, leaveOpen: true); + var sheetPath = FirstSheetPath(zip); + var strings = SharedStrings(zip); + var dateStyles = DateStyles(zip); + var sheet = zip.GetEntry(sheetPath) ?? throw new XlsxReadException("The first sheet is missing: " + sheetPath); + return ReadSheet(sheet, strings, dateStyles, cancellationToken); + } + catch (InvalidDataException ex) + { + throw new XlsxReadException("Not a workbook.", ex); + } + catch (XmlException ex) + { + throw new XlsxReadException("A part of the workbook is not valid XML.", ex); + } + finally + { + if (copy is not null) + { + await copy.DisposeAsync().ConfigureAwait(false); + } + } + } + + /// The zero-based column of a cell reference such as AB12. + /// The reference. + /// The column, or -1 when the reference has no letters. + public static int ColumnOf(string? reference) + { + if (string.IsNullOrEmpty(reference)) + { + return -1; + } + + var column = 0; + var letters = 0; + foreach (var c in reference) + { + if (!char.IsAsciiLetter(c)) + { + break; + } + + column = (column * 26) + (char.ToUpperInvariant(c) - 'A' + 1); + letters++; + } + + return letters == 0 ? -1 : column - 1; + } + + private static XmlReader Open(ZipArchiveEntry entry) + { + if (entry.Length > MaxPartBytes) + { + throw new XlsxReadException("A part of the workbook is too large: " + entry.FullName); + } + + return XmlReader.Create(entry.Open(), new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null, IgnoreWhitespace = false }); + } + + private static string FirstSheetPath(ZipArchive zip) + { + var workbook = zip.GetEntry("xl/workbook.xml") ?? throw new XlsxReadException("xl/workbook.xml is missing."); + string? relationship = null; + using (var reader = Open(workbook)) + { + while (reader.Read()) + { + if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "sheet") + { + relationship = reader.GetAttribute("id", RelationshipNamespace); + break; + } + } + } + + if (relationship is null) + { + throw new XlsxReadException("The workbook has no sheet."); + } + + var rels = zip.GetEntry("xl/_rels/workbook.xml.rels"); + if (rels is not null) + { + using var reader = Open(rels); + while (reader.Read()) + { + if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "Relationship" && reader.GetAttribute("Id") == relationship + && reader.GetAttribute("Target") is { } target) + { + target = target.Replace('\\', '/'); + return target.StartsWith('/') ? target.TrimStart('/') : "xl/" + target; + } + } + } + + return "xl/worksheets/sheet1.xml"; + } + + private static List SharedStrings(ZipArchive zip) + { + var strings = new List(); + var entry = zip.GetEntry("xl/sharedStrings.xml"); + if (entry is null) + { + return strings; + } + + using var reader = Open(entry); + while (reader.Read()) + { + if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "si") + { + strings.Add(ReadText(reader)); + } + } + + return strings; + } + + // The concatenated of an or element, without the phonetic runs; the reader ends on its end tag. + private static string ReadText(XmlReader reader) + { + if (reader.IsEmptyElement) + { + return string.Empty; + } + + var depth = reader.Depth; + var text = new System.Text.StringBuilder(); + var skip = -1; + while (reader.Read() && !(reader.NodeType == XmlNodeType.EndElement && reader.Depth == depth)) + { + if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "rPh" && !reader.IsEmptyElement) + { + skip = reader.Depth; + } + else if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == skip) + { + skip = -1; + } + else if (skip < 0 && reader.NodeType == XmlNodeType.Element && reader.LocalName == "t" && !reader.IsEmptyElement) + { + text.Append(reader.ReadElementContentAsString()); + if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == depth) + { + break; + } + } + } + + return text.ToString(); + } + + // The indexes of the cell styles (cellXfs) whose number format shows a date. + private static HashSet DateStyles(ZipArchive zip) + { + var styles = new HashSet(); + var entry = zip.GetEntry("xl/styles.xml"); + if (entry is null) + { + return styles; + } + + var custom = new HashSet(); + using var reader = Open(entry); + var inCellXfs = false; + var index = 0; + while (reader.Read()) + { + if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "numFmt" + && int.TryParse(reader.GetAttribute("numFmtId"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var id) + && IsDateFormat(reader.GetAttribute("formatCode"))) + { + custom.Add(id); + } + else if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "cellXfs") + { + inCellXfs = !reader.IsEmptyElement; + } + else if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "cellXfs") + { + inCellXfs = false; + } + else if (inCellXfs && reader.NodeType == XmlNodeType.Element && reader.LocalName == "xf") + { + if (int.TryParse(reader.GetAttribute("numFmtId"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var format) + && (DateFormats.Contains(format) || custom.Contains(format))) + { + styles.Add(index); + } + + index++; + } + } + + return styles; + } + + // A custom format shows a date when, outside quoted text and brackets, it has a day, month or year code. + private static bool IsDateFormat(string? code) + { + if (string.IsNullOrEmpty(code)) + { + return false; + } + + var quoted = false; + var bracket = false; + foreach (var c in code) + { + switch (c) + { + case '"': + quoted = !quoted; + break; + case '[' when !quoted: + bracket = true; + break; + case ']' when !quoted: + bracket = false; + break; + case 'd' or 'D' or 'y' or 'Y' or 'm' or 'M' when !quoted && !bracket: + return true; + } + } + + return false; + } + + private static List> ReadSheet(ZipArchiveEntry sheet, List strings, HashSet dateStyles, CancellationToken cancellationToken) + { + var rows = new List>(); + using var reader = Open(sheet); + List? row = null; + while (reader.Read()) + { + if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "row") + { + cancellationToken.ThrowIfCancellationRequested(); + row = []; + if (reader.IsEmptyElement) + { + row = null; + } + } + else if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "row" && row is not null) + { + while (row.Count > 0 && row[^1].Length == 0) + { + row.RemoveAt(row.Count - 1); + } + + if (row.Count > 0) + { + rows.Add(row); + } + + row = null; + } + else if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "c" && row is not null) + { + var column = ColumnOf(reader.GetAttribute("r")); + var type = reader.GetAttribute("t"); + var style = int.TryParse(reader.GetAttribute("s"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var s) ? s : -1; + var value = reader.IsEmptyElement ? string.Empty : ReadCell(reader, type, strings, dateStyles.Contains(style)); + if (column < 0) + { + column = row.Count; + } + + while (row.Count < column) + { + row.Add(string.Empty); + } + + if (row.Count == column) + { + row.Add(value); + } + else + { + row[column] = value; + } + } + } + + return rows; + } + + // The value of a element; the reader ends on its end tag. + private static string ReadCell(XmlReader reader, string? type, List strings, bool date) + { + var depth = reader.Depth; + string? raw = null; + string? inline = null; + while (reader.Read() && !(reader.NodeType == XmlNodeType.EndElement && reader.Depth == depth)) + { + if (reader.NodeType != XmlNodeType.Element) + { + continue; + } + + if (reader.LocalName == "v" && !reader.IsEmptyElement) + { + raw = reader.ReadElementContentAsString(); + if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == depth) + { + break; + } + } + else if (reader.LocalName == "is") + { + inline = ReadText(reader); + } + } + + return type switch + { + "inlineStr" => inline ?? string.Empty, + "s" => int.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out var index) && index >= 0 && index < strings.Count ? strings[index] : string.Empty, + "b" => raw == "1" ? "true" : "false", + "str" or "e" => raw ?? string.Empty, + _ => Number(raw, date), + }; + } + + private static string Number(string? raw, bool date) + { + if (string.IsNullOrEmpty(raw)) + { + return string.Empty; + } + + if (date && double.TryParse(raw, NumberStyles.Float, CultureInfo.InvariantCulture, out var serial) && serial is > 0 and < 2958466) + { + var day = Epoch.AddDays(Math.Floor(serial)); + return day.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); + } + + return decimal.TryParse(raw, NumberStyles.Float, CultureInfo.InvariantCulture, out var number) + ? number.ToString(CultureInfo.InvariantCulture) + : raw; + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor b/src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor new file mode 100644 index 0000000..427a9c4 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor @@ -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. *@ + + +@if (Session.Company is null) +{ +

@T["ImportExport.NoCompany"]

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

@T["Pages.AccessDenied.Title"]

+

@T["ImportExport.NoTargets"]

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

@T["ImportExport.Export.Lead"]

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

@T["ImportExport.Formats.Lead"]

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

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

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

@T["ImportExport.Mapping.Lead"]

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

@T["ImportExport.Preview.NoRows"]

+ } + else + { + + + + + @foreach (var key in PreviewFields) + { + + } + + + + + @foreach (var row in VisibleRows) + { + var cells = CellsOf(row.Line); + + + @foreach (var key in PreviewFields) + { + + } + + + } + +
@T["ImportExport.Preview.Line"]@FieldName(key)@T["ImportExport.Preview.Outcome"]
@row.Line@CellOf(row, cells, key) + @OutcomeText(row) + @foreach (var message in row.Messages) + { + @MessageText(message) + } +
+ } +
+
+ } +
+
+} diff --git a/src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor.cs b/src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor.cs new file mode 100644 index 0000000..57ac76f --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor.cs @@ -0,0 +1,391 @@ +using Khaemhat.Application.ImportExport; +using Khaemhat.Application.Security; +using Khaemhat.Web.Shell; +using Khaemhat.Web.Ui; +using Microsoft.AspNetCore.Components.Forms; +using Microsoft.JSInterop; + +namespace Khaemhat.Web.Components.Pages.Admin; + +/// The state and the actions of the guided import and export (mockup 077). +public partial class ImportExportPage +{ + /// The largest file accepted, in megabytes. + public const int MaxMegabytes = 25; + + private const int MaxPreviewRows = 500; + private const int MaxPreviewFields = 6; + + private static readonly TransferFormat[] Formats = [TransferFormat.Csv, TransferFormat.Xlsx, TransferFormat.Json]; + + private ImportOptions _options = new(); + private string _targetKey = "clienti"; + private TransferFormat _format = TransferFormat.Csv; + private ImportFile? _file; + private long _fileBytes; + private string?[] _mapping = []; + private Dictionary _rows = []; + private ImportPreview? _preview; + private ImportReport? _report; + private bool _onlyProblems; + private bool _busy; + private int _step; + + private IReadOnlyList Targets => + [.. Imports.Targets.Where(t => Session.Permissions.Allows(t.Permission) || Session.Permissions.Allows(t.ExportPermission))]; + + private IImportTarget Target => Targets.FirstOrDefault(t => t.Key == _targetKey) ?? Targets[0]; + + private bool IsParties => Target is PartiesImportTarget; + + private bool IsRecordTarget => Target is PartiesImportTarget or ItemsImportTarget; + + private bool IsPrices => Target is PricesImportTarget; + + private bool CanExport => Target.CanExport && Session.Permissions.Flags.CanExport && Session.Permissions.Allows(Target.ExportPermission); + + private string? ExportHint => !Target.CanExport ? T["ImportExport.Export.Nothing"] : !Session.Permissions.Flags.CanExport ? T["ImportExport.Export.NotAllowed"] : null; + + private string CheckOnlyMilestone => Target is ChartOfAccountsImportTarget ? "M7" : "M6"; + + private IReadOnlyList> TargetChoices => [.. Targets.Select(t => new KhOption(t.Key, TargetName(t.Key)))]; + + private IReadOnlyList> ExistingChoices => + [.. Enum.GetValues().Select(v => new KhOption(v, T["ImportExport.ExistingChoices." + v]))]; + + private IReadOnlyList> MissingChoices => + [.. Enum.GetValues().Select(v => new KhOption(v, T["ImportExport.MissingChoices." + v]))]; + + private IReadOnlyList Steps + { + get + { + var preview = _preview; + return + [ + new(T["ImportExport.Steps.Origin"], _file is { } file + ? T.Format("ImportExport.Steps.OriginDetail", file.Name, file.Count.ToString("N0", T.Culture), Size(_fileBytes)) + : T["ImportExport.Steps.OriginEmpty"]), + new(T["ImportExport.Steps.Mapping"], _file is { } mapped + ? T.Format("ImportExport.Steps.MappingDetail", _mapping.Count(m => m is not null), mapped.Headers.Count) + : T["ImportExport.Steps.MappingEmpty"]), + new(T["ImportExport.Steps.Check"], preview is null + ? T["ImportExport.Steps.CheckEmpty"] + : T.Format("ImportExport.Steps.CheckDetail", Number(preview.Rows.Count - preview.Errors - preview.Warnings), Number(preview.Warnings), Number(preview.Errors))), + new(T["ImportExport.Steps.Import"], _report is { } report + ? T.Format("ImportExport.Steps.ImportDone", Number(report.Created), Number(report.Updated)) + : preview is null ? T["ImportExport.Steps.ImportEmpty"] + : preview.CanApply ? T.Format("ImportExport.Steps.ImportReady", Number(preview.Importable)) + : T["ImportExport.Steps.ImportCheckOnly"]), + ]; + } + } + + private IReadOnlyList MissingRequired => + [.. Target.Fields.Where(f => f.Required && !_mapping.Contains(f.Key)).Select(f => FieldName(f.Key))]; + + // The first mapped columns, then the columns that have a remark somewhere, so that every remark is next to its cell. + private IReadOnlyList PreviewFields + { + get + { + var mapped = Target.Fields.Select(f => f.Key).Where(k => _mapping.Contains(k)).ToList(); + var remarked = AllRows.SelectMany(r => r.Messages).Select(m => m.Field).ToHashSet(StringComparer.Ordinal); + var shown = mapped.Take(MaxPreviewFields).ToHashSet(StringComparer.Ordinal); + shown.UnionWith(mapped.Where(remarked.Contains).Take(MaxPreviewFields)); + return [.. mapped.Where(shown.Contains)]; + } + } + + private bool HasProblems => (_report?.Rows ?? _preview?.Rows ?? []).Any(r => r.Messages.Count > 0); + + private IReadOnlyList AllRows => _report?.Rows ?? _preview?.Rows ?? []; + + private IReadOnlyList VisibleRows => + [.. AllRows.Where(r => !_onlyProblems || r.Messages.Count > 0).Take(MaxPreviewRows)]; + + private string PreviewTitle + { + get + { + var total = AllRows.Count(r => !_onlyProblems || r.Messages.Count > 0); + return total > MaxPreviewRows + ? T.Format("ImportExport.Preview.Subtitle", Number(MaxPreviewRows), Number(total)) + : T.Format("ImportExport.Preview.SubtitleAll", Number(total)); + } + } + + private string TargetName(string key) => T["ImportExport.Targets." + key]; + + private string FieldName(string key) => T.Contains("ImportExport.Fields." + key) ? T["ImportExport.Fields." + key] : key; + + private static string RequiredMark(ImportField field) => field.Required ? " *" : string.Empty; + + private static string FormatName(TransferFormat format) => format.ToString().ToUpperInvariant(); + + private string Number(int value) => value.ToString("N0", T.Culture); + + private string Size(long bytes) => bytes >= 1024 * 1024 + ? (bytes / 1024d / 1024d).ToString("0.0", T.Culture) + " MB" + : Math.Max(1, (bytes + 512) / 1024).ToString(T.Culture) + " KB"; + + private string ImportLabel(int rows) => rows == 1 ? T["ImportExport.Preview.ImportOne"] : T.Format("ImportExport.Preview.Import", Number(rows)); + + private string SectionsText(IReadOnlyDictionary sections) => + string.Join(", ", sections.Select(s => s.Key + " (" + Number(s.Value) + ")")); + + private string? Sample(int column) => _file is { Count: > 0 } file && column < file.Rows[0].Count ? file.Rows[0][column] : null; + + private IReadOnlyDictionary? CellsOf(int line) => _rows.TryGetValue(line, out var row) ? row.Values : null; + + // The cell of the file, or the value the check proposes for it (the city from the postal code). + private static string? CellOf(ImportRowResult row, IReadOnlyDictionary? cells, string key) => + cells?.GetValueOrDefault(key) ?? row.Messages.FirstOrDefault(m => m.Field == key && m.IsWarning && m.Value is not null)?.Value; + + private static string? RowClass(ImportRowResult row) => row.Outcome switch + { + ImportOutcome.Error => "kh-import-err", + ImportOutcome.Warning => "kh-import-warn", + _ => null, + }; + + private static string? CellClass(ImportRowResult row, string key) => + row.Messages.FirstOrDefault(m => m.Field == key) is { } message ? (message.IsWarning ? "kh-import-cell-warn" : "kh-import-cell-err") : null; + + private static KhTone ToneOf(ImportRowResult row) => row.Outcome switch + { + ImportOutcome.Error => KhTone.Error, + ImportOutcome.Warning => KhTone.Warning, + _ => row.Action == ImportAction.Skip ? KhTone.Neutral : KhTone.Ok, + }; + + private string OutcomeText(ImportRowResult row) => row.Outcome switch + { + ImportOutcome.Error => T["ImportExport.Preview.Error"], + ImportOutcome.Warning when row.Messages.Count == 1 => T["ImportExport.Preview.Warning"], + ImportOutcome.Warning => T.Format("ImportExport.Preview.Warnings", row.Messages.Count), + _ => T["ImportExport.Preview." + row.Action], + }; + + private string MessageText(ImportMessage message) + { + var text = !T.Contains(message.Code) ? message.Code + : message.Value is null ? T[message.Code] + : T.Format(message.Code, message.Value); + return message.Field.Length == 0 ? text : T.Format("ImportExport.MessageField", FieldName(message.Field), text); + } + + private void Reset() + { + _file = null; + _fileBytes = 0; + _mapping = []; + _rows = []; + _preview = null; + _report = null; + _onlyProblems = false; + _step = 0; + } + + private Task SetTargetAsync(string? key) + { + _targetKey = key ?? Targets[0].Key; + _options = new ImportOptions(); + if (_file is { } file) + { + _mapping = [.. ImportService.SuggestMapping(Target, file.Headers)]; + _preview = null; + _report = null; + _step = 1; + } + + return Task.CompletedTask; + } + + private void SetExisting(ExistingCodeAction value) => _options = _options with { Existing = value }; + + private void SetMissing(MissingCodeAction value) => _options = _options with { Missing = value }; + + private void SetVerifyVat(bool value) => _options = _options with { VerifyVat = value }; + + private void SetFillFromPostalCode(bool value) => _options = _options with { FillFromPostalCode = value }; + + private void SetMapping(int column, string? key) + { + var field = string.IsNullOrEmpty(key) ? null : key; + if (field is not null) + { + // A field goes to one column only: the column that had it loses it. + for (var i = 0; i < _mapping.Length; i++) + { + if (i != column && _mapping[i] == field) + { + _mapping[i] = null; + } + } + } + + _mapping[column] = field; + _preview = null; + } + + private void ChangeFile() => Reset(); + + private void BackToMapping() + { + _preview = null; + _report = null; + _step = 1; + } + + private async Task ReadAsync(InputFileChangeEventArgs e) + { + Reset(); + if (e.File.Size > MaxMegabytes * 1024L * 1024L) + { + Toasts.Show(ToastKind.Error, e.File.Name, T.Format("ImportExport.TooLarge", MaxMegabytes)); + return; + } + + _busy = true; + try + { + await using var source = e.File.OpenReadStream(MaxMegabytes * 1024L * 1024L); + var file = await ImportFileReader.ReadAsync(e.File.Name, source); + _file = file; + _fileBytes = e.File.Size; + _mapping = [.. ImportService.SuggestMapping(Target, file.Headers)]; + _step = 1; + } + catch (ImportFileException ex) + { + Toasts.Show(ToastKind.Error, e.File.Name, T[ex.Code]); + } + catch (IOException ex) + { + Toasts.Show(ToastKind.Error, e.File.Name, ex.Message); + } + finally + { + _busy = false; + } + } + + private async Task CheckAsync() + { + if (Session.Actor is not { } actor || Session.Company is not { } company || _file is not { } file) + { + return; + } + + _busy = true; + try + { + _rows = ImportService.Rows(file, _mapping).ToDictionary(r => r.Line); + _preview = await Imports.PreviewAsync(actor, company.Code, Target.Key, file, _mapping, _options); + _report = null; + _onlyProblems = _preview.Errors + _preview.Warnings > 0 && _preview.Rows.Count > MaxPreviewRows; + _step = 2; + } + catch (AccessDeniedException) + { + Toasts.Show(ToastKind.Error, T["Pages.AccessDenied.Title"], T["ImportExport.NoTargets"]); + } + finally + { + _busy = false; + } + } + + private async Task ImportAsync() + { + if (Session.Actor is not { } actor || Session.Company is not { } company || _file is not { } file || _preview is not { } preview) + { + return; + } + + if (!await Dialogs.ConfirmAsync(new(ImportLabel(preview.Importable), T.Format("ImportExport.Preview.Confirm", Number(preview.Importable)), + ImportLabel(preview.Importable), T["Common.Cancel"]))) + { + return; + } + + _busy = true; + try + { + _report = await Imports.ImportAsync(actor, company.Code, Target.Key, file, _mapping, _options); + _onlyProblems = _report.Rows.Any(r => r.Messages.Count > 0); + _step = 3; + Toasts.Show(ToastKind.Success, T.Format("ImportExport.Done.Toast", Number(_report.Created + _report.Updated)), + T.Format("ImportExport.Done.Lead", TargetName(_report.Target), _report.Created, _report.Updated, _report.Skipped, _report.Failed)); + } + catch (AccessDeniedException) + { + Toasts.Show(ToastKind.Error, T["Pages.AccessDenied.Title"], T["ImportExport.NoTargets"]); + } + catch (ImportFileException ex) + { + Toasts.Show(ToastKind.Error, TargetName(Target.Key), T[ex.Code]); + } + finally + { + _busy = false; + } + } + + private async Task ReportAsync() + { + using var buffer = new MemoryStream(); + IReadOnlyList labels = + [ + T["ImportExport.ReportColumns.Line"], T["ImportExport.ReportColumns.Key"], T["ImportExport.ReportColumns.Field"], T["ImportExport.ReportColumns.Outcome"], + T["ImportExport.ReportColumns.Message"], + ]; + await ImportService.WriteErrorReportAsync( + AllRows, + (_, message) => (T[message.IsWarning ? "ImportExport.Outcome.Warning" : "ImportExport.Outcome.Error"], MessageText(message)), + labels, + buffer); + var name = "report-" + Path.GetFileNameWithoutExtension(_file?.Name ?? Target.Key) + ".csv"; + await DownloadAsync(buffer, name, ImportService.MediaType(TransferFormat.Csv)); + } + + private async Task TemplateAsync() + { + using var buffer = new MemoryStream(); + await ImportService.WriteTemplateAsync(Target, _format, buffer); + await DownloadAsync(buffer, ImportService.FileName(Target.Key, _format, null), ImportService.MediaType(_format)); + } + + private async Task ExportAsync() + { + if (Session.Actor is not { } actor || Session.Company is not { } company) + { + return; + } + + _busy = true; + try + { + using var buffer = new MemoryStream(); + var count = await Imports.ExportAsync(actor, company.Code, Target.Key, _format, buffer); + await DownloadAsync(buffer, ImportService.FileName(Target.Key, _format, DateOnly.FromDateTime(DateTime.Now)), ImportService.MediaType(_format)); + Toasts.Show(ToastKind.Success, TargetName(Target.Key), T.Format("ImportExport.Export.Done", Number(count))); + } + catch (AccessDeniedException) + { + Toasts.Show(ToastKind.Error, T["Pages.AccessDenied.Title"], T["ImportExport.Export.NotAllowed"]); + } + finally + { + _busy = false; + } + } + + private async Task DownloadAsync(MemoryStream buffer, string name, string mediaType) + { + buffer.Position = 0; + using var stream = new DotNetStreamReference(buffer, leaveOpen: true); + await JS.InvokeVoidAsync("khaemhat.download", name, mediaType, stream); + } +} diff --git a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs index 38e14f7..3a0fe9d 100644 --- a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs +++ b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs @@ -147,6 +147,17 @@ internal static class KhaemhatServices services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + + // Guided import and export (ADR 0031): the entities in the order of the screen. + services.AddSingleton(sp => ActivatorUtilities.CreateInstance( + sp, Khaemhat.Core.Parties.PartyKind.Customer)); + services.AddSingleton(sp => ActivatorUtilities.CreateInstance( + sp, Khaemhat.Core.Parties.PartyKind.Supplier)); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddHttpClient(c => c.Timeout = TimeSpan.FromSeconds(30)); services.AddHttpClient(c => c.Timeout = TimeSpan.FromSeconds(20)); diff --git a/src/Khaemhat.Web/Resources/it-IT/ImportExport.json b/src/Khaemhat.Web/Resources/it-IT/ImportExport.json new file mode 100644 index 0000000..bd7a5bc --- /dev/null +++ b/src/Khaemhat.Web/Resources/it-IT/ImportExport.json @@ -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." + } + } +} diff --git a/src/Khaemhat.Web/Resources/it-IT/Shell.json b/src/Khaemhat.Web/Resources/it-IT/Shell.json index a32fdcf..c4de263 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Shell.json +++ b/src/Khaemhat.Web/Resources/it-IT/Shell.json @@ -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": { diff --git a/src/Khaemhat.Web/Shell/HelpLinks.cs b/src/Khaemhat.Web/Shell/HelpLinks.cs index d474eb7..eaff9b1 100644 --- a/src/Khaemhat.Web/Shell/HelpLinks.cs +++ b/src/Khaemhat.Web/Shell/HelpLinks.cs @@ -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"), diff --git a/src/Khaemhat.Web/Shell/MenuCatalog.cs b/src/Khaemhat.Web/Shell/MenuCatalog.cs index 626604d..2c9d753 100644 --- a/src/Khaemhat.Web/Shell/MenuCatalog.cs +++ b/src/Khaemhat.Web/Shell/MenuCatalog.cs @@ -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); diff --git a/src/Khaemhat.Web/wwwroot/app.css b/src/Khaemhat.Web/wwwroot/app.css index 964e824..0de2b8d 100644 --- a/src/Khaemhat.Web/wwwroot/app.css +++ b/src/Khaemhat.Web/wwwroot/app.css @@ -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; } } diff --git a/src/Khaemhat.Web/wwwroot/css/interactive.css b/src/Khaemhat.Web/wwwroot/css/interactive.css index 764da62..d52cacc 100644 --- a/src/Khaemhat.Web/wwwroot/css/interactive.css +++ b/src/Khaemhat.Web/wwwroot/css/interactive.css @@ -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); } diff --git a/tests/Khaemhat.Application.Tests/ImportRulesTests.cs b/tests/Khaemhat.Application.Tests/ImportRulesTests.cs new file mode 100644 index 0000000..257e60e --- /dev/null +++ b/tests/Khaemhat.Application.Tests/ImportRulesTests.cs @@ -0,0 +1,173 @@ +using System.Text; +using Khaemhat.Application.ImportExport; +using Khaemhat.Core.Accounting; + +namespace Khaemhat.Application.Tests; + +/// The pure parts of the guided import (issue #44, ADR 0031): values, files, mapping and the chart of accounts. +[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(() => 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(() => ReadJsonAsync("""{"codice":"A"}""")); + Assert.AreEqual(ImportErrors.FileUnreadable, wrong.Code); + var format = await Assert.ThrowsExactlyAsync(() => 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 ReadJsonAsync(string json) + { + using var stream = new MemoryStream(Encoding.UTF8.GetBytes(json)); + return await ImportFileReader.ReadAsync("dati.json", stream); + } +} diff --git a/tests/Khaemhat.Infrastructure.Tests/Files/XlsxReaderTests.cs b/tests/Khaemhat.Infrastructure.Tests/Files/XlsxReaderTests.cs new file mode 100644 index 0000000..083ad6c --- /dev/null +++ b/tests/Khaemhat.Infrastructure.Tests/Files/XlsxReaderTests.cs @@ -0,0 +1,64 @@ +using System.IO.Compression; +using System.Text; +using Khaemhat.Infrastructure.Files; + +namespace Khaemhat.Infrastructure.Tests.Files; + +/// The XLSX reader of the guided import (issue #44): what the writer produces comes back as text. +[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(() => 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(() => 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)); +} diff --git a/tests/Khaemhat.Web.Tests/ImportExport/ImportServiceTests.cs b/tests/Khaemhat.Web.Tests/ImportExport/ImportServiceTests.cs new file mode 100644 index 0000000..e97d3f5 --- /dev/null +++ b/tests/Khaemhat.Web.Tests/ImportExport/ImportServiceTests.cs @@ -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; + +/// The guided import and export on a real instance (issue #44, ADR 0031). +[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(); + var parties = app.Services.GetRequiredService(); + 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(); + var tables = app.Services.GetRequiredService(); + await tables.SaveAsync(Root, company, new ItemCategory { Code = "VALV", Description = "Valvolame" }); + var baseList = (await tables.ListAsync(Root, company, new ListQuery { Limit = 100 })).Items.Single(l => l.IsBase).Code; + var parties = app.Services.GetRequiredService(); + 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(); + 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(); + var tables = app.Services.GetRequiredService(); + 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(() => 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")); +} diff --git a/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs b/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs index 2de0bec..c30bc6b 100644 --- a/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs +++ b/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs @@ -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(); }