From 9bcf8c1082cc8a86fe0517af670a6acf4f38b568 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 11 Nov 2026 23:15:09 +0100 Subject: [PATCH] feat: company table screens, profile and fiscal years, seed command (#38, #39, #45) Gives the company tables of the previous commit their screens, so a company can be configured from the browser, and makes the base data runnable outside the web server. - one generic editor for the 26 coded tables (/tabelle/), described in TableScreens: grid with active/disabled filter, detail with errors and warnings, disable instead of delete, CSV export and all-or-nothing import, "update from base tables"; index page and menu entries - company profile in tabs with the fiscal pack checks, fiscal years with month lock/unlock, exchange rates with manual rates - PaymentTermService: installments saved together, percentages must sum to 100 - a new profile proposes the registered company name instead of its code - seed verb in Khaemhat.Web and scripts/seed.sh --base [--company CODE], shipped in the image under /app/scripts - ADR 0026 (base data only adds missing codes; ISTAT and ABI/CAB lists come as separate datasets), wiki, CHANGELOG, STATUS Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 13 + docker/Dockerfile | 4 +- docs/DEVELOPMENT.md | 6 +- docs/STATUS.md | 13 +- .../0026-tabelle-azienda-e-dati-di-base.md | 51 ++ docs/wiki/Dati-di-base-e-esempio.md | 39 +- docs/wiki/Tabelle-azienda.md | 62 ++- scripts/seed.sh | 19 +- .../Tables/CompanyProfileService.cs | 20 +- .../Tables/PaymentTermService.cs | 159 ++++++ .../Components/Pages/ComingSoon.razor | 1 - .../Pages/Tables/CompanyProfilePage.razor | 173 ++++++ .../Pages/Tables/ExchangeRatesPage.razor | 129 +++++ .../Pages/Tables/FiscalYearsPage.razor | 217 ++++++++ .../Components/Pages/Tables/TablePage.razor | 31 ++ .../Components/Pages/Tables/TablesGuard.razor | 43 ++ .../Components/Pages/Tables/TablesIndex.razor | 46 ++ .../Tables/KhPaymentTermLines.razor | 145 +++++ .../Components/Tables/KhRowField.razor | 72 +++ .../Components/Tables/KhTableEditor.razor | 451 +++++++++++++++ src/Khaemhat.Web/Hosting/KhaemhatServices.cs | 1 + src/Khaemhat.Web/Hosting/SeedCommand.cs | 115 ++++ src/Khaemhat.Web/Program.cs | 6 + src/Khaemhat.Web/Resources/it-IT/Shell.json | 6 +- src/Khaemhat.Web/Resources/it-IT/Tables.json | 526 ++++++++++++++++++ src/Khaemhat.Web/Shell/MenuCatalog.cs | 6 +- src/Khaemhat.Web/Tables/ProfileLayout.cs | 111 ++++ src/Khaemhat.Web/Tables/TableOptions.cs | 98 ++++ src/Khaemhat.Web/Tables/TableScreens.cs | 359 ++++++++++++ src/Khaemhat.Web/Tables/TableValues.cs | 143 +++++ src/Khaemhat.Web/wwwroot/css/interactive.css | 18 + .../Tables/CompanyTablesTests.cs | 26 + .../Tables/TableScreensTests.cs | 206 +++++++ 33 files changed, 3272 insertions(+), 43 deletions(-) create mode 100644 docs/adr/0026-tabelle-azienda-e-dati-di-base.md create mode 100644 src/Khaemhat.Application/Tables/PaymentTermService.cs create mode 100644 src/Khaemhat.Web/Components/Pages/Tables/CompanyProfilePage.razor create mode 100644 src/Khaemhat.Web/Components/Pages/Tables/ExchangeRatesPage.razor create mode 100644 src/Khaemhat.Web/Components/Pages/Tables/FiscalYearsPage.razor create mode 100644 src/Khaemhat.Web/Components/Pages/Tables/TablePage.razor create mode 100644 src/Khaemhat.Web/Components/Pages/Tables/TablesGuard.razor create mode 100644 src/Khaemhat.Web/Components/Pages/Tables/TablesIndex.razor create mode 100644 src/Khaemhat.Web/Components/Tables/KhPaymentTermLines.razor create mode 100644 src/Khaemhat.Web/Components/Tables/KhRowField.razor create mode 100644 src/Khaemhat.Web/Components/Tables/KhTableEditor.razor create mode 100644 src/Khaemhat.Web/Hosting/SeedCommand.cs create mode 100644 src/Khaemhat.Web/Resources/it-IT/Tables.json create mode 100644 src/Khaemhat.Web/Tables/ProfileLayout.cs create mode 100644 src/Khaemhat.Web/Tables/TableOptions.cs create mode 100644 src/Khaemhat.Web/Tables/TableScreens.cs create mode 100644 src/Khaemhat.Web/Tables/TableValues.cs create mode 100644 tests/Khaemhat.Web.Tests/Tables/TableScreensTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 658fe72..50e5096 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,19 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`. italiana, codice fiscale con calcolo, lettura dei dati e omocodia, codice destinatario SDI per azienda, PA, privato ed estero; `ViesClient` per la verifica delle partite IVA comunitarie (esito *valida*, *non valida* o *servizio non disponibile*). +- Tabelle azienda (ADR 0026): 26 tabelle codificate (codici IVA, modalità e condizioni di pagamento con le rate, + banche, valute, tipi documento, numeratori, listini, sconti, agenti, depositi, causali di magazzino, unità di misura, + vettori, porto, trasporto, causali di trasporto, aspetto dei beni, rese, nazioni, province, comuni, categorie, + centri di costo, commesse) con un'unica maschera a `/tabelle/`: elenco con filtro attive/disattivate, + dettaglio con errori e avvisi, disattivazione al posto dell'eliminazione per le righe usate, export e import CSV + tutto o niente, storico e cache condivisa fra istanze. Indice delle tabelle a `/tabelle` e voci nel menu. +- Profilo azienda a schede (dati societari, fiscale e SDI, banche, stampa, esercizi, trasmittente e intermediario) + con i controlli del pacchetto fiscale; esercizi e mesi con blocco e sblocco; cambi BCE giornalieri (attività di + sistema) e cambi manuali. +- Dati di base aggiunti alla creazione dell'azienda e a ogni avvio, solo per i codici mancanti: paesi, valute, unità + di misura, codici IVA, pagamenti, tipi documento, numeratori, causali, trasporti, deposito, listino ed esercizio in + corso. Versione salvata nelle impostazioni dell'azienda (`IT 2026.2`). +- `scripts/seed.sh --base [--company CODICE]`, incluso nell'immagine in `/app/scripts/`. ## [0.3.0] - 2026-11-11 diff --git a/docker/Dockerfile b/docker/Dockerfile index 709c53e..6458206 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -65,8 +65,8 @@ ENV ASPNETCORE_ENVIRONMENT=Production \ WORKDIR /app COPY --from=build /app ./ COPY docker/entrypoint.sh /app/entrypoint.sh -COPY scripts/restore-system.sh /app/scripts/restore-system.sh -RUN chmod 0755 /app/entrypoint.sh /app/scripts/restore-system.sh \ +COPY scripts/restore-system.sh scripts/seed.sh /app/scripts/ +RUN chmod 0755 /app/entrypoint.sh /app/scripts/restore-system.sh /app/scripts/seed.sh \ && install -d -o app -g app -m 0750 /data LABEL org.opencontainers.image.title="Khaemhat" \ diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 5fe8bae..bb3f45f 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -34,8 +34,10 @@ Se manca l'SDK 10 ci si ferma e lo si chiede al titolare (SPEC §23). Su Windows | `scripts/gen-datamodel.sh [--check]` | rigenera la sezione generata di `docs/DATA-MODEL.md` dalle migrazioni; `--check` verifica soltanto | | `KHAEMHAT_PERF=1 scripts/test.sh --filter TestCategory=Performance` | misure di riferimento dello strato dati con 100.000 righe (`docs/DATA-MODEL.md` §6.1) | -Gli stub `seed.sh` (M4) e `restore-system.sh` (M12, incluso nell'immagine, ADR 0017) spiegano l'uso previsto ed -escono con errore finché la loro milestone non li completa. +`scripts/seed.sh --base [--company CODICE]` aggiunge i dati di base mancanti (ADR 0026) con le variabili `KHAEMHAT_*` +già impostate (ad esempio quelle di `run-dev.sh`); è incluso nell'immagine in `/app/scripts/`. `--demo` arriva con +anagrafiche e articoli. Lo stub `restore-system.sh` (M12, incluso nell'immagine, ADR 0017) spiega l'uso previsto ed +esce con errore finché la sua milestone non lo completa. #### Test sui due motori diff --git a/docs/STATUS.md b/docs/STATUS.md index 24e416e..91386f6 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -3,10 +3,13 @@ > Punto di ripresa per ogni sessione. Aggiornare a fine sessione. **Ultimo aggiornamento:** 2026-11-11 -**Milestone corrente:** M4 — Tabelle, anagrafiche, articoli (issue #37-#46, nel progetto in *Da fare*). M3 chiusa: -PR #119 in `main`, tag `v0.3.0`, immagine e release. -**Prossimo passo:** M4, a partire dal pacchetto fiscale (#37) e dal profilo azienda (#38). #35 (PNG ad alta -risoluzione) resta aperta e non blocca. +**Milestone corrente:** M4 — Tabelle, anagrafiche, articoli (issue #37-#46), ramo `feat/37-tabelle-anagrafiche`. +Fatti: pacchetto fiscale (#37), validatori e VIES (#40), tabelle azienda, profilo, esercizi e cambi con le maschere +(#38, #39), dati di base e `scripts/seed.sh --base` (#45, senza gli elenchi ISTAT e ABI/CAB: serve il via +dell'utente al download). ADR 0025-0026. +**Prossimo passo:** codici automatici e compilazione automatica (#43), poi anagrafiche (#41) e articoli e listini +(#42) con i dati di esempio, import/export guidato (#44), chiusura M4 (#46). #35 (PNG ad alta risoluzione) resta +aperta e non blocca. 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. @@ -14,7 +17,7 @@ filtro predefinito nei radar. ## Fatto - Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E6. -- ADR 0001-0024. +- ADR 0001-0026. - 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/0026-tabelle-azienda-e-dati-di-base.md b/docs/adr/0026-tabelle-azienda-e-dati-di-base.md new file mode 100644 index 0000000..26f1b31 --- /dev/null +++ b/docs/adr/0026-tabelle-azienda-e-dati-di-base.md @@ -0,0 +1,51 @@ +# ADR 0026 - Tabelle azienda generiche e dati di base solo in aggiunta + +- **Stato:** accettata +- **Data:** 2026-11-11 +- **Modifica:** SPEC §4 (`scripts/seed.sh`), §11.1, §14; ADR 0025; milestone M4, issue #38, #39 e #45 + +## Contesto + +SPEC §11.1 elenca una ventina di tabelle azienda (codici IVA, pagamenti, depositi, vettori, numeratori, categorie…), +ognuna con elenco, dettaglio, import ed export CSV. SPEC §14 chiede che le tabelle di base si carichino alla creazione +dell'azienda e si aggiornino a ogni versione "senza toccare le righe modificate dall'azienda", ma non dice come +riconoscere una riga modificata. Province, comuni con CAP e la tabella ABI/CAB delle banche sono elenchi pubblici +grandi (8.000 comuni, decine di migliaia di sportelli) che non sono nel repository e hanno licenze da verificare. + +## Decisione + +1. **Un servizio per tutte le tabelle codificate.** Ogni tabella è un'entità `CodedEntity` (codice, descrizione, + disattivata) descritta in `TableCatalog`: le regole comuni (codice unico, una sola riga predefinita, eliminazione + rifiutata se la riga è usata e proposta di disattivarla, storico, cache invalidata fra istanze, CSV tutto o niente) + stanno in `TableService`. Le regole proprie di una tabella sono funzioni del catalogo; quelle italiane (natura + IVA, codici SDI) arrivano dal pacchetto fiscale (ADR 0025). +2. **Una maschera generica.** L'interfaccia descrive ogni tabella in `TableScreens` (campi, tipo, lookup, code list + del pacchetto) e la mostra con un unico editor `KhTableEditor` all'indirizzo `/tabelle/`. Profilo + azienda, esercizi e cambi hanno pagine proprie perché non sono elenchi di codici. +3. **Dati di base solo in aggiunta.** Il caricamento inserisce **solo i codici che mancano** e non modifica né + cancella righe esistenti, anche se identiche al pacchetto: una riga presente è dell'azienda. Non serve quindi + distinguere righe "modificate" da righe "originali". La versione caricata è salvata nelle impostazioni + dell'azienda (`seed.base.version`, ad esempio `IT 2026.2`). Correggere una riga di base già presente è un'azione + esplicita dell'utente, non dell'aggiornamento. +4. **Origine delle righe.** Righe fiscali (codici IVA, modalità e condizioni di pagamento, tipi documento) dal + pacchetto del paese tramite `IBaseTablesTemplate`; paesi ISO da un CSV incorporato; valute BCE, unità di misura, + trasporti, causali, deposito principale, listino base, numeratori ed esercizio corrente dal seeder di base. +5. **Comuni.** Il **codice** di un comune è il suo codice catastale (4 caratteri, quello del codice fiscale): non + serve una colonna in più. +6. **Elenchi pubblici caricati a parte.** Province, comuni con CAP e banche ABI/CAB non sono nel seed di 0.4.0: + arriveranno come file di dati con origine e licenza indicate (ISTAT, CC BY 4.0, per province e comuni) dopo il + via dell'utente al download. Fino ad allora le tabelle si riempiono a mano o con l'import CSV. +7. **Riga di comando.** `scripts/seed.sh --base [--company CODICE]` esegue la sequenza di avvio senza servire pagine + (migrazioni, prima azienda) e aggiunge i dati di base a un'azienda o a tutte quelle attive. Nel container lo + script è in `/app/scripts/` e passa da `entrypoint.sh` con il verbo `seed`; in sviluppo usa `dotnet run`. + `--demo` e `--scale` arrivano con anagrafiche e articoli. + +## Conseguenze + +- Un aggiornamento delle tabelle di base non può mai rovinare una configurazione aziendale; il rovescio è che una + correzione a un codice già presente (ad esempio un riferimento normativo cambiato) va comunicata nel `CHANGELOG` + e fatta dall'utente, o con una migrazione mirata quando è obbligatoria. +- Aggiungere una tabella costa un'entità, una mappa, una voce in `TableCatalog` e una in `TableScreens`, più i testi: + i test controllano che ogni schermata abbia le chiavi di testo e ogni codice di errore la sua traduzione. +- Il pulsante *Aggiorna da tabelle base* delle maschere e la pagina di amministrazione (mockup 089) usano lo + stesso `SeedRunner`. diff --git a/docs/wiki/Dati-di-base-e-esempio.md b/docs/wiki/Dati-di-base-e-esempio.md index dad873e..6127d75 100644 --- a/docs/wiki/Dati-di-base-e-esempio.md +++ b/docs/wiki/Dati-di-base-e-esempio.md @@ -1,6 +1,6 @@ # Dati di base e di esempio -> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M4; dati di esempio completi in M9) +> **Stato:** bozza · **Ultima revisione:** 2026-11-11 · **Versione software:** non ancora rilasciata (milestone M4; dati di esempio completi in M9) > **Modulo di licenza:** CORE · **Livello richiesto:** amministratore (rimozione dati di esempio: super utente) · **Specifica:** SPEC §6, §12.11, §14 ## A cosa serve @@ -56,6 +56,20 @@ Il pacchetto italiano fa parte del pacchetto fiscale Italia (vedi [Fiscalità it | **CRM** | pipeline e fasi, modelli e-mail | | **Sistema** | ruoli predefiniti, regole di automazione predefinite, attività programmate di sistema | +### Cosa c'è oggi + +Dalla versione 0.4.0 il caricamento di base contiene: paesi ISO con appartenenza all'UE, le 30 valute dei cambi BCE, +unità di misura, codici IVA e nature, modalità `MP01`-`MP23` e condizioni di pagamento con le rate, tipi documento +con codice TD, numeratori, causali di magazzino, deposito principale, porti, trasporto a cura, causali di trasporto, +aspetto dei beni, rese, categorie, listino base e l'esercizio dell'anno in corso con i suoi mesi. Le righe fiscali +vengono dal pacchetto del paese dell'azienda. + +**Province, comuni e banche ABI/CAB** non sono ancora inclusi: sono elenchi pubblici (ISTAT per province e comuni) +che verranno aggiunti come file di dati con origine e licenza indicate. Nel frattempo si caricano con l'**Importa CSV** +delle rispettive tabelle. Il **codice** di un comune è il suo codice catastale (es. `H501` per Roma). Le altre +voci dell'elenco (piano dei conti, causali contabili, registri IVA, cespiti, codici tributo, CRM) arrivano con i +moduli che le usano. + ### Aggiorna tabelle di base Ogni nuova versione di Khaemhat può portare un pacchetto aggiornato (nuovi codici IVA, nuovi tipi documento SDI, @@ -64,8 +78,12 @@ nuovi codici tributo…). 1. Premi **Anteprima differenze** per vedere cosa cambierebbe. 2. Premi **Aggiorna tabelle di base**. -L'aggiornamento è **idempotente** (rieseguirlo non duplica nulla) e **aggiunge solo i codici mancanti senza -toccare le righe che l'azienda ha modificato**. +L'aggiornamento è **idempotente** (rieseguirlo non duplica nulla) e **aggiunge solo i codici mancanti**: una riga +già presente non viene mai modificata né cancellata, anche se l'azienda non l'ha mai toccata. Se una nuova versione +corregge un codice esistente (ad esempio un riferimento normativo), il [CHANGELOG](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/src/branch/main/CHANGELOG.md) +lo segnala e la correzione si fa nella tabella. La versione caricata è salvata nelle impostazioni dell'azienda. + +Lo stesso aggiornamento si avvia dal menu `…` di ogni tabella con **Aggiorna da tabelle base**. Le tabelle di base si caricano anche automaticamente alla creazione di un'azienda, se la variabile `KHAEMHAT_SEED_BASE` non è `false` (predefinito `true`). @@ -125,14 +143,21 @@ esempio. ## Da riga di comando -Lo script `scripts/seed.sh` esegue le stesse operazioni fuori dall'interfaccia (utile in sviluppo): +Lo script `scripts/seed.sh` aggiunge le tabelle di base fuori dall'interfaccia. Esegue la sequenza di avvio +(migrazioni, prima azienda) senza servire pagine, poi lavora su un'azienda o su tutte quelle attive e stampa le righe +aggiunte per tabella. Usa le stesse variabili `KHAEMHAT_*` del servizio. + +Nel container (lo script è in `/app/scripts/`): ``` -scripts/seed.sh --base -scripts/seed.sh --demo [--scale N] [--company CODICE] +docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --base +docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --base --company DEMO ``` -`--scale N` moltiplica i volumi dei dati di esempio (usato per le prove di prestazione). +In sviluppo, dalla cartella del repository: `scripts/seed.sh --base [--company CODICE]`. + +Le opzioni `--demo [--scale N]` per i dati di esempio (`--scale N` moltiplica i volumi, per le prove di prestazione) +arrivano con anagrafiche e articoli; oggi vengono rifiutate con un messaggio. ## Migrazioni diff --git a/docs/wiki/Tabelle-azienda.md b/docs/wiki/Tabelle-azienda.md index db9dfd8..f2e7635 100644 --- a/docs/wiki/Tabelle-azienda.md +++ b/docs/wiki/Tabelle-azienda.md @@ -1,7 +1,7 @@ # Tabelle azienda -> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M4) -> **Modulo di licenza:** CORE · **Permessi principali:** famiglia `company.*` (codici esatti definiti in sviluppo) · **Specifica:** SPEC §11.1, §11.12 (codici automatici, compilazione, preferenze), §14 +> **Stato:** bozza · **Ultima revisione:** 2026-11-11 · **Versione software:** non ancora rilasciata (milestone M4) +> **Modulo di licenza:** CORE · **Permessi principali:** `company.settings.read` (consultare), `company.settings.write` (modificare) · **Specifica:** SPEC §11.1, §11.12 (codici automatici, compilazione, preferenze), §14 Le **tabelle azienda** sono i dati di configurazione su cui si appoggia tutto il resto: il **profilo dell'azienda**, gli **esercizi e i periodi**, i **codici IVA**, i pagamenti, le banche, i depositi, i numeratori dei documenti, i @@ -10,18 +10,45 @@ dati di base italiani (vedi [Dati di base e di esempio](Dati-di-base-e-esempio)) ## Dove si trova -Menu **Tabelle azienda** → *Profilo azienda*, *Codici IVA*, *Pagamenti*, *Numeratori*, *Depositi*, *Valute*, -*Trasporti*, *Preferenze e codici automatici*; le altre tabelle sono raggiungibili dallo stesso menu e dalla ricerca -globale (`Ctrl+K`). Esercizi e periodi sono in *Tabelle azienda → Esercizi*. +Menu **Tabelle azienda**: la voce principale apre l'indice di tutte le tabelle (`/tabelle`), raggruppate in +*Azienda*, *Fisco, pagamenti e banche*, *Vendite e documenti*, *Magazzino e trasporto*, *Geografia* e *Classificazioni*. Sotto la voce +ci sono le scorciatoie per *Profilo azienda*, *Esercizi*, *Codici IVA*, *Pagamenti*, *Numeratori*, *Depositi*, +*Valute* e *Cambi*. Ogni tabella ha un indirizzo proprio, ad esempio `/tabelle/codici-iva`, ed è raggiungibile anche +dalla ricerca globale (`Ctrl+K`). *Preferenze e codici automatici* arriva con il resto di M4. -Ogni tabella ha la propria maschera, costruita come il radar dei clienti e la maschera dei codici IVA: elenco con -ricerca e filtri, dettaglio sotto o in scheda, **import ed export CSV**. +## Come si usa una tabella + +Tutte le tabelle codificate hanno la stessa maschera: + +- **Elenco** con ricerca, filtro rapido *Attive / Disattivate / Tutte* (all'apertura si vedono solo le attive) e + colonne principali; un clic sceglie la riga, doppio clic o `Invio` la apre. +- **Dettaglio** sotto l'elenco: *Codice*, *Descrizione*, *Disattivata* e i campi propri della tabella. Gli errori + compaiono accanto al campo e nel riepilogo; gli **avvisi** (ad esempio un codice IVA senza riferimento normativo) + non bloccano il salvataggio. +- **Barra comandi**: *Nuovo*, *Salva* (`Ctrl+S`), *Annulla modifiche*, *Elimina*. Una riga usata altrove non si può + eliminare: Khaemhat propone di **disattivarla**, così resta nei documenti già fatti ma non si propone più. +- Menu `…`: **Esporta CSV**, **Importa CSV** e **Aggiorna da tabelle base**. +- Uscendo con modifiche non salvate viene chiesta conferma. + +**Importa CSV** (file fino a 20 MB, separatore `;`, `,` o tabulazione, prima riga con i nomi delle colonne come nell'export): le +righe con un codice già presente vengono aggiornate, le altre aggiunte. È **tutto o niente**: se una riga ha un +errore non viene importato nulla e la finestra elenca riga, campo e motivo. + +**Aggiorna da tabelle base** aggiunge i codici di base mancanti senza modificare le righe che ci sono già (vedi +[Dati di base e di esempio](Dati-di-base-e-esempio)). + +Le **condizioni di pagamento** hanno anche le **rate**: giorni, fine mese, giorno fisso e percentuale; la somma delle +percentuali deve fare 100 e le rate si salvano tutte insieme. ## Profilo azienda ![075 · Profilo azienda](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/075-profilo-azienda.png) *Mockup 075 — profilo azienda: schede Dati societari, Fiscale e SDI, Banche, Logo e stampe, Esercizi e periodicità, Trasmittente/intermediario (anteprima ridotta).* +Indirizzo: `/tabelle/profilo-azienda`. Al salvataggio partita IVA, codice fiscale, codice destinatario e regime +fiscale sono controllati dal pacchetto fiscale del paese; se un errore è in un'altra scheda, Khaemhat si sposta +sulla scheda del primo errore. Il logo per le stampe arriva con i modelli di stampa dei documenti. + Il profilo è una scheda unica (una sola per azienda). In alto a destra un badge indica la versione del **pacchetto fiscale** in uso (es. *IT 2026.2*). @@ -49,6 +76,10 @@ sblocca. **Periodi** (mesi o trimestri secondo la periodicità IVA): stato *aperto*, *liquidato* o *bloccato*, esito della liquidazione IVA (*provvisoria*, *confermata*), registrazioni, interruttore **Blocco**. +Indirizzo: `/tabelle/esercizi`. **Nuovo esercizio** crea l'anno successivo all'ultimo con i suoi dodici mesi. Il +pulsante **Blocca** di un mese impedisce nuove registrazioni con date in quel mese; **Sblocca** chiede conferma. Un +mese *liquidato* si sblocca solo annullando la liquidazione IVA (M7). + Regola fondamentale: **si possono registrare documenti e movimenti contabili solo con data in un periodo aperto**. Un periodo bloccato rifiuta ogni registrazione con data al suo interno; la conferma della liquidazione IVA blocca il periodo (vedi [IVA](IVA)) e la chiusura dell'esercizio lo rende di sola lettura (vedi [Contabilità](Contabilita)). @@ -58,8 +89,8 @@ periodo (vedi [IVA](IVA)) e la chiusura dell'esercizio lo rende di sola lettura | Tabella | Contenuto | |---|---| | **Paesi** | codici ISO 3166-1, appartenenza all'UE, codice SDI per l'estero (`XXXXXXX`) | -| **Province** e **Comuni** | CAP e codice catastale: servono per la compilazione da CAP e per il calcolo del codice fiscale | -| **Valute** e **Cambi** | valute con i cambi giornalieri della BCE | +| **Province** e **Comuni** | CAP e codice catastale (il codice del comune è il codice catastale): servono per la compilazione da CAP e per il calcolo del codice fiscale. Gli elenchi ISTAT si caricano a parte, vedi [Dati di base e di esempio](Dati-di-base-e-esempio) | +| **Valute** e **Cambi** | valute con i cambi giornalieri della BCE; in *Cambi* (`/tabelle/cambi`) si vedono i cambi per data e origine e si inserisce un cambio manuale | | **Unità di misura** | codici interni e codice usato nell'XML SDI | | **Codici IVA** | aliquota, natura SDI, riferimento normativo, esigibilità, tipo, indetraibilità, conti IVA, validità (vedi sotto) | | **Metodi di pagamento** | codici SDI `MP01`…`MP23` (es. MP01 contanti, MP02 assegno, MP05 bonifico, MP08 carta di pagamento, MP12 RiBa, MP19 SEPA Direct Debit) | @@ -112,11 +143,14 @@ sotto-codice scelto in riga), `SPLIT` (split payment), indetraibili 50% e 100%, ## Numeratori -Ogni **tipo documento** usa un numeratore per **sezionale** e **anno**, con un **formato** che di predefinito è -`{prefix}/{anno}/{number:D6}`, ad esempio `FT/2026/000419`. Il numero è assegnato in modo atomico **alla conferma**; -per fatture, note di credito e registrazioni contabili definitive **non sono ammessi buchi** nella numerazione. Il -protocollo IVA degli acquisti ha il proprio formato (es. `ACQ/{anno}/…`) e i progressivi si azzerano a ogni -esercizio (impostazione *Reset progressivi*). +Ogni **tipo documento** usa un numeratore per **sezionale** e **anno**, con un **formato** composto dai segnaposto +`{prefix}`, `{year}`, `{section}` e `{number}` (con `{number:D6}` il numero ha sei cifre con gli zeri davanti). Il +formato deve contenere `{number}`. Esempi dei numeratori di base: fatture `{number}/{year}` (`419/2026`), ordini +clienti `OC-{year}-{number:D4}` (`OC-2026-0042`), autofatture `{number}/AF/{year}` nel sezionale `AF`. + +Il numero è assegnato in modo atomico **alla conferma** del documento (da M5); per fatture, note di credito, +protocollo acquisti e registrazioni contabili **non sono ammessi buchi** nella numerazione (opzione *Ammessi buchi di numerazione* +spenta). I numeratori sono per anno: il caricamento di base crea quelli dell'anno in corso. ## Preferenze e codici automatici diff --git a/scripts/seed.sh b/scripts/seed.sh index 7fd5256..ccef53d 100755 --- a/scripts/seed.sh +++ b/scripts/seed.sh @@ -1,9 +1,16 @@ #!/usr/bin/env bash -# Loads base tables and demo data into a company database (SPEC §15). -# scripts/seed.sh --base | --demo [--scale N] [--company CODE] -# Stub: completed in milestone M4 (SPEC §20). Until then it explains what it will do and exits with an error. +# Adds the missing base tables to the company databases (SPEC §14, ADR 0026). Rows already there are never changed. +# scripts/seed.sh --base [--company CODE] +# In the container (shipped as /app/scripts/seed.sh, same KHAEMHAT_* variables as the service): +# docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --base +# On a development machine it runs the project with the variables already set in the shell (see scripts/run-dev.sh). +# The demo data (--demo [--scale N]) arrive with parties and items. set -euo pipefail -echo "seed.sh: non ancora disponibile, arriva con la milestone M4." >&2 -echo "Uso previsto: scripts/seed.sh --base | --demo [--scale N] [--company CODE]" >&2 -exit 1 +if [[ -f /app/Khaemhat.Web.dll ]]; then + # The entrypoint prepares the user and waits for the database, then runs "dotnet Khaemhat.Web.dll seed ...". + exec /app/entrypoint.sh seed "$@" +fi + +root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +exec dotnet run --project "$root/src/Khaemhat.Web" -- seed "$@" diff --git a/src/Khaemhat.Application/Tables/CompanyProfileService.cs b/src/Khaemhat.Application/Tables/CompanyProfileService.cs index 35dad98..ccdf48c 100644 --- a/src/Khaemhat.Application/Tables/CompanyProfileService.cs +++ b/src/Khaemhat.Application/Tables/CompanyProfileService.cs @@ -5,6 +5,7 @@ using Khaemhat.Core.Tables; using Khaemhat.Core.Tax; using Khaemhat.Core.Validation; using Khaemhat.Data; +using Khaemhat.Data.Companies; using Khaemhat.Data.Querying; using Khaemhat.Fiscal.Abstractions; @@ -42,6 +43,7 @@ public sealed partial class CompanyProfileService private readonly AuditTrail _audit; private readonly CompanyFiscalContext _fiscal; private readonly FiscalPackCatalog _packs; + private readonly ICompanyRegistry _companies; /// Creates the service. /// Opens the company databases. @@ -49,13 +51,16 @@ public sealed partial class CompanyProfileService /// Writes the history. /// The fiscal pack of each company. /// The installed fiscal packs. - public CompanyProfileService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, CompanyFiscalContext fiscal, FiscalPackCatalog packs) + /// The registry, for the name of a company without a profile yet. + public CompanyProfileService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, CompanyFiscalContext fiscal, FiscalPackCatalog packs, ICompanyRegistry companies) { ArgumentNullException.ThrowIfNull(factory); ArgumentNullException.ThrowIfNull(permissions); ArgumentNullException.ThrowIfNull(audit); ArgumentNullException.ThrowIfNull(fiscal); ArgumentNullException.ThrowIfNull(packs); + ArgumentNullException.ThrowIfNull(companies); + _companies = companies; _factory = factory; _permissions = permissions; _audit = audit; @@ -71,8 +76,17 @@ public sealed partial class CompanyProfileService public async Task GetAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) { var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.ReadPermission, cancellationToken).ConfigureAwait(false); - await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); - return await LoadAsync(uow, cancellationToken).ConfigureAwait(false) ?? NewProfile(company); + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + if (await LoadAsync(uow, cancellationToken).ConfigureAwait(false) is { } profile) + { + return profile; + } + } + + // A new profile starts from the name the company was registered with. + var registered = await _companies.FindAsync(company, cancellationToken).ConfigureAwait(false); + return NewProfile(registered?.Name is { Length: > 0 } name ? name : company); } /// Checks a profile without saving it. diff --git a/src/Khaemhat.Application/Tables/PaymentTermService.cs b/src/Khaemhat.Application/Tables/PaymentTermService.cs new file mode 100644 index 0000000..8b38fba --- /dev/null +++ b/src/Khaemhat.Application/Tables/PaymentTermService.cs @@ -0,0 +1,159 @@ +using Khaemhat.Application.Audit; +using Khaemhat.Application.Security; +using Khaemhat.Core.Caching; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Tables; + +/// +/// The installments of a payment term (SPEC §11.1): days from the document date, end of month, fixed day and share of +/// the amount. They are saved all together, because only the whole set has to add up to 100%. +/// +public sealed class PaymentTermService +{ + /// The installments do not add up to 100%. + public const string PercentTotal = "tables.payment-term.percent-total"; + + /// A payment term needs at least one installment. + public const string LinesRequired = "tables.payment-term.lines-required"; + + /// The days are negative or beyond a year and a half. + public const string DaysRange = "tables.payment-term.days"; + + /// The fixed day is not a day of the month. + public const string FixedDayRange = "tables.payment-term.fixed-day"; + + /// The field the errors of the installments are reported on. + public const string LinesField = "Lines"; + + private const int MaxDays = 540; + + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly AuditTrail _audit; + private readonly ICacheProvider _cache; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The audit trail. + /// The cache of the tables. + public PaymentTermService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, ICacheProvider cache) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(audit); + ArgumentNullException.ThrowIfNull(cache); + _factory = factory; + _permissions = permissions; + _audit = audit; + _cache = cache; + } + + /// The installments of a payment term, in order. + /// Who reads. + /// The company. + /// The payment term. + /// Cancellation. + /// The installments. + public async Task> LinesAsync(Actor actor, string companyCode, long paymentTermId, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.ReadPermission, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await ReadAsync(uow, paymentTermId, cancellationToken).ConfigureAwait(false); + } + + /// Checks a set of installments. + /// The installments. + /// The errors, on . + public static IReadOnlyList Validate(IReadOnlyList lines) + { + ArgumentNullException.ThrowIfNull(lines); + var problems = new List(); + if (lines.Count == 0) + { + problems.Add(new(LinesField, LinesRequired)); + return problems; + } + + if (lines.Any(l => l.Days < 0 || l.Days > MaxDays)) + { + problems.Add(new(LinesField, DaysRange)); + } + + if (lines.Any(l => l.FixedDay is < 1 or > 31)) + { + problems.Add(new(LinesField, FixedDayRange)); + } + + if (lines.Any(l => l.Percent <= 0) || lines.Sum(l => l.Percent) != 100m) + { + problems.Add(new(LinesField, PercentTotal)); + } + + return problems; + } + + /// Replaces the installments of a payment term, numbering them 1, 2, 3 in the given order. + /// Who saves. + /// The company. + /// The payment term. + /// The installments. + /// Cancellation. + /// The saved installments. + /// The installments are not valid (Lines:code). + public async Task> SaveLinesAsync(Actor actor, string companyCode, long paymentTermId, IReadOnlyList lines, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(lines); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TableService.WritePermission, cancellationToken).ConfigureAwait(false); + var problems = Validate(lines); + if (problems.Count > 0) + { + throw new ValidationFailedException([.. problems.Select(p => p.Field + ":" + p.Code)]); + } + + IReadOnlyList saved; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + _ = await uow.Repository().GetAsync(paymentTermId, cancellationToken).ConfigureAwait(false) + ?? throw new KeyNotFoundException(TableService.NotFound); + var repository = uow.Repository(); + foreach (var old in await ReadAsync(uow, paymentTermId, cancellationToken).ConfigureAwait(false)) + { + await repository.DeleteAsync(old.Id, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Delete, old.Id, old, null, actor.UserName, cancellationToken).ConfigureAwait(false); + } + + var number = 0; + foreach (var line in lines) + { + var row = new PaymentTermLine + { + PaymentTermId = paymentTermId, + Number = ++number, + Days = line.Days, + EndOfMonth = line.EndOfMonth, + FixedDay = line.FixedDay, + Percent = line.Percent, + }; + var id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Insert, id, null, row, actor.UserName, cancellationToken).ConfigureAwait(false); + } + + saved = await ReadAsync(uow, paymentTermId, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + await _cache.PublishInvalidationAsync(CacheKeys.Prefix(company, "tables"), cancellationToken).ConfigureAwait(false); + return saved; + } + + private static async Task> ReadAsync(IUnitOfWork uow, long paymentTermId, CancellationToken cancellationToken) => + (await uow.Repository() + .ListAsync(Query.For().Where(x => x.PaymentTermId == paymentTermId).OrderBy(x => x.Number), cancellationToken) + .ConfigureAwait(false)).Items; +} diff --git a/src/Khaemhat.Web/Components/Pages/ComingSoon.razor b/src/Khaemhat.Web/Components/Pages/ComingSoon.razor index dc42fc8..fd4fa6c 100644 --- a/src/Khaemhat.Web/Components/Pages/ComingSoon.razor +++ b/src/Khaemhat.Web/Components/Pages/ComingSoon.razor @@ -10,7 +10,6 @@ @page "/servizi/{*Rest}" @page "/canali/{*Rest}" @page "/report/{*Rest}" -@page "/tabelle/{*Rest}" @page "/automazioni/{*Rest}" @page "/amministrazione/{*Rest}" @attribute [Authorize] diff --git a/src/Khaemhat.Web/Components/Pages/Tables/CompanyProfilePage.razor b/src/Khaemhat.Web/Components/Pages/Tables/CompanyProfilePage.razor new file mode 100644 index 0000000..ef85522 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Tables/CompanyProfilePage.razor @@ -0,0 +1,173 @@ +@page "/tabelle/profilo-azienda" +@attribute [Authorize] +@using Khaemhat.Application.Security +@using Khaemhat.Application.Tables +@using Khaemhat.Core.Common +@using Khaemhat.Core.Tables +@using Khaemhat.Web.Tables +@using Khaemhat.Web.Components.Tables +@inject ShellSession Session +@inject CompanyProfileService Profiles +@inject TableService Tables +@inject CompanyFiscalContext Fiscal +@inject ToastService Toasts + +@* The company profile (SPEC §11.1, mockup 075): company data, tax and e-invoice, default bank, print, fiscal year and + VAT, transmitter and intermediary. The country of the profile picks the fiscal pack of the company. *@ + + + +
+
+
@T["Shell.Menu.CompanyTables"] / @T["CompanyTables.Profile.Title"]
+

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

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

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

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

@T["CompanyTables.Profile.LogoHint"]

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

@T["CompanyTables.Rates.Title"]

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

@T["CompanyTables.FiscalYears.Heading"]

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

@T["CompanyTables.FiscalYears.None"]

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

@T["Pages.NotFound.Title"]

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

@T["Common.Loading"]

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

@T["CompanyTables.NoCompany.Title"]

+

@T["CompanyTables.NoCompany.Lead"]

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

@T["Pages.AccessDenied.Title"]

+

@T["Pages.AccessDenied.Lead"]

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

@T["Shell.Menu.CompanyTables"]

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

@_error

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

@T[Screen.TitleKey]

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

@T["CompanyTables.Import.Text"]

+

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

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

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

+ } + else + { +

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

+
    + @foreach (var error in result.Errors.Take(50)) + { +
  • @T.Format("CompanyTables.Import.Error", error.Row, error.Field ?? "-", ErrorText(error.Code))
  • + } +
+ } + } +
+
+ +
+
+ +@code { + private const long MaxImportBytes = 20L * 1024 * 1024; + + private readonly KhValidation _validation = new(); + private readonly TableOptions _options = new(); + private KhRadar? _radar; + private TRow? _row; + private TRow? _saved; + private bool _modified; + private bool _busy; + private bool _importOpen; + private TableImportResult? _import; + private List _warnings = []; + private IReadOnlyList>? _columns; + + /// The table. + [Parameter, EditorRequired] + public TableScreen Screen { get; set; } = default!; + + private static string? DisabledClass(TRow row) => row.Disabled ? "muted" : null; + + private TableDefinition Definition => Tables.Catalog.Find(Screen.Key)!; + + private string? Company => Session.Company?.Code; + + private bool CanWrite => Session.Permissions.Allows(TableService.WritePermission); + + private string DetailTitle => _row is { Id: > 0 } row ? T.Format("CompanyTables.Detail", row.Code) : T["CompanyTables.NewRow"]; + + private IReadOnlyList EnabledOnly => [new("disabled", ListFilterOperator.Equals, ["false"])]; + + private IReadOnlyList QuickFilters => + [ + new("disabled", T["CompanyTables.Filter.State"], + [ + new(string.Empty, T["CompanyTables.Filter.All"]), new("false", T["CompanyTables.Filter.Enabled"]), new("true", T["CompanyTables.Filter.Disabled"]), + ]), + ]; + + private IReadOnlyList> Columns => _columns ??= + [ + new("code", T["CompanyTables.Fields.Code"], r => r.Code) { Kind = KhColumnKind.Code, Width = "110px" }, + new("description", T["CompanyTables.Fields.Description"], r => r.Description), + .. Screen.Fields.Where(f => f.InGrid).Select(Column), + new("disabled", T["CompanyTables.Fields.Disabled"], r => r.Disabled) { Kind = KhColumnKind.Bool, Width = "90px" }, + ]; + + private IReadOnlyList ToolbarItems => + [ + new("new", "plus", T["CompanyTables.New"]) { OnClick = NewAsync, Disabled = !CanWrite, Primary = true, Shortcut = "Alt+N" }, + new("save", "save", T["Common.Save"]) { OnClick = SaveAsync, Disabled = !CanWrite || !_modified || _busy, Shortcut = "Ctrl+S" }, + new("undo", "undo", T["CompanyTables.Undo"]) { OnClick = UndoAsync, Disabled = !_modified }, + new("delete", "trash", T["CompanyTables.Delete"]) { OnClick = DeleteAsync, Disabled = !CanWrite || _row is not { Id: > 0 } || _busy, Danger = true }, + new("export", "download", T["CompanyTables.Export"]) { Kind = ToolbarKind.Action, OnClick = ExportAsync }, + new("import", "upload", T["CompanyTables.Import.Title"]) { Kind = ToolbarKind.Action, OnClick = OpenImport, Disabled = !CanWrite }, + new("base", "refresh", T["CompanyTables.BaseData"]) { Kind = ToolbarKind.Action, OnClick = BaseDataAsync, Disabled = !CanWrite || _busy }, + ]; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + if (Company is { } company) + { + await LoadOptionsAsync(company); + } + } + + private KhColumn Column(TableField field) + { + var property = TableValues.PropertyOf(typeof(TRow), field); + return field.Kind switch + { + TableFieldKind.Number => new(field.Property, T[field.LabelKey], r => TableValues.GetNumber(r, property)) + { + Kind = KhColumnKind.Number, Decimals = field.Decimals, Width = field.Width, Sortable = false, + }, + TableFieldKind.Bool => new(field.Property, T[field.LabelKey], r => property.GetValue(r)) { Kind = KhColumnKind.Bool, Width = field.Width, Sortable = false }, + TableFieldKind.Date => new(field.Property, T[field.LabelKey], r => property.GetValue(r)) { Kind = KhColumnKind.Date, Width = field.Width, Sortable = false }, + TableFieldKind.Choice => new(field.Property, T[field.LabelKey], r => property.GetValue(r) is Enum v ? T[TableScreens.EnumKey(v)] : null) + { + Width = field.Width, Sortable = false, + }, + TableFieldKind.Lookup => new(field.Property, T[field.LabelKey], r => _options.CodeOf(field, TableValues.GetText(r, property))) { Width = field.Width, Sortable = false }, + _ => new(field.Property, T[field.LabelKey], r => TableValues.GetText(r, property)) + { + Kind = field.Kind is TableFieldKind.Code or TableFieldKind.CodeList ? KhColumnKind.Code : KhColumnKind.Text, Width = field.Width, Sortable = false, + }, + }; + } + + private async Task LoadOptionsAsync(string company) + { + if (Session.Actor is { } actor) + { + await _options.LoadAsync(Tables, Fiscal, Screen.Fields, actor, company); + _columns = null; + } + } + + private Task> ListAsync(ListQuery query, CancellationToken cancellationToken) => + Session.Actor is { } actor && Company is { } company + ? Tables.ListAsync(actor, company, query, cancellationToken) + : Task.FromResult(new ListPage([], 0, new Dictionary())); + + private async Task OpenAsync(TRow row) + { + if (_row?.Id == row.Id || !await LeaveAsync()) + { + return; + } + + Show(row); + } + + private void Show(TRow row) + { + _row = Copy(row); + _saved = row.Id > 0 ? Copy(row) : null; + _modified = false; + _warnings = []; + _validation.Clear(); + } + + // Asks before throwing away what was typed. + private async Task LeaveAsync() => + !_modified || await Dialogs.ConfirmAsync(new ConfirmRequest(T["CompanyTables.Leave.Title"], T["CompanyTables.Leave.Text"], T["CompanyTables.Leave.Confirm"], + T["Common.Cancel"], Danger: true)); + + private async Task NewAsync() + { + if (await LeaveAsync()) + { + Show(new TRow()); + _modified = true; + } + } + + private Task UndoAsync() + { + if (_saved is { } saved) + { + Show(saved); + } + else + { + _row = null; + _modified = false; + _validation.Clear(); + } + + return Task.CompletedTask; + } + + private void Change(Action change) + { + change(); + _modified = true; + } + + private async Task SaveAsync() + { + if (_row is null || Session.Actor is not { } actor || Company is not { } company) + { + return; + } + + _busy = true; + _validation.Clear(); + try + { + var problems = await Tables.ValidateAsync(actor, company, _row); + _warnings = [.. problems.Where(p => p.IsWarning).Select(p => T[p.Code])]; + var errors = problems.Where(p => !p.IsWarning).ToList(); + if (errors.Count > 0) + { + foreach (var problem in errors) + { + _validation.Add(problem.Field, ErrorText(problem.Code)); + } + + Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], T["CompanyTables.FixFields"]); + return; + } + + var saved = await Tables.SaveAsync(actor, company, _row); + var warnings = _warnings; + Show(saved); + _warnings = warnings; + Toasts.Show(ToastKind.Success, T["CompanyTables.Saved"], saved.Code); + await RefreshAsync(company); + } + catch (ValidationFailedException ex) + { + foreach (var (field, code) in ex.Errors.Select(TableValues.SplitError)) + { + _validation.Add(field, ErrorText(code)); + } + + Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], T["CompanyTables.FixFields"]); + } + catch (ConcurrencyException) + { + Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], T["CompanyTables.Concurrency"]); + } + finally + { + _busy = false; + } + } + + private async Task DeleteAsync() + { + if (_row is not { Id: > 0 } row || Session.Actor is not { } actor || Company is not { } company) + { + return; + } + + if (!await Dialogs.ConfirmAsync(new ConfirmRequest(T["CompanyTables.Delete"], T.Format("CompanyTables.DeleteText", row.Code), T["CompanyTables.Delete"], + T["Common.Cancel"], Danger: true))) + { + return; + } + + _busy = true; + try + { + var outcome = await Tables.DeleteAsync(actor, company, row.Id); + Toasts.Show(ToastKind.Success, outcome == TableDeleteOutcome.Deleted ? T["CompanyTables.Deleted"] : T["CompanyTables.DisabledInstead"], row.Code); + _row = null; + _saved = null; + _modified = false; + await RefreshAsync(company); + } + catch (KeyNotFoundException) + { + Toasts.Show(ToastKind.Error, T["tables.not-found"]); + } + finally + { + _busy = false; + } + } + + private async Task RefreshAsync(string company) + { + if (Screen.Fields.Any(f => f.Lookup == typeof(TRow))) + { + await LoadOptionsAsync(company); + } + + if (_radar is not null) + { + await _radar.ReloadAsync(); + } + } + + private async Task ExportAsync() + { + if (Session.Actor is not { } actor || Company is not { } company) + { + return; + } + + using var buffer = new MemoryStream(); + var count = await Tables.ExportCsvAsync(actor, company, buffer); + buffer.Position = 0; + using var stream = new DotNetStreamReference(buffer, leaveOpen: true); + await JS.InvokeVoidAsync("khaemhat.download", Screen.Slug + ".csv", "text/csv", stream); + Toasts.Show(ToastKind.Success, T.Format("Ui.Grid.Exported", T.Number(count))); + } + + private Task OpenImport() + { + _import = null; + _importOpen = true; + return Task.CompletedTask; + } + + private void CloseImport() => _importOpen = false; + + private async Task ImportAsync(InputFileChangeEventArgs e) + { + if (Session.Actor is not { } actor || Company is not { } company) + { + return; + } + + if (e.File.Size > MaxImportBytes) + { + Toasts.Show(ToastKind.Error, e.File.Name, T["CompanyTables.Import.TooLarge"]); + return; + } + + _busy = true; + try + { + await using var source = e.File.OpenReadStream(MaxImportBytes); + using var content = new MemoryStream(); + await source.CopyToAsync(content); + content.Position = 0; + _import = await Tables.ImportCsvAsync(actor, company, content); + if (_import.Succeeded) + { + await RefreshAsync(company); + } + } + finally + { + _busy = false; + } + } + + private async Task BaseDataAsync() + { + if (Session.Actor is not { } actor || Company is not { } company) + { + return; + } + + _busy = true; + try + { + var report = await Seeds.UpdateBaseAsync(actor, company); + Toasts.Show(ToastKind.Success, T["CompanyTables.BaseData"], T.Format("CompanyTables.BaseDataDone", report.Total, report.DataVersion)); + await LoadOptionsAsync(company); + await RefreshAsync(company); + } + finally + { + _busy = false; + } + } + + private string ErrorText(string code) => T.Contains(code) ? T[code] : T["CompanyTables.UnknownError"]; + + private static TRow Copy(TRow row) + { + var copy = new TRow(); + foreach (var property in typeof(TRow).GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.CanRead && p.CanWrite)) + { + property.SetValue(copy, property.GetValue(row)); + } + + return copy; + } +} diff --git a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs index 4993dbe..aa3bd4d 100644 --- a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs +++ b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs @@ -141,6 +141,7 @@ internal static class KhaemhatServices 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/Hosting/SeedCommand.cs b/src/Khaemhat.Web/Hosting/SeedCommand.cs new file mode 100644 index 0000000..1a00255 --- /dev/null +++ b/src/Khaemhat.Web/Hosting/SeedCommand.cs @@ -0,0 +1,115 @@ +using System.Globalization; +using Khaemhat.Application.Instance; +using Khaemhat.Application.Seeding; +using Khaemhat.Core.Instance; +using Khaemhat.Data; +using Khaemhat.Data.Companies; +using Khaemhat.Infrastructure.Logging; + +namespace Khaemhat.Web.Hosting; + +/// +/// The command line of scripts/seed.sh (SPEC §4, §14): seed --base [--company CODE] runs the start +/// sequence without serving anything (migrations, first company), then adds the missing base data to one company or to +/// every active one, and prints what it added. Rows already there are never changed (ADR 0026). +/// +public static class SeedCommand +{ + /// The first argument that selects the command. + public const string Verb = "seed"; + + /// Exit code of a wrong command line. + public const int UsageError = 64; + + /// Whether the arguments ask for this command. + /// The arguments. + /// for seed .... + public static bool Matches(string[] args) => args is [Verb, ..]; + + /// Reads the options after the verb. + /// The arguments, verb included. + /// The company, or for every active one. + /// The problem, or . + /// when the line is valid. + public static bool TryParse(string[] args, out string? company, out string? error) + { + ArgumentNullException.ThrowIfNull(args); + company = null; + error = null; + var wantsBase = false; + for (var i = 1; i < args.Length; i++) + { + switch (args[i]) + { + case "--base": + wantsBase = true; + break; + case "--demo" or "--scale": + error = "seed --demo: i dati dimostrativi arrivano con anagrafiche e articoli (M4, issue #41 e #42)."; + return false; + case "--company" when i + 1 < args.Length && CompanyCodes.IsValid(CompanyCodes.Normalize(args[i + 1])): + company = CompanyCodes.Normalize(args[++i]); + break; + default: + error = "Argomento non valido: " + args[i]; + return false; + } + } + + if (!wantsBase) + { + error = "Uso: seed --base [--company CODICE]"; + } + + return error is null; + } + + /// Runs the command. + /// The arguments, verb included. + /// The exit code: 0 done, 1 failed, 64 wrong command line. + public static async Task RunAsync(string[] args) + { + if (!TryParse(args, out var company, out var error)) + { + await Console.Error.WriteLineAsync(error).ConfigureAwait(false); + return UsageError; + } + + // The configuration comes from the KHAEMHAT_* variables, as for the service; no web server is started. + var app = KhaemhatApp.Build([]); + await using (app.ConfigureAwait(false)) + { + var services = app.Services; + try + { + await services.GetRequiredService().RunAsync().ConfigureAwait(false); + var registry = services.GetRequiredService(); + IReadOnlyList codes = company is null + ? [.. (await registry.ListAsync().ConfigureAwait(false)).Where(c => c.Status == CompanyStatus.Active).Select(c => c.Code)] + : await registry.FindAsync(company).ConfigureAwait(false) is { } found ? [found.Code] : []; + if (codes.Count == 0) + { + await Console.Error.WriteLineAsync(company is null ? "Nessuna azienda attiva." : "Azienda sconosciuta: " + company).ConfigureAwait(false); + return 1; + } + + var runner = services.GetRequiredService(); + foreach (var code in codes) + { + var report = await runner.RunAsync(code, SeedKind.Base).ConfigureAwait(false); + Console.WriteLine(string.Create(CultureInfo.InvariantCulture, $"{code}: dati di base {report.DataVersion}, {report.Total} righe aggiunte.")); + foreach (var (table, count) in report.Added.Where(a => a.Value > 0).OrderBy(a => a.Key, StringComparer.Ordinal)) + { + Console.WriteLine(string.Create(CultureInfo.InvariantCulture, $" {table}: {count}")); + } + } + + return 0; + } + finally + { + await services.GetRequiredService().DisposeAsync().ConfigureAwait(false); + } + } + } +} diff --git a/src/Khaemhat.Web/Program.cs b/src/Khaemhat.Web/Program.cs index 9829d30..c5f4bdf 100644 --- a/src/Khaemhat.Web/Program.cs +++ b/src/Khaemhat.Web/Program.cs @@ -3,6 +3,12 @@ using Khaemhat.Web.Hosting; try { + // scripts/seed.sh: the base data from the command line, without serving anything. + if (SeedCommand.Matches(args)) + { + return await SeedCommand.RunAsync(args).ConfigureAwait(false); + } + await KhaemhatApp.Build(args).RunAsync().ConfigureAwait(false); } catch (ConfigurationException ex) diff --git a/src/Khaemhat.Web/Resources/it-IT/Shell.json b/src/Khaemhat.Web/Resources/it-IT/Shell.json index 5b92b22..b585b7c 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Shell.json +++ b/src/Khaemhat.Web/Resources/it-IT/Shell.json @@ -124,7 +124,11 @@ "Profile": "Profilo azienda", "FiscalYears": "Esercizi e periodi", "TaxCodes": "Codici IVA", - "Payments": "Pagamenti" + "Payments": "Pagamenti", + "Numerators": "Numeratori", + "Warehouses": "Depositi", + "Currencies": "Valute", + "ExchangeRates": "Cambi" }, "Automation": { "_": "Automazioni", diff --git a/src/Khaemhat.Web/Resources/it-IT/Tables.json b/src/Khaemhat.Web/Resources/it-IT/Tables.json new file mode 100644 index 0000000..5a9a810 --- /dev/null +++ b/src/Khaemhat.Web/Resources/it-IT/Tables.json @@ -0,0 +1,526 @@ +{ + "CompanyTables": { + "Modified": "Modificato", + "New": "Nuovo", + "NewRow": "Nuova riga", + "Undo": "Annulla modifiche", + "Delete": "Elimina", + "DeleteText": "Eliminare {0}? Se altri dati lo usano viene solo disattivato.", + "Deleted": "Riga eliminata", + "DisabledInstead": "Riga in uso: disattivata invece che eliminata", + "Export": "Esporta CSV", + "BaseData": "Aggiorna da tabelle base", + "BaseDataDone": "Aggiunte {0} righe mancanti (dati di base {1}). Le righe esistenti non sono state toccate.", + "Detail": "{0} · dettaglio", + "Saved": "Salvato", + "NotSaved": "Non salvato", + "FixFields": "Correggi i campi segnalati.", + "Concurrency": "Qualcun altro ha modificato la riga nel frattempo: ricarica e ripeti la modifica.", + "UnknownError": "Valore non valido.", + "Filter": { + "State": "Stato", + "All": "Tutti", + "Enabled": "Attivi", + "Disabled": "Disattivati" + }, + "Leave": { + "Title": "Modifiche non salvate", + "Text": "Le modifiche alla riga corrente andranno perse.", + "Confirm": "Abbandona le modifiche" + }, + "Import": { + "Title": "Importa CSV", + "Text": "Le righe con un codice già presente vengono aggiornate, le altre aggiunte. Se una riga ha un errore non viene importato nulla.", + "Columns": "Colonne riconosciute: {0}.", + "Choose": "Scegli il file", + "Done": "Importazione completata: {0} righe aggiunte, {1} aggiornate.", + "Refused": "Importazione annullata: {0} errori.", + "Error": "Riga {0}, campo {1}: {2}", + "TooLarge": "Il file supera i 20 MB." + }, + "Lines": { + "Title": "Rate", + "Add": "Aggiungi rata", + "Save": "Salva rate", + "Days": "Giorni", + "EndOfMonth": "Fine mese", + "FixedDay": "Giorno fisso", + "Percent": "% importo", + "Remove": "Togli la rata", + "Total": "Totale", + "Saved": "Rate salvate" + }, + "NoCompany": { + "Title": "Nessuna azienda aperta", + "Lead": "Le tabelle sono di un'azienda: scegline una dal selettore in alto." + }, + "Index": { + "Subtitle": "Dati dell'azienda e tabelle usate da anagrafiche, documenti e contabilità.", + "Company": "Azienda" + }, + "Groups": { + "Fiscal": "Fisco, pagamenti e banche", + "Sales": "Vendite e documenti", + "Logistics": "Magazzino e trasporto", + "Geography": "Geografia", + "Classification": "Classificazioni" + }, + "Profile": { + "Title": "Profilo azienda", + "Hint": "Dati societari, fiscali e di trasmissione delle fatture elettroniche.", + "YearsHint": "Gli esercizi e i periodi si gestiscono in", + "LogoHint": "Il logo per le stampe arriva con i modelli di stampa dei documenti.", + "Tabs": { + "societa": "Dati societari", + "fiscale": "Fiscale e SDI", + "banche": "Banche", + "stampa": "Logo e stampa", + "esercizi": "Esercizi e periodicità", + "trasmittente": "Trasmittente e intermediario" + }, + "Groups": { + "Company": "Società", + "Address": "Sede e contatti", + "Tax": "Fiscale", + "Bank": "Banca predefinita", + "Print": "Stampa", + "Vat": "Esercizio e IVA", + "Transmitter": "Trasmittente", + "Intermediary": "Intermediario" + } + }, + "FiscalYears": { + "Title": "Esercizi", + "Heading": "Esercizi e periodi contabili", + "Hint": "Anni contabili e mesi, con il blocco delle registrazioni.", + "New": "Nuovo esercizio", + "Years": "Esercizi", + "None": "Nessun esercizio: creane uno con Nuovo esercizio.", + "Year": "Esercizio", + "Start": "Inizio", + "End": "Fine", + "State": "Stato", + "LockedMonths": "Mesi bloccati", + "LastSettled": "Ultimo periodo IVA liquidato", + "Periods": "Periodi {0} · periodicità IVA {1}", + "PeriodsLabel": "Periodi", + "Period": "Periodo", + "From": "Dal", + "To": "Al", + "Lock": "Blocco", + "SettledLock": "Bloccato dalla liquidazione", + "Unlock": "Sblocca", + "LockMonth": "Blocca", + "UnlockText": "Sbloccare {0}? Si potranno di nuovo registrare documenti con quelle date.", + "Created": "Esercizio creato" + }, + "Rates": { + "Title": "Cambi", + "Hint": "Cambi di riferimento BCE, letti ogni giorno lavorativo, e cambi inseriti a mano.", + "Manual": "Cambio manuale", + "Save": "Salva il cambio", + "ManualHint": "I cambi manuali non vengono mai sovrascritti da quelli BCE." + }, + "Screens": { + "tax-codes": { + "Title": "Codici IVA", + "Hint": "Aliquote, nature dell'operazione, esigibilità e riferimenti normativi." + }, + "payment-methods": { + "Title": "Modalità di pagamento", + "Hint": "Bonifico, Ri.Ba., SDD e le altre, con il codice MP della fattura elettronica." + }, + "payment-terms": { + "Title": "Pagamenti", + "Hint": "Condizioni di pagamento con le rate: giorni, fine mese, giorno fisso." + }, + "bank-accounts": { + "Title": "Banche dell'azienda", + "Hint": "Conti correnti con IBAN, BIC, codici SIA e CUC." + }, + "currencies": { + "Title": "Valute", + "Hint": "Valute ISO 4217 con simbolo e decimali." + }, + "document-types": { + "Title": "Tipi documento", + "Hint": "Preventivi, ordini, DDT, fatture e note, con numeratore e tipo TD." + }, + "numerators": { + "Title": "Numeratori", + "Hint": "Numerazione per anno e sezionale, con il formato del numero." + }, + "price-lists": { + "Title": "Listini", + "Hint": "Testate dei listini: valuta, IVA inclusa, validità, ricarico." + }, + "discount-policies": { + "Title": "Sconti", + "Hint": "Formule di sconto in cascata, come 10+5." + }, + "salespeople": { + "Title": "Agenti", + "Hint": "Agenti e rappresentanti con provvigione ed Enasarco." + }, + "warehouses": { + "Title": "Depositi", + "Hint": "Magazzini e depositi dell'azienda." + }, + "inventory-reasons": { + "Title": "Causali di magazzino", + "Hint": "Carico, scarico, resi, trasferimenti, inventario." + }, + "units": { + "Title": "Unità di misura", + "Hint": "Unità con i decimali e il codice per la fattura elettronica." + }, + "carriers": { + "Title": "Vettori", + "Hint": "Trasportatori con partita IVA e albo." + }, + "shipping-terms": { + "Title": "Porto", + "Hint": "Franco, assegnato, franco con addebito." + }, + "transport-means": { + "Title": "Trasporto a cura", + "Hint": "Mittente, destinatario, vettore." + }, + "transport-reasons": { + "Title": "Causali di trasporto", + "Hint": "Vendita, conto visione, reso, riparazione." + }, + "goods-appearances": { + "Title": "Aspetto dei beni", + "Hint": "Cartoni, bancali, sfuso." + }, + "delivery-terms": { + "Title": "Rese", + "Hint": "Condizioni di resa Incoterms 2020." + }, + "countries": { + "Title": "Nazioni", + "Hint": "Paesi ISO 3166 con appartenenza UE, prefisso IVA e valuta." + }, + "provinces": { + "Title": "Province", + "Hint": "Sigle delle province con la regione." + }, + "municipalities": { + "Title": "Comuni", + "Hint": "Comuni con il codice catastale come codice, provincia, codice ISTAT e CAP." + }, + "item-categories": { + "Title": "Categorie articoli", + "Hint": "Fino a tre livelli di categoria." + }, + "party-categories": { + "Title": "Categorie soggetti", + "Hint": "Classi di clienti e fornitori." + }, + "cost-centers": { + "Title": "Centri di costo", + "Hint": "Centri di costo e di ricavo, anche gerarchici." + }, + "jobs": { + "Title": "Commesse", + "Hint": "Commesse e progetti con date e stato." + } + }, + "Fields": { + "Code": "Codice", + "Description": "Descrizione", + "Disabled": "Disattivato", + "Rate": "Aliquota", + "Nature": "Natura", + "Kind": "Tipo", + "Exigibility": "Esigibilità", + "NonDeductiblePercent": "% indetraibile", + "ValidFrom": "Valido dal", + "ValidTo": "Valido al", + "LegalReference": "Riferimento normativo", + "SalesAccountCode": "Conto vendite", + "PurchaseAccountCode": "Conto acquisti", + "EInvoiceCode": "Codice FE", + "NeedsBank": "Richiede banca", + "PaymentMethodId": "Modalità", + "Condition": "Condizione", + "VatOnFirstInstallment": "IVA sulla prima rata", + "BankName": "Banca", + "Iban": "IBAN", + "Bic": "BIC", + "SiaCode": "Codice SIA", + "CucCode": "Codice CUC", + "AccountCode": "Conto contabile", + "IsDefault": "Predefinito", + "Symbol": "Simbolo", + "Decimals": "Decimali", + "NumeratorId": "Numeratore", + "InventoryReasonId": "Causale di magazzino", + "EInvoiceType": "Tipo TD", + "VatRegisterCode": "Registro IVA", + "JournalTemplateCode": "Modello di prima nota", + "PrintTemplate": "Modello di stampa", + "Year": "Anno", + "Section": "Sezionale", + "Prefix": "Prefisso", + "Format": "Formato", + "LastNumber": "Ultimo numero", + "GapsAllowed": "Ammessi buchi di numerazione", + "CurrencyCode": "Valuta", + "VatIncluded": "IVA inclusa", + "BasePriceListId": "Listino base", + "MarkupPercent": "% ricarico", + "RoundingStep": "Arrotondamento", + "Formula": "Formula", + "Email": "Email", + "Phone": "Telefono", + "CommissionPercent": "% provvigione", + "Enasarco": "Enasarco", + "Address": "Indirizzo", + "City": "Città", + "ProvinceCode": "Provincia", + "Effect": "Effetto", + "AffectsValue": "Movimenta il valore", + "IsTransfer": "Trasferimento", + "VatNumber": "Partita IVA", + "RegisterNumber": "Iscrizione albo", + "Iso3": "ISO 3", + "VatPrefix": "Prefisso IVA", + "EuMember": "UE", + "Region": "Regione", + "IstatCode": "Codice ISTAT", + "PostalCodes": "CAP", + "ParentId": "Padre", + "Level": "Livello", + "Status": "Stato", + "StartDate": "Inizio", + "EndDate": "Fine", + "RateDate": "Data", + "Source": "Fonte", + "LegalName": "Ragione sociale", + "FiscalName": "Denominazione fiscale", + "ReaOffice": "Ufficio REA", + "ReaNumber": "Numero REA", + "ShareCapital": "Capitale sociale", + "Shareholders": "Soci", + "LiquidationStatus": "Stato di liquidazione", + "StreetNumber": "Civico", + "PostalCode": "CAP", + "AddressCountry": "Nazione", + "Pec": "PEC", + "Website": "Sito web", + "Country": "Paese fiscale", + "TaxCode": "Codice fiscale", + "TaxRegime": "Regime fiscale", + "RecipientCode": "Codice destinatario", + "DefaultBankAccountId": "Banca predefinita", + "FooterNotes": "Note a piè di pagina", + "FiscalYearStartMonth": "Mese di inizio esercizio", + "VatPeriodicity": "Periodicità IVA", + "ProRataPercent": "% pro rata", + "CashVat": "IVA per cassa", + "TransmitterCountry": "Paese trasmittente", + "TransmitterId": "Codice trasmittente", + "IntermediaryName": "Intermediario", + "IntermediaryTaxCode": "Codice fiscale intermediario" + }, + "Enums": { + "TaxCodeKind": { + "Taxable": "Imponibile", + "NonTaxable": "Non imponibile", + "Exempt": "Esente", + "Excluded": "Escluso", + "NotSubject": "Non soggetto", + "ReverseCharge": "Inversione contabile", + "Margin": "Regime del margine", + "OtherEuVat": "IVA di altro Stato UE" + }, + "TaxExigibility": { + "Immediate": "Immediata", + "Deferred": "Differita", + "SplitPayment": "Scissione dei pagamenti" + }, + "NumeratorKind": { + "Quotation": "Preventivi", + "SalesOrder": "Ordini clienti", + "DeliveryNote": "DDT", + "SalesInvoice": "Fatture di vendita", + "PurchaseOrder": "Ordini fornitori", + "PurchaseInvoice": "Fatture di acquisto", + "Inventory": "Movimenti di magazzino", + "Journal": "Prima nota", + "Other": "Altro" + }, + "StockEffect": { + "None": "Nessuno", + "Load": "Carico", + "Unload": "Scarico" + }, + "JobStatus": { + "Open": "Aperta", + "Suspended": "Sospesa", + "Closed": "Chiusa" + }, + "FiscalYearStatus": { + "Open": "Aperto", + "Closing": "In chiusura", + "Closed": "Chiuso" + }, + "FiscalPeriodStatus": { + "Open": "Aperto", + "Settled": "Liquidato", + "Locked": "Bloccato" + }, + "VatPeriodicity": { + "Monthly": "mensile", + "Quarterly": "trimestrale" + } + }, + "Values": { + "Shareholders": { + "SU": "Socio unico", + "SM": "Più soci" + }, + "LiquidationStatus": { + "LN": "Non in liquidazione", + "LS": "In liquidazione" + }, + "Source": { + "ECB": "BCE", + "MANUAL": "Manuale" + } + } + }, + "tables": { + "code": { + "required": "Il codice è obbligatorio.", + "too-long": "Il codice è troppo lungo.", + "duplicate": "Esiste già una riga con questo codice.", + "pattern": "Il codice non ha la forma attesa." + }, + "description": { + "required": "La descrizione è obbligatoria." + }, + "not-found": "La riga non esiste più.", + "csv": { + "no-code": "Manca la colonna code.", + "bad-value": "Valore non leggibile.", + "unknown-column": "Colonna sconosciuta." + }, + "percent": { + "range": "La percentuale deve essere tra 0 e 100." + }, + "validity": { + "order": "La fine della validità precede l'inizio." + }, + "code-list": { + "unknown": "Codice non previsto dalla tabella ufficiale.", + "obsolete": "Codice non più in vigore." + }, + "decimals": { + "range": "Numero di decimali fuori intervallo." + }, + "iban": { + "invalid": "IBAN non valido." + }, + "bic": { + "invalid": "BIC non valido." + }, + "email": { + "invalid": "Indirizzo email non valido." + }, + "vat-number": { + "invalid": "Partita IVA non valida." + }, + "parent": { + "invalid": "Il padre non può essere la riga stessa né un suo discendente, e i livelli sono al massimo tre." + }, + "reference": { + "missing": "Il valore collegato non esiste." + }, + "discount": { + "formula": "Formula di sconto non valida: usa percentuali tra 0 e 100 separate da +." + }, + "numerator": { + "format": "Il formato deve contenere il segnaposto del numero e solo segnaposto noti (anno, prefisso, sezionale)." + }, + "year": { + "range": "Anno fuori intervallo." + }, + "number": { + "range": "Numero fuori intervallo." + }, + "inventory-reason": { + "transfer": "Un trasferimento non ha effetto di carico o scarico." + }, + "exchange-rate": { + "invalid": "Il cambio deve essere maggiore di zero." + }, + "payment-term": { + "percent-total": "Le rate devono sommare il 100% e ognuna deve essere maggiore di zero.", + "lines-required": "Serve almeno una rata.", + "days": "I giorni vanno da 0 a 540.", + "fixed-day": "Il giorno fisso va da 1 a 31." + }, + "ecb-rates": "Cambi di riferimento BCE" + }, + "profile": { + "name": { + "required": "La ragione sociale è obbligatoria." + }, + "country": { + "unknown": "Paese senza pacchetto fiscale." + }, + "month": { + "range": "Il mese va da 1 a 12." + }, + "two-letters": "Servono due lettere.", + "tax-code": { + "invalid": "Codice fiscale non valido." + }, + "recipient-code": { + "invalid": "Codice destinatario non valido." + }, + "value": { + "invalid": "Valore non ammesso." + } + }, + "fiscal": { + "year": { + "overlap": "Le date si sovrappongono a un altro esercizio.", + "closed": "L'esercizio è chiuso." + }, + "period": { + "settled": "Il periodo è già liquidato: non si può sbloccare." + }, + "date": { + "open": "Data aperta.", + "no-year": "Nessun esercizio comprende questa data.", + "year-closed": "L'esercizio di questa data è chiuso.", + "locked": "Il periodo di questa data è bloccato.", + "settled": "Il periodo IVA di questa data è già liquidato." + }, + "tax": { + "rate-range": "L'aliquota deve essere tra 0 e 100.", + "rate-unusual": "Aliquota diversa da quelle in vigore in Italia.", + "nature-required": "Con aliquota zero la natura è obbligatoria.", + "nature-unknown": "Natura non prevista.", + "nature-obsolete": "Natura non più in vigore: usa un sottocodice.", + "nature-with-rate": "La natura si indica solo con aliquota zero.", + "legal-reference-missing": "Manca il riferimento normativo.", + "split-needs-rate": "La scissione dei pagamenti richiede un'aliquota.", + "reverse-charge-immediate": "L'inversione contabile ha esigibilità immediata.", + "non-deductible-range": "La percentuale indetraibile va da 0 a 100." + }, + "recipient": { + "required": "Il codice destinatario è obbligatorio.", + "characters": "Il codice destinatario ha caratteri non ammessi.", + "business-length": "Il codice destinatario di un'impresa ha 7 caratteri.", + "pa-length": "Il codice ufficio della PA ha 6 caratteri.", + "consumer": "Per un consumatore il codice è 0000000.", + "foreign": "Per un soggetto estero il codice è XXXXXXX.", + "foreign-code-domestic": "Il codice XXXXXXX è solo per soggetti esteri." + } + } +} diff --git a/src/Khaemhat.Web/Shell/MenuCatalog.cs b/src/Khaemhat.Web/Shell/MenuCatalog.cs index 4f4c2ba..38bcf34 100644 --- a/src/Khaemhat.Web/Shell/MenuCatalog.cs +++ b/src/Khaemhat.Web/Shell/MenuCatalog.cs @@ -87,9 +87,11 @@ public static class MenuCatalog ]), new("Shell.Menu.Section.System", [ - Area("Shell.Menu.CompanyTables", "layers", "/tabelle", ModuleCodes.Core, "company.settings.read", "M4", + Area("Shell.Menu.CompanyTables", "layers", "/tabelle", ModuleCodes.Core, "company.settings.read", null, ("Shell.Menu.CompanyTables.Profile", "profilo-azienda"), ("Shell.Menu.CompanyTables.FiscalYears", "esercizi"), - ("Shell.Menu.CompanyTables.TaxCodes", "codici-iva"), ("Shell.Menu.CompanyTables.Payments", "pagamenti")), + ("Shell.Menu.CompanyTables.TaxCodes", "codici-iva"), ("Shell.Menu.CompanyTables.Payments", "pagamenti"), + ("Shell.Menu.CompanyTables.Numerators", "numeratori"), ("Shell.Menu.CompanyTables.Warehouses", "depositi"), + ("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", diff --git a/src/Khaemhat.Web/Tables/ProfileLayout.cs b/src/Khaemhat.Web/Tables/ProfileLayout.cs new file mode 100644 index 0000000..5485e0a --- /dev/null +++ b/src/Khaemhat.Web/Tables/ProfileLayout.cs @@ -0,0 +1,111 @@ +using Khaemhat.Core.Tables; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Web.Tables; + +/// A group of fields of a tab of the company profile. +/// The text key of the title, under CompanyTables.Profile.Groups. +/// The icon. +/// The fields. +public sealed record ProfileGroup(string Key, string Icon, IReadOnlyList Fields); + +/// A tab of the company profile. +/// The id in the address (?scheda=fiscale). +/// The icon. +/// The groups. +public sealed record ProfileTab(string Id, string Icon, IReadOnlyList Groups); + +/// The tabs of the company profile (SPEC §11.1, mockup 075). +public static class ProfileLayout +{ + /// The tabs, in order. + public static IReadOnlyList Tabs { get; } = + [ + new("societa", "building", + [ + new("Company", "building", + [ + new(nameof(CompanyProfile.LegalName)) { Required = true, Span = 12, MaxLength = 200 }, + new(nameof(CompanyProfile.FiscalName)) { Span = 12, MaxLength = 200 }, + new(nameof(CompanyProfile.ReaOffice), TableFieldKind.Code) { MaxLength = 2, Span = 3 }, + new(nameof(CompanyProfile.ReaNumber), TableFieldKind.Code) { MaxLength = 20, Span = 3 }, + new(nameof(CompanyProfile.ShareCapital), TableFieldKind.Number) { Decimals = 2, Min = 0, Span = 6 }, + new(nameof(CompanyProfile.Shareholders), TableFieldKind.Choice) { Values = ["SU", "SM"] }, + new(nameof(CompanyProfile.LiquidationStatus), TableFieldKind.Choice) { Values = ["LN", "LS"] }, + ]), + new("Address", "pin", + [ + new(nameof(CompanyProfile.Address)) { Span = 9 }, + new(nameof(CompanyProfile.StreetNumber)) { Span = 3, MaxLength = 10 }, + new(nameof(CompanyProfile.PostalCode), TableFieldKind.Code) { Span = 3, MaxLength = 10 }, + new(nameof(CompanyProfile.City)) { Span = 6 }, + new(nameof(CompanyProfile.ProvinceCode), TableFieldKind.Code) { Span = 3, MaxLength = 2 }, + new(nameof(CompanyProfile.AddressCountry), TableFieldKind.Lookup) { Lookup = typeof(Country), ByCode = true }, + new(nameof(CompanyProfile.Phone)), + new(nameof(CompanyProfile.Email)), + new(nameof(CompanyProfile.Pec)), + new(nameof(CompanyProfile.Website)) { Span = 12 }, + ]), + ]), + new("fiscale", "file-check", + [ + new("Tax", "file-check", + [ + new(nameof(CompanyProfile.Country), TableFieldKind.Lookup) { Lookup = typeof(Country), ByCode = true, Required = true }, + new(nameof(CompanyProfile.CurrencyCode), TableFieldKind.Lookup) { Lookup = typeof(Currency), ByCode = true, Required = true }, + new(nameof(CompanyProfile.VatNumber), TableFieldKind.Code) { MaxLength = 30 }, + new(nameof(CompanyProfile.TaxCode), TableFieldKind.Code) { MaxLength = 16 }, + new(nameof(CompanyProfile.TaxRegime), TableFieldKind.CodeList) { CodeList = TaxRegimes, Required = true, Span = 12 }, + new(nameof(CompanyProfile.RecipientCode), TableFieldKind.Code) { MaxLength = 7 }, + ]), + ]), + new("banche", "coins", + [ + new("Bank", "coins", + [ + new(nameof(CompanyProfile.DefaultBankAccountId), TableFieldKind.Lookup) { Lookup = typeof(BankAccount), Span = 12 }, + ]), + ]), + new("stampa", "printer", + [ + new("Print", "printer", + [ + new(nameof(CompanyProfile.FooterNotes)) { Span = 12, Rows = 4, MaxLength = 1000 }, + ]), + ]), + new("esercizi", "calendar", + [ + new("Vat", "calendar", + [ + new(nameof(CompanyProfile.FiscalYearStartMonth), TableFieldKind.Number) { Min = 1, Max = 12, Required = true, Span = 4 }, + new(nameof(CompanyProfile.VatPeriodicity), TableFieldKind.Choice) { Span = 4 }, + new(nameof(CompanyProfile.ProRataPercent), TableFieldKind.Number) { Decimals = 2, Min = 0, Max = 100, Span = 4 }, + new(nameof(CompanyProfile.CashVat), TableFieldKind.Bool) { Span = 12 }, + ]), + ]), + new("trasmittente", "send", + [ + new("Transmitter", "send", + [ + new(nameof(CompanyProfile.TransmitterCountry), TableFieldKind.Code) { MaxLength = 2, Span = 3 }, + new(nameof(CompanyProfile.TransmitterId), TableFieldKind.Code) { MaxLength = 28, Span = 9 }, + ]), + new("Intermediary", "users", + [ + new(nameof(CompanyProfile.IntermediaryName)) { Span = 8 }, + new(nameof(CompanyProfile.IntermediaryTaxCode), TableFieldKind.Code) { MaxLength = 16, Span = 4 }, + ]), + ]), + ]; + + /// Every field, in order. + public static IEnumerable Fields => Tabs.SelectMany(t => t.Groups).SelectMany(g => g.Fields); + + /// The tab of a field, to show the one with an error. + /// The property. + /// The tab, or . + public static ProfileTab? TabOf(string? property) => + Tabs.FirstOrDefault(t => t.Groups.Any(g => g.Fields.Any(f => f.Property == property))); + + private static CodeList? TaxRegimes(IFiscalPack pack) => pack.GetFeature()?.TaxRegimes; +} diff --git a/src/Khaemhat.Web/Tables/TableOptions.cs b/src/Khaemhat.Web/Tables/TableOptions.cs new file mode 100644 index 0000000..b210303 --- /dev/null +++ b/src/Khaemhat.Web/Tables/TableOptions.cs @@ -0,0 +1,98 @@ +using System.Globalization; +using System.Reflection; +using Khaemhat.Application.Localization; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Entities; +using Khaemhat.Fiscal.Abstractions; +using Khaemhat.Web.Ui; + +namespace Khaemhat.Web.Tables; + +/// The choices of the fields of a page: rows of other tables, lists of the fiscal pack, enumerations, fixed values. +public sealed class TableOptions +{ + private readonly Dictionary>> _lookups = new(StringComparer.Ordinal); + + /// The fiscal pack of the company. + public IFiscalPack? Pack { get; private set; } + + /// Reads the pack of the company and the rows every lookup field points to. + /// The tables. + /// The fiscal context. + /// The fields. + /// Who reads. + /// The company. + /// Cancellation. + /// A task. + public async Task LoadAsync(TableService tables, CompanyFiscalContext fiscal, IEnumerable fields, Actor actor, string company, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(fiscal); + ArgumentNullException.ThrowIfNull(fields); + Pack = await fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false); + foreach (var field in fields.Where(f => f is { Kind: TableFieldKind.Lookup, Lookup: not null })) + { + var choices = await TableValues.LookupAsync(tables, field.Lookup!, field.ByCode, actor, company, cancellationToken).ConfigureAwait(false); + _lookups[field.Property] = [.. choices.Select(c => new KhOption(c.Value, c.Text))]; + } + } + + /// The choices of a field for a row. + /// The field. + /// Its property. + /// The row, to keep an obsolete code or leave out the row itself. + /// The texts. + /// The choices. + public IReadOnlyList> For(TableField field, PropertyInfo property, object? row, ITexts texts) + { + ArgumentNullException.ThrowIfNull(field); + ArgumentNullException.ThrowIfNull(property); + ArgumentNullException.ThrowIfNull(texts); + var current = row is null ? null : TableValues.GetText(row, property); + switch (field.Kind) + { + case TableFieldKind.Choice when field.Values is { } values: + return [.. values.Select(v => new KhOption(v, texts[ValueKey(field, v)]))]; + + case TableFieldKind.Choice: + return [.. TableValues.EnumChoices(property, v => texts[TableScreens.EnumKey(v)]).Select(c => new KhOption(c.Value, c.Text))]; + + case TableFieldKind.CodeList: + var list = Pack is null ? null : field.CodeList?.Invoke(Pack); + if (list is null) + { + return current is null ? [] : [new(current, current)]; + } + + return [.. list.Entries.Where(e => !e.Obsolete || e.Code == current).Select(e => new KhOption(e.Code, e.Code + " · " + e.Description))]; + + default: + var options = _lookups.GetValueOrDefault(field.Property) ?? []; + // A self reference never points to the row itself. + return field.Lookup == row?.GetType() && row is Entity { Id: > 0 } entity + ? [.. options.Where(o => o.Value != entity.Id.ToString(CultureInfo.InvariantCulture))] + : options; + } + } + + /// The code shown in the grid for the value of a lookup. + /// The field. + /// The stored value. + /// The code. + public string? CodeOf(TableField field, string? value) + { + ArgumentNullException.ThrowIfNull(field); + return value is null ? null : _lookups.GetValueOrDefault(field.Property)?.FirstOrDefault(o => o.Value == value)?.Text.Split(" · ")[0] ?? value; + } + + /// The text key of a fixed value: CompanyTables.Values.<Property>.<Value>. + /// The field. + /// The value. + /// The key. + public static string ValueKey(TableField field, string value) + { + ArgumentNullException.ThrowIfNull(field); + return "CompanyTables.Values." + field.Property + "." + value; + } +} diff --git a/src/Khaemhat.Web/Tables/TableScreens.cs b/src/Khaemhat.Web/Tables/TableScreens.cs new file mode 100644 index 0000000..818268b --- /dev/null +++ b/src/Khaemhat.Web/Tables/TableScreens.cs @@ -0,0 +1,359 @@ +using Khaemhat.Application.Tables; +using Khaemhat.Core.Tables; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Web.Tables; + +/// How a field of a company table is edited. +public enum TableFieldKind +{ + /// Free text. + Text = 0, + + /// A short code in monospace, upper case. + Code = 1, + + /// A number (decimal or integer property). + Number = 2, + + /// A yes/no flag. + Bool = 3, + + /// A date. + Date = 4, + + /// A value of an enumeration. + Choice = 5, + + /// A row of another company table, by id or by code. + Lookup = 6, + + /// A code of a list of the fiscal pack (payment methods of the e-invoice, VAT natures). + CodeList = 7, +} + +/// A field of the detail panel of a company table (mockup 076). +/// The property of the entity; its label is CompanyTables.Fields.<Property>. +/// How it is edited. +public sealed record TableField(string Property, TableFieldKind Kind = TableFieldKind.Text) +{ + /// The columns of the form it takes, out of 12. + public int Span { get; init; } = 6; + + /// The decimals of a number. + public int Decimals { get; init; } + + /// The smallest number. + public decimal? Min { get; init; } + + /// The largest number. + public decimal? Max { get; init; } + + /// The longest text. + public int? MaxLength { get; init; } + + /// Whether the field must be filled. + public bool Required { get; init; } + + /// The table a lookup points to. + public Type? Lookup { get; init; } + + /// Whether a lookup stores the code (a string property) instead of the id. + public bool ByCode { get; init; } + + /// The list of the fiscal pack a field takes its codes from. + public Func? CodeList { get; init; } + + /// Whether the field is also a column of the grid. + public bool InGrid { get; init; } + + /// The width of the grid column. + public string? Width { get; init; } + + /// Whether the value is computed and only shown. + public bool ReadOnly { get; init; } + + /// The fixed values of a on a text property; their texts are CompanyTables.Values.<Property>.<Value>. + public IReadOnlyList? Values { get; init; } + + /// The rows of a multi-line text. + public int Rows { get; init; } + + /// The text key of the label. + public string LabelKey => "CompanyTables.Fields." + Property; +} + +/// A company table as the interface shows it: address, icon, group and fields. +/// The last part of the address, such as codici-iva. +/// The key of the , such as tax-codes. +/// The entity. +/// The icon. +/// The group of the index page. +public sealed record TableScreen(string Slug, string Key, Type Entity, string Icon, TableGroup Group) +{ + /// The fields after code and description, in order. + public IReadOnlyList Fields { get; init; } = []; + + /// The address. + public string Href => TableScreens.BasePath + "/" + Slug; + + /// The text key of the title. + public string TitleKey => "CompanyTables.Screens." + Key + ".Title"; + + /// The text key of the one-line description. + public string HintKey => "CompanyTables.Screens." + Key + ".Hint"; +} + +/// The groups of the index page of the company tables. +public enum TableGroup +{ + /// VAT, payments, banks, currencies. + Fiscal = 0, + + /// Documents, numbering, price lists, discounts. + Sales = 1, + + /// Warehouses, reasons, units, transport. + Logistics = 2, + + /// Countries, provinces, municipalities. + Geography = 3, + + /// Categories, salespeople, cost centres, jobs. + Classification = 4, +} + +/// +/// The company tables of SPEC §11.1 with the fields of their detail panel. The page /tabelle/{slug} is generic +/// (KhTableEditor); the company profile, the fiscal years and the exchange rates have pages of their own. +/// +public static class TableScreens +{ + /// The address of the area. + public const string BasePath = "/tabelle"; + + /// Every screen, in the order of the index page. + public static IReadOnlyList All { get; } = + [ + new("codici-iva", "tax-codes", typeof(TaxCode), "euro", TableGroup.Fiscal) + { + Fields = + [ + new(nameof(TaxCode.Rate), TableFieldKind.Number) { Decimals = 2, Min = 0, Max = 100, InGrid = true, Width = "80px", Span = 3 }, + new(nameof(TaxCode.Nature), TableFieldKind.CodeList) { CodeList = p => p.TaxCodes.Natures, InGrid = true, Width = "90px", Span = 3 }, + new(nameof(TaxCode.Kind), TableFieldKind.Choice) { ReadOnly = true, InGrid = true, Width = "150px", Span = 3 }, + new(nameof(TaxCode.Exigibility), TableFieldKind.Choice) { Span = 3 }, + new(nameof(TaxCode.NonDeductiblePercent), TableFieldKind.Number) { Decimals = 2, Min = 0, Max = 100, Span = 3 }, + new(nameof(TaxCode.ValidFrom), TableFieldKind.Date) { Span = 3 }, + new(nameof(TaxCode.ValidTo), TableFieldKind.Date) { Span = 3 }, + new(nameof(TaxCode.LegalReference)) { Span = 12, InGrid = true }, + new(nameof(TaxCode.SalesAccountCode), TableFieldKind.Code), + new(nameof(TaxCode.PurchaseAccountCode), TableFieldKind.Code), + ], + }, + new("modalita-pagamento", "payment-methods", typeof(PaymentMethod), "coins", TableGroup.Fiscal) + { + Fields = + [ + new(nameof(PaymentMethod.EInvoiceCode), TableFieldKind.CodeList) { CodeList = EInvoice(f => f.PaymentMethods), Required = true, InGrid = true, Width = "90px" }, + new(nameof(PaymentMethod.NeedsBank), TableFieldKind.Bool) { InGrid = true, Width = "90px" }, + ], + }, + new("pagamenti", "payment-terms", typeof(PaymentTerm), "calendar", TableGroup.Fiscal) + { + Fields = + [ + new(nameof(PaymentTerm.PaymentMethodId), TableFieldKind.Lookup) { Lookup = typeof(PaymentMethod), InGrid = true, Width = "160px" }, + new(nameof(PaymentTerm.Condition), TableFieldKind.CodeList) { CodeList = EInvoice(f => f.PaymentConditions), Required = true, InGrid = true, Width = "90px" }, + new(nameof(PaymentTerm.VatOnFirstInstallment), TableFieldKind.Bool) { Span = 12 }, + ], + }, + new("banche", "bank-accounts", typeof(BankAccount), "building", TableGroup.Fiscal) + { + Fields = + [ + new(nameof(BankAccount.BankName)) { Span = 12, InGrid = true }, + new(nameof(BankAccount.Iban), TableFieldKind.Code) { Span = 8, MaxLength = 34, InGrid = true, Width = "260px" }, + new(nameof(BankAccount.Bic), TableFieldKind.Code) { Span = 4, MaxLength = 11 }, + new(nameof(BankAccount.SiaCode), TableFieldKind.Code) { Span = 4, MaxLength = 5 }, + new(nameof(BankAccount.CucCode), TableFieldKind.Code) { Span = 4, MaxLength = 8 }, + new(nameof(BankAccount.AccountCode), TableFieldKind.Code) { Span = 4 }, + new(nameof(BankAccount.IsDefault), TableFieldKind.Bool) { Span = 12, InGrid = true, Width = "90px" }, + ], + }, + new("valute", "currencies", typeof(Currency), "euro", TableGroup.Fiscal) + { + Fields = + [ + new(nameof(Currency.Symbol)) { MaxLength = 5, InGrid = true, Width = "80px", Span = 3 }, + new(nameof(Currency.Decimals), TableFieldKind.Number) { Min = 0, Max = 4, InGrid = true, Width = "80px", Span = 3 }, + ], + }, + new("tipi-documento", "document-types", typeof(DocumentType), "file", TableGroup.Sales) + { + Fields = + [ + new(nameof(DocumentType.Kind), TableFieldKind.Choice) { Required = true, InGrid = true, Width = "170px" }, + new(nameof(DocumentType.NumeratorId), TableFieldKind.Lookup) { Lookup = typeof(DocumentNumerator), InGrid = true, Width = "120px" }, + new(nameof(DocumentType.InventoryReasonId), TableFieldKind.Lookup) { Lookup = typeof(InventoryReason) }, + new(nameof(DocumentType.EInvoiceType), TableFieldKind.CodeList) { CodeList = EInvoice(f => f.DocumentTypes), InGrid = true, Width = "90px" }, + new(nameof(DocumentType.VatRegisterCode), TableFieldKind.Code) { Span = 4 }, + new(nameof(DocumentType.JournalTemplateCode), TableFieldKind.Code) { Span = 4 }, + new(nameof(DocumentType.PrintTemplate), TableFieldKind.Code) { Span = 4 }, + ], + }, + new("numeratori", "numerators", typeof(DocumentNumerator), "list", TableGroup.Sales) + { + Fields = + [ + new(nameof(DocumentNumerator.Year), TableFieldKind.Number) { Min = 2000, Max = 2100, Required = true, InGrid = true, Width = "70px", Span = 3 }, + new(nameof(DocumentNumerator.Kind), TableFieldKind.Choice) { Required = true, InGrid = true, Width = "170px", Span = 5 }, + new(nameof(DocumentNumerator.Section), TableFieldKind.Code) { MaxLength = 10, InGrid = true, Width = "80px", Span = 4 }, + new(nameof(DocumentNumerator.Prefix), TableFieldKind.Code) { MaxLength = 10, Span = 4 }, + new(nameof(DocumentNumerator.Format)) { Required = true, Span = 8, InGrid = true, Width = "180px" }, + new(nameof(DocumentNumerator.LastNumber), TableFieldKind.Number) { Min = 0, InGrid = true, Width = "100px", Span = 4 }, + new(nameof(DocumentNumerator.GapsAllowed), TableFieldKind.Bool) { Span = 8 }, + ], + }, + new("listini", "price-lists", typeof(PriceList), "tag", TableGroup.Sales) + { + Fields = + [ + new(nameof(PriceList.CurrencyCode), TableFieldKind.Lookup) { Lookup = typeof(Currency), ByCode = true, Required = true, InGrid = true, Width = "80px", Span = 4 }, + new(nameof(PriceList.VatIncluded), TableFieldKind.Bool) { InGrid = true, Width = "90px", Span = 8 }, + new(nameof(PriceList.ValidFrom), TableFieldKind.Date), + new(nameof(PriceList.ValidTo), TableFieldKind.Date), + new(nameof(PriceList.BasePriceListId), TableFieldKind.Lookup) { Lookup = typeof(PriceList) }, + new(nameof(PriceList.MarkupPercent), TableFieldKind.Number) { Decimals = 2, Span = 3 }, + new(nameof(PriceList.RoundingStep), TableFieldKind.Number) { Decimals = 4, Min = 0, Span = 3 }, + ], + }, + new("sconti", "discount-policies", typeof(DiscountPolicy), "tag", TableGroup.Sales) + { + Fields = [new(nameof(DiscountPolicy.Formula), TableFieldKind.Code) { Required = true, InGrid = true, Width = "140px" }], + }, + new("agenti", "salespeople", typeof(Salesperson), "user", TableGroup.Sales) + { + Fields = + [ + new(nameof(Salesperson.Email)) { InGrid = true }, + new(nameof(Salesperson.Phone)), + new(nameof(Salesperson.CommissionPercent), TableFieldKind.Number) { Decimals = 2, Min = 0, Max = 100, InGrid = true, Width = "90px" }, + new(nameof(Salesperson.Enasarco), TableFieldKind.Bool), + ], + }, + new("depositi", "warehouses", typeof(Warehouse), "box", TableGroup.Logistics) + { + Fields = + [ + new(nameof(Warehouse.Address)) { Span = 12 }, + new(nameof(Warehouse.City)) { Span = 8, InGrid = true }, + new(nameof(Warehouse.ProvinceCode), TableFieldKind.Code) { MaxLength = 2, Span = 4, InGrid = true, Width = "60px" }, + new(nameof(Warehouse.IsDefault), TableFieldKind.Bool) { Span = 12, InGrid = true, Width = "90px" }, + ], + }, + new("causali-magazzino", "inventory-reasons", typeof(InventoryReason), "activity", TableGroup.Logistics) + { + Fields = + [ + new(nameof(InventoryReason.Effect), TableFieldKind.Choice) { InGrid = true, Width = "110px", Span = 4 }, + new(nameof(InventoryReason.AffectsValue), TableFieldKind.Bool) { InGrid = true, Width = "90px", Span = 4 }, + new(nameof(InventoryReason.IsTransfer), TableFieldKind.Bool) { InGrid = true, Width = "90px", Span = 4 }, + ], + }, + new("unita-di-misura", "units", typeof(UnitOfMeasure), "grid", TableGroup.Logistics) + { + Fields = + [ + new(nameof(UnitOfMeasure.Decimals), TableFieldKind.Number) { Min = 0, Max = 6, InGrid = true, Width = "80px", Span = 3 }, + new(nameof(UnitOfMeasure.EInvoiceCode), TableFieldKind.Code) { MaxLength = 10, InGrid = true, Width = "100px", Span = 3 }, + ], + }, + new("vettori", "carriers", typeof(Carrier), "truck", TableGroup.Logistics) + { + Fields = + [ + new(nameof(Carrier.VatNumber), TableFieldKind.Code) { InGrid = true, Width = "130px" }, + new(nameof(Carrier.RegisterNumber), TableFieldKind.Code), + new(nameof(Carrier.Address)) { Span = 12 }, + new(nameof(Carrier.City)) { InGrid = true }, + new(nameof(Carrier.Phone)), + new(nameof(Carrier.Email)) { Span = 12 }, + ], + }, + new("porto", "shipping-terms", typeof(ShippingTerm), "truck", TableGroup.Logistics), + new("trasporto-a-cura", "transport-means", typeof(TransportMean), "truck", TableGroup.Logistics), + new("causali-trasporto", "transport-reasons", typeof(TransportReason), "truck", TableGroup.Logistics), + new("aspetto-beni", "goods-appearances", typeof(GoodsAppearance), "box", TableGroup.Logistics), + new("rese", "delivery-terms", typeof(DeliveryTerm), "globe", TableGroup.Logistics), + new("nazioni", "countries", typeof(Country), "globe", TableGroup.Geography) + { + Fields = + [ + new(nameof(Country.Iso3), TableFieldKind.Code) { MaxLength = 3, InGrid = true, Width = "70px", Span = 3 }, + new(nameof(Country.VatPrefix), TableFieldKind.Code) { MaxLength = 2, InGrid = true, Width = "80px", Span = 3 }, + new(nameof(Country.CurrencyCode), TableFieldKind.Lookup) { Lookup = typeof(Currency), ByCode = true, InGrid = true, Width = "80px", Span = 3 }, + new(nameof(Country.EuMember), TableFieldKind.Bool) { InGrid = true, Width = "70px", Span = 3 }, + ], + }, + new("province", "provinces", typeof(Province), "pin", TableGroup.Geography) + { + Fields = [new(nameof(Province.Region)) { InGrid = true }], + }, + new("comuni", "municipalities", typeof(Municipality), "pin", TableGroup.Geography) + { + Fields = + [ + new(nameof(Municipality.ProvinceCode), TableFieldKind.Code) { MaxLength = 2, Required = true, InGrid = true, Width = "60px", Span = 3 }, + new(nameof(Municipality.IstatCode), TableFieldKind.Code) { MaxLength = 6, InGrid = true, Width = "90px", Span = 3 }, + new(nameof(Municipality.Region)) { InGrid = true }, + new(nameof(Municipality.PostalCodes)) { Span = 12, InGrid = true, Width = "160px" }, + ], + }, + new("categorie-articoli", "item-categories", typeof(ItemCategory), "layers", TableGroup.Classification) + { + Fields = + [ + new(nameof(ItemCategory.ParentId), TableFieldKind.Lookup) { Lookup = typeof(ItemCategory), InGrid = true, Width = "140px" }, + new(nameof(ItemCategory.Level), TableFieldKind.Number) { ReadOnly = true, InGrid = true, Width = "70px", Span = 3 }, + ], + }, + new("categorie-soggetti", "party-categories", typeof(PartyCategory), "users", TableGroup.Classification), + new("centri-di-costo", "cost-centers", typeof(CostCenter), "target", TableGroup.Classification) + { + Fields = [new(nameof(CostCenter.ParentId), TableFieldKind.Lookup) { Lookup = typeof(CostCenter), InGrid = true, Width = "140px" }], + }, + new("commesse", "jobs", typeof(Job), "folder", TableGroup.Classification) + { + Fields = + [ + new(nameof(Job.Status), TableFieldKind.Choice) { InGrid = true, Width = "110px", Span = 4 }, + new(nameof(Job.StartDate), TableFieldKind.Date) { InGrid = true, Width = "100px", Span = 4 }, + new(nameof(Job.EndDate), TableFieldKind.Date) { Span = 4 }, + ], + }, + ]; + + /// The screen of an address. + /// The last part of the address. + /// The screen, or . + public static TableScreen? Find(string? slug) => + All.FirstOrDefault(s => string.Equals(s.Slug, slug, StringComparison.OrdinalIgnoreCase)); + + /// The screen of an entity. + /// The entity. + /// The screen, or . + public static TableScreen? Of(Type entity) => All.FirstOrDefault(s => s.Entity == entity); + + /// The text key of a value of an enumeration: CompanyTables.Enums.<Type>.<Value>. + /// The value. + /// The key. + public static string EnumKey(Enum value) + { + ArgumentNullException.ThrowIfNull(value); + return "CompanyTables.Enums." + value.GetType().Name + "." + value; + } + + private static Func EInvoice(Func list) => + pack => pack.GetFeature() is { } format ? list(format) : null; +} diff --git a/src/Khaemhat.Web/Tables/TableValues.cs b/src/Khaemhat.Web/Tables/TableValues.cs new file mode 100644 index 0000000..1b95b72 --- /dev/null +++ b/src/Khaemhat.Web/Tables/TableValues.cs @@ -0,0 +1,143 @@ +using System.Globalization; +using System.Reflection; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Tables; + +namespace Khaemhat.Web.Tables; + +/// A choice of a lookup or code list: the stored value and the text shown. +/// The value: the id or the code, as text. +/// The text, such as BB30 · Bonifico 30 gg. +public sealed record TableChoice(string Value, string Text); + +/// Reads and writes the fields of a company table row by name, converting between the editors and the properties. +public static class TableValues +{ + /// The property of a field. + /// The entity. + /// The field. + /// The property. + public static PropertyInfo PropertyOf(Type entity, TableField field) + { + ArgumentNullException.ThrowIfNull(entity); + ArgumentNullException.ThrowIfNull(field); + return entity.GetProperty(field.Property, BindingFlags.Public | BindingFlags.Instance) + ?? throw new InvalidOperationException($"{entity.Name} has no property {field.Property}."); + } + + /// The value as text (codes, lookups, choices). + /// The row. + /// The property. + /// The text, or . + public static string? GetText(object row, PropertyInfo property) => property.GetValue(row) switch + { + null => null, + string text => text, + long id => id.ToString(CultureInfo.InvariantCulture), + Enum value => value.ToString(), + IFormattable value => value.ToString(null, CultureInfo.InvariantCulture), + var value => value.ToString(), + }; + + /// Writes a text into a string, id or enumeration property; an empty text clears what can be cleared. + /// The row. + /// The property. + /// The text. + public static void SetText(object row, PropertyInfo property, string? text) + { + ArgumentNullException.ThrowIfNull(property); + var type = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType; + var empty = string.IsNullOrWhiteSpace(text); + object? value; + if (type == typeof(string)) + { + value = empty ? (IsNullable(property) ? null : string.Empty) : text!.Trim(); + } + else if (empty) + { + value = Nullable.GetUnderlyingType(property.PropertyType) is null ? Activator.CreateInstance(type) : null; + } + else if (type.IsEnum) + { + value = Enum.Parse(type, text!, ignoreCase: true); + } + else + { + value = Convert.ChangeType(text, type, CultureInfo.InvariantCulture); + } + + property.SetValue(row, value); + } + + /// The value of a number property. + /// The row. + /// The property. + /// The number, or . + public static decimal? GetNumber(object row, PropertyInfo property) => + property.GetValue(row) is { } value ? Convert.ToDecimal(value, CultureInfo.InvariantCulture) : null; + + /// Writes a number into a decimal, integer or long property; an empty value is zero unless it may be empty. + /// The row. + /// The property. + /// The number. + public static void SetNumber(object row, PropertyInfo property, decimal? number) + { + ArgumentNullException.ThrowIfNull(property); + var nullable = Nullable.GetUnderlyingType(property.PropertyType); + var type = nullable ?? property.PropertyType; + if (number is null) + { + property.SetValue(row, nullable is null ? Activator.CreateInstance(type) : null); + return; + } + + var value = type == typeof(decimal) ? number.Value : Math.Round(number.Value, MidpointRounding.AwayFromZero); + property.SetValue(row, Convert.ChangeType(value, type, CultureInfo.InvariantCulture)); + } + + /// The choices of an enumeration, with their texts. + /// The property. + /// The text of a value. + /// The choices. + public static IReadOnlyList EnumChoices(PropertyInfo property, Func text) + { + ArgumentNullException.ThrowIfNull(property); + ArgumentNullException.ThrowIfNull(text); + var type = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType; + return [.. Enum.GetValues(type).Cast().Select(v => new TableChoice(v.ToString(), text(v)))]; + } + + /// Reads the rows of a coded table, whatever its type, as choices. + /// The service. + /// The table. + /// Whether the value is the code instead of the id. + /// Who asks. + /// The company. + /// Cancellation. + /// The choices, enabled rows only. + public static async Task> LookupAsync(TableService tables, Type entity, bool byCode, Actor actor, string company, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(tables); + ArgumentNullException.ThrowIfNull(entity); + var method = typeof(TableService).GetMethod(nameof(TableService.ActiveAsync))!.MakeGenericMethod(entity); + var task = (Task)method.Invoke(tables, [actor, company, cancellationToken])!; + await task.ConfigureAwait(false); + var rows = (IEnumerable)task.GetType().GetProperty(nameof(Task.Result))!.GetValue(task)!; + return [.. rows.Select(r => new TableChoice(byCode ? r.Code : r.Id.ToString(CultureInfo.InvariantCulture), r.Code + " · " + r.Description))]; + } + + /// Splits the errors of a refused save (Field:code) into field and code. + /// The error. + /// The field (or ) and the code. + public static (string? Field, string Code) SplitError(string error) + { + ArgumentNullException.ThrowIfNull(error); + var colon = error.IndexOf(':', StringComparison.Ordinal); + return colon > 0 ? (error[..colon], error[(colon + 1)..]) : (null, error); + } + + private static bool IsNullable(PropertyInfo property) => + new NullabilityInfoContext().Create(property).WriteState == NullabilityState.Nullable; +} diff --git a/src/Khaemhat.Web/wwwroot/css/interactive.css b/src/Khaemhat.Web/wwwroot/css/interactive.css index 74cc9da..764da62 100644 --- a/src/Khaemhat.Web/wwwroot/css/interactive.css +++ b/src/Khaemhat.Web/wwwroot/css/interactive.css @@ -307,3 +307,21 @@ input.kh-cell.err { border-color: var(--kh-err); background: var(--kh-err-soft); .kh-linesbar .grow { flex: 1; } .kbdhint { display: inline-flex; gap: 3px; align-items: center; font: 10.5px var(--kh-mono); color: var(--kh-text-3); white-space: nowrap; } .kbdhint kbd { border: 1px solid var(--kh-border-strong); border-bottom-width: 2px; padding: 0 4px; border-radius: 3px; background: var(--kh-surface); font: inherit; color: var(--kh-text-2); } + +/* Company tables (mockup 076, 052, 075): grid on top, detail below. */ +.kh-tables { display: flex; flex-direction: column; gap: var(--kh-gap); padding-top: var(--kh-gap); } +.kh-tables .kh-warnings { list-style: none; margin: 0 var(--kh-pad, 14px) var(--kh-pad, 14px); padding: 8px 12px; } +.kh-tables .kh-warnings li { display: flex; gap: 6px; align-items: center; } +.kh-import-errors { max-height: 240px; overflow: auto; margin: 8px 0 0; padding-left: 18px; font-size: 12px; } +.kh-lines { width: 100%; border-collapse: collapse; } +.kh-lines th { text-align: left; font-weight: 500; color: var(--kh-text-2); font-size: 12px; padding: 6px 8px; border-bottom: 1px solid var(--kh-border); } +.kh-lines td { padding: 4px 8px; border-bottom: 1px solid var(--kh-border); vertical-align: middle; } +.kh-lines td.n, .kh-lines th.n { text-align: right; } +.kh-lines input.in { width: 100%; } +.kh-lines tfoot td { font-weight: 600; } +.kh-pad { padding: var(--kh-gap); } +.kh-table-index { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: var(--kh-gap); } +.kh-table-index a { display: flex; gap: 10px; align-items: flex-start; padding: 10px 12px; border: 1px solid var(--kh-border); border-radius: var(--kh-radius, 8px); color: inherit; text-decoration: none; background: var(--kh-surface); } +.kh-table-index a:hover { border-color: var(--kh-accent); } +.kh-table-index b { display: block; font-weight: 500; } +.kh-table-index small { color: var(--kh-text-3); } diff --git a/tests/Khaemhat.Web.Tests/Tables/CompanyTablesTests.cs b/tests/Khaemhat.Web.Tests/Tables/CompanyTablesTests.cs index 2583c97..39ae6c3 100644 --- a/tests/Khaemhat.Web.Tests/Tables/CompanyTablesTests.cs +++ b/tests/Khaemhat.Web.Tests/Tables/CompanyTablesTests.cs @@ -203,4 +203,30 @@ public sealed class CompanyTablesTests await app.StopAsync(); } } + + [TestMethod] + public async Task PaymentTermLines_AreReplacedTogether_OrNotAtAll() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var tables = app.Services.GetRequiredService(); + var terms = app.Services.GetRequiredService(); + var term = (await tables.AllAsync(Root, company)).Single(t => t.Code == "RB3060FM"); + Assert.HasCount(2, await terms.LinesAsync(Root, company, term.Id)); + + var saved = await terms.SaveLinesAsync(Root, company, term.Id, + [ + new() { Days = 30, EndOfMonth = true, Percent = 40m }, + new() { Days = 60, EndOfMonth = true, Percent = 30m }, + new() { Days = 90, EndOfMonth = true, Percent = 30m }, + ]); + CollectionAssert.AreEqual(new[] { 1, 2, 3 }, saved.Select(l => l.Number).ToArray()); + + var refused = await Assert.ThrowsExactlyAsync(() => + terms.SaveLinesAsync(Root, company, term.Id, [new() { Days = 30, Percent = 90m }])); + CollectionAssert.Contains(refused.Errors.ToList(), PaymentTermService.LinesField + ":" + PaymentTermService.PercentTotal); + Assert.HasCount(3, await terms.LinesAsync(Root, company, term.Id), "Nothing changed."); + } + } } diff --git a/tests/Khaemhat.Web.Tests/Tables/TableScreensTests.cs b/tests/Khaemhat.Web.Tests/Tables/TableScreensTests.cs new file mode 100644 index 0000000..2070887 --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Tables/TableScreensTests.cs @@ -0,0 +1,206 @@ +using System.Reflection; +using System.Text.RegularExpressions; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Tables; +using Khaemhat.Core.Tax; +using Khaemhat.Web.Components.Pages.Tables; +using Khaemhat.Web.Hosting; +using Khaemhat.Web.Tables; +using Khaemhat.Web.Tests.Shell; + +namespace Khaemhat.Web.Tests.Tables; + +/// The screens of the company tables (mockups 052, 075, 076): every table has one, every field and text exists. +[TestClass] +public sealed partial class TableScreensTests +{ + [TestMethod] + public void EveryTableOfTheCatalog_HasOneScreen_WithItsEntity() + { + var catalog = new TableCatalog(); + + CollectionAssert.AreEquivalent(catalog.All.Select(t => t.Key).ToList(), TableScreens.All.Select(s => s.Key).ToList()); + Assert.HasCount(TableScreens.All.Count, TableScreens.All.Select(s => s.Slug).Distinct().ToList(), "Unique addresses."); + foreach (var screen in TableScreens.All) + { + Assert.AreEqual(catalog.Find(screen.Key)!.EntityType, screen.Entity, screen.Key); + Assert.AreSame(screen, TableScreens.Find(screen.Slug.ToUpperInvariant())); + Assert.DoesNotContain(screen.Slug, TablesIndex.Pages.Select(p => p.Href).ToList(), "The special pages have their own address."); + } + } + + [TestMethod] + public void EveryField_IsAWritablePropertyOfTheRightKind() + { + foreach (var (entity, field) in TableScreens.All.SelectMany(s => s.Fields.Select(f => (s.Entity, f))) + .Concat(ProfileLayout.Fields.Select(f => (typeof(CompanyProfile), f)))) + { + var property = TableValues.PropertyOf(entity, field); + var type = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType; + var name = entity.Name + "." + field.Property; + Assert.IsTrue(property.CanWrite, name); + switch (field.Kind) + { + case TableFieldKind.Number: + Assert.IsTrue(type == typeof(decimal) || type == typeof(int) || type == typeof(long), name); + break; + case TableFieldKind.Bool: + Assert.AreEqual(typeof(bool), type, name); + break; + case TableFieldKind.Date: + Assert.AreEqual(typeof(DateOnly), type, name); + break; + case TableFieldKind.Choice: + Assert.IsTrue(type.IsEnum || (type == typeof(string) && field.Values is { Count: > 0 }), name); + break; + case TableFieldKind.Lookup: + Assert.IsTrue(field.Lookup is not null && typeof(CodedEntity).IsAssignableFrom(field.Lookup), name); + Assert.AreEqual(field.ByCode ? typeof(string) : typeof(long), type, name); + break; + case TableFieldKind.CodeList: + Assert.IsNotNull(field.CodeList, name); + Assert.AreEqual(typeof(string), type, name); + break; + default: + Assert.AreEqual(typeof(string), type, name); + break; + } + } + } + + [TestMethod] + public void CodeLists_ComeFromTheItalianPack() + { + var pack = new Fiscal.Italy.ItalyFiscalPack(); + foreach (var field in TableScreens.All.SelectMany(s => s.Fields).Concat(ProfileLayout.Fields).Where(f => f.Kind == TableFieldKind.CodeList)) + { + Assert.IsNotEmpty(field.CodeList!(pack)!.Entries, field.Property); + } + } + + [TestMethod] + public void EveryTextTheScreensBuild_Exists() + { + var keys = new List(); + keys.AddRange(TableScreens.All.SelectMany(s => new[] { s.TitleKey, s.HintKey })); + keys.AddRange(TableScreens.All.SelectMany(s => s.Fields).Concat(ProfileLayout.Fields).Select(f => f.LabelKey)); + keys.AddRange(new[] { "Code", "Description", "Disabled", "CurrencyCode", "RateDate", "Rate", "Source" }.Select(p => "CompanyTables.Fields." + p)); + keys.AddRange(Enum.GetValues().Select(g => "CompanyTables.Groups." + g)); + keys.AddRange(ProfileLayout.Tabs.Select(t => "CompanyTables.Profile.Tabs." + t.Id)); + keys.AddRange(ProfileLayout.Tabs.SelectMany(t => t.Groups).Select(g => "CompanyTables.Profile.Groups." + g.Key)); + keys.AddRange(TablesIndex.Pages.SelectMany(p => new[] { p.Title, p.Hint })); + foreach (var field in TableScreens.All.SelectMany(s => s.Fields).Concat(ProfileLayout.Fields)) + { + keys.AddRange((field.Values ?? []).Select(v => TableOptions.ValueKey(field, v))); + } + + var enums = TableScreens.All.SelectMany(s => s.Fields.Where(f => f.Kind == TableFieldKind.Choice).Select(f => TableValues.PropertyOf(s.Entity, f))) + .Concat(ProfileLayout.Fields.Where(f => f is { Kind: TableFieldKind.Choice, Values: null }).Select(f => TableValues.PropertyOf(typeof(CompanyProfile), f))) + .Select(p => Nullable.GetUnderlyingType(p.PropertyType) ?? p.PropertyType) + .Concat([typeof(FiscalYearStatus), typeof(FiscalPeriodStatus), typeof(VatPeriodicity)]) + .Distinct(); + keys.AddRange(enums.SelectMany(e => Enum.GetValues(e).Cast()).Select(TableScreens.EnumKey)); + keys.AddRange(new[] { ExchangeRateService.EcbSource, ExchangeRateService.ManualSource }.Select(s => "CompanyTables.Values.Source." + s)); + + Assert.IsEmpty(keys.Where(k => !ShellTests.Texts.Contains(k)).Distinct().ToList()); + } + + [TestMethod] + public void EveryErrorCode_HasAText() + { + var codes = new[] { typeof(TableService), typeof(TableCatalog), typeof(CompanyProfileService), typeof(FiscalYearService), typeof(PaymentTermService), typeof(ExchangeRateService) } + .SelectMany(t => t.GetFields(BindingFlags.Public | BindingFlags.Static).Where(f => f.IsLiteral && f.FieldType == typeof(string))) + .Select(f => (string)f.GetRawConstantValue()!) + .Where(c => c.StartsWith("tables.", StringComparison.Ordinal) || c.StartsWith("profile.", StringComparison.Ordinal) || c.StartsWith("fiscal.", StringComparison.Ordinal)) + .Where(c => !c.EndsWith('.')) + .Concat(Enum.GetValues().Select(FiscalYearService.ErrorOf)) + .ToList(); + // The problems of the Italian pack are literals in its sources. + foreach (var file in Directory.EnumerateFiles(Path.Combine(Repository.Root, "src", "Khaemhat.Fiscal.Italy"), "*.cs", SearchOption.AllDirectories) + .Where(f => !Repository.IsBuildOutput(f))) + { + codes.AddRange(FiscalCode().Matches(File.ReadAllText(file)).Select(m => m.Groups[1].Value)); + } + + Assert.IsGreaterThan(40, codes.Count); + Assert.IsEmpty(codes.Where(c => !ShellTests.Texts.Contains(c)).Distinct().ToList()); + } + + [TestMethod] + public void Values_AreConvertedBetweenEditorsAndProperties() + { + var term = new PaymentTerm(); + var method = TableValues.PropertyOf(typeof(PaymentTerm), new TableField(nameof(PaymentTerm.PaymentMethodId))); + TableValues.SetText(term, method, "42"); + Assert.AreEqual(42L, term.PaymentMethodId); + Assert.AreEqual("42", TableValues.GetText(term, method)); + TableValues.SetText(term, method, string.Empty); + Assert.IsNull(term.PaymentMethodId); + + var numerator = new DocumentNumerator(); + var kind = TableValues.PropertyOf(typeof(DocumentNumerator), new TableField(nameof(DocumentNumerator.Kind))); + TableValues.SetText(numerator, kind, "SalesInvoice"); + Assert.AreEqual(NumeratorKind.SalesInvoice, numerator.Kind); + var year = TableValues.PropertyOf(typeof(DocumentNumerator), new TableField(nameof(DocumentNumerator.Year))); + TableValues.SetNumber(numerator, year, 2026.4m); + Assert.AreEqual(2026, numerator.Year); + TableValues.SetNumber(numerator, year, null); + Assert.AreEqual(0, numerator.Year); + var section = TableValues.PropertyOf(typeof(DocumentNumerator), new TableField(nameof(DocumentNumerator.Section))); + TableValues.SetText(numerator, section, " "); + Assert.IsNull(numerator.Section, "An empty optional text is null."); + var format = TableValues.PropertyOf(typeof(DocumentNumerator), new TableField(nameof(DocumentNumerator.Format))); + TableValues.SetText(numerator, format, null); + Assert.AreEqual(string.Empty, numerator.Format, "A required text is never null."); + + Assert.AreEqual(("Iban", "tables.iban.invalid"), TableValues.SplitError("Iban:tables.iban.invalid")); + Assert.AreEqual(((string?)null, "fiscal.year.closed"), TableValues.SplitError("fiscal.year.closed")); + } + + [TestMethod] + public void PaymentTermLines_MustAddUpToTheWhole() + { + Assert.IsEmpty(PaymentTermService.Validate([Line(30, 50m), Line(60, 50m)])); + Assert.AreEqual(PaymentTermService.LinesRequired, PaymentTermService.Validate([]).Single().Code); + Assert.AreEqual(PaymentTermService.PercentTotal, PaymentTermService.Validate([Line(30, 50m), Line(60, 40m)]).Single().Code); + Assert.AreEqual(PaymentTermService.DaysRange, PaymentTermService.Validate([Line(-1, 100m)]).Single().Code); + Assert.AreEqual(PaymentTermService.FixedDayRange, PaymentTermService.Validate([new PaymentTermLine { Days = 30, Percent = 100m, FixedDay = 32 }]).Single().Code); + + static PaymentTermLine Line(int days, decimal percent) => new() { Days = days, Percent = percent }; + } + + [TestMethod] + public void Menu_LeadsToRealPages() + { + var area = Khaemhat.Web.Shell.MenuCatalog.FindArea("/tabelle")!; + + Assert.IsNull(area.Milestone, "Delivered in M4."); + foreach (var child in area.Children) + { + var slug = child.Href[(TableScreens.BasePath.Length + 1)..]; + Assert.IsTrue(TableScreens.Find(slug) is not null || TablesIndex.Pages.Any(p => p.Href == child.Href), child.Href); + Assert.IsTrue(ShellTests.Texts.Contains(child.Key), child.Key); + } + } + + [TestMethod] + public void SeedCommand_ReadsItsArguments() + { + Assert.IsTrue(SeedCommand.Matches(["seed", "--base"])); + Assert.IsFalse(SeedCommand.Matches(["--urls", "http://localhost:5080"])); + + Assert.IsTrue(SeedCommand.TryParse(["seed", "--base"], out var all, out _)); + Assert.IsNull(all, "Every active company."); + Assert.IsTrue(SeedCommand.TryParse(["seed", "--company", "demo", "--base"], out var one, out _)); + Assert.AreEqual("DEMO", one); + + Assert.IsFalse(SeedCommand.TryParse(["seed"], out _, out var usage)); + Assert.IsNotNull(usage); + Assert.IsFalse(SeedCommand.TryParse(["seed", "--demo"], out _, out _), "Demo data arrive with parties and items."); + Assert.IsFalse(SeedCommand.TryParse(["seed", "--base", "--company"], out _, out _)); + Assert.IsFalse(SeedCommand.TryParse(["seed", "--base", "--other"], out _, out _)); + } + + [GeneratedRegex("\"(fiscal\\.[a-z][a-z.\\-]*[a-z])\"")] + private static partial Regex FiscalCode(); +}