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/<slug>), 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 <noreply@anthropic.com>
This commit is contained in:
1 parent
34e196424f
commit
9bcf8c1082
33 files changed
+3272
-43
No files matched your search
@@ -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/<tabella>`: 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
|
||||
|
||||
|
||||
+2
-2
@@ -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" \
|
||||
|
||||
+4
-2
@@ -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
|
||||
|
||||
|
||||
+8
-5
@@ -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`,
|
||||
|
||||
@@ -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<T>` all'indirizzo `/tabelle/<slug>`. 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`.
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||

|
||||
*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
|
||||
|
||||
|
||||
+13
-6
@@ -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 "$@"
|
||||
@@ -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;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">Opens the company databases.</param>
|
||||
@@ -49,13 +51,16 @@ public sealed partial class CompanyProfileService
|
||||
/// <param name="audit">Writes the history.</param>
|
||||
/// <param name="fiscal">The fiscal pack of each company.</param>
|
||||
/// <param name="packs">The installed fiscal packs.</param>
|
||||
public CompanyProfileService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, CompanyFiscalContext fiscal, FiscalPackCatalog packs)
|
||||
/// <param name="companies">The registry, for the name of a company without a profile yet.</param>
|
||||
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<CompanyProfile> 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);
|
||||
}
|
||||
|
||||
/// <summary>Checks a profile without saving it.</summary>
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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%.
|
||||
/// </summary>
|
||||
public sealed class PaymentTermService
|
||||
{
|
||||
/// <summary>The installments do not add up to 100%.</summary>
|
||||
public const string PercentTotal = "tables.payment-term.percent-total";
|
||||
|
||||
/// <summary>A payment term needs at least one installment.</summary>
|
||||
public const string LinesRequired = "tables.payment-term.lines-required";
|
||||
|
||||
/// <summary>The days are negative or beyond a year and a half.</summary>
|
||||
public const string DaysRange = "tables.payment-term.days";
|
||||
|
||||
/// <summary>The fixed day is not a day of the month.</summary>
|
||||
public const string FixedDayRange = "tables.payment-term.fixed-day";
|
||||
|
||||
/// <summary>The field the errors of the installments are reported on.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
/// <param name="audit">The audit trail.</param>
|
||||
/// <param name="cache">The cache of the tables.</param>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The installments of a payment term, in order.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="paymentTermId">The payment term.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The installments.</returns>
|
||||
public async Task<IReadOnlyList<PaymentTermLine>> 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);
|
||||
}
|
||||
|
||||
/// <summary>Checks a set of installments.</summary>
|
||||
/// <param name="lines">The installments.</param>
|
||||
/// <returns>The errors, on <see cref="LinesField"/>.</returns>
|
||||
public static IReadOnlyList<TableProblem> Validate(IReadOnlyList<PaymentTermLine> lines)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(lines);
|
||||
var problems = new List<TableProblem>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Replaces the installments of a payment term, numbering them 1, 2, 3 in the given order.</summary>
|
||||
/// <param name="actor">Who saves.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="paymentTermId">The payment term.</param>
|
||||
/// <param name="lines">The installments.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The saved installments.</returns>
|
||||
/// <exception cref="ValidationFailedException">The installments are not valid (<c>Lines:code</c>).</exception>
|
||||
public async Task<IReadOnlyList<PaymentTermLine>> SaveLinesAsync(Actor actor, string companyCode, long paymentTermId, IReadOnlyList<PaymentTermLine> 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<PaymentTermLine> saved;
|
||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
_ = await uow.Repository<PaymentTerm, long>().GetAsync(paymentTermId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new KeyNotFoundException(TableService.NotFound);
|
||||
var repository = uow.Repository<PaymentTermLine, long>();
|
||||
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<IReadOnlyList<PaymentTermLine>> ReadAsync(IUnitOfWork uow, long paymentTermId, CancellationToken cancellationToken) =>
|
||||
(await uow.Repository<PaymentTermLine, long>()
|
||||
.ListAsync(Query.For<PaymentTermLine>().Where(x => x.PaymentTermId == paymentTermId).OrderBy(x => x.Number), cancellationToken)
|
||||
.ConfigureAwait(false)).Items;
|
||||
}
|
||||
@@ -10,7 +10,6 @@
|
||||
@page "/servizi/{*Rest}"
|
||||
@page "/canali/{*Rest}"
|
||||
@page "/report/{*Rest}"
|
||||
@page "/tabelle/{*Rest}"
|
||||
@page "/automazioni/{*Rest}"
|
||||
@page "/amministrazione/{*Rest}"
|
||||
@attribute [Authorize]
|
||||
|
||||
@@ -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. *@
|
||||
<KhPageTitle Text="@T["CompanyTables.Profile.Title"]" Icon="building" />
|
||||
|
||||
<TablesGuard>
|
||||
<div class="phead">
|
||||
<div>
|
||||
<div class="crumbs"><a href="@TableScreens.BasePath">@T["Shell.Menu.CompanyTables"]</a> / @T["CompanyTables.Profile.Title"]</div>
|
||||
<h1>@(_profile?.LegalName is { Length: > 0 } name ? name : T["CompanyTables.Profile.Title"])</h1>
|
||||
<div class="sub">@T["CompanyTables.Profile.Hint"]</div>
|
||||
</div>
|
||||
<div class="grow"></div>
|
||||
@if (_modified)
|
||||
{
|
||||
<KhBadge Tone="KhTone.Warning">@T["CompanyTables.Modified"]</KhBadge>
|
||||
}
|
||||
<div class="toolbar">
|
||||
<button type="button" class="btn" disabled="@(!_modified)" @onclick="UndoAsync"><KhIcon Name="undo" /> @T["CompanyTables.Undo"]</button>
|
||||
<button type="button" class="btn primary" disabled="@(!_modified || !CanWrite || _busy)" @onclick="SaveAsync"><KhIcon Name="save" /> @T["Common.Save"]</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (_profile is not null)
|
||||
{
|
||||
<section class="panel kh-tables-profile">
|
||||
<KhTabs Items="TabItems" Active="@_tab" ActiveChanged="t => _tab = t" Label="@T["CompanyTables.Profile.Title"]" />
|
||||
<KhForm Validation="_validation" ReadOnly="!CanWrite" Layout="KhFormLayout.Groups">
|
||||
@foreach (var group in ProfileLayout.Tabs.First(t => t.Id == _tab).Groups)
|
||||
{
|
||||
<KhFieldGroup Title="@T["CompanyTables.Profile.Groups." + group.Key]" Icon="@group.Icon">
|
||||
@foreach (var field in group.Fields)
|
||||
{
|
||||
<KhRowField Row="_profile" Field="field" Options="_options" ReadOnly="!CanWrite" OnChanged="() => _modified = true" />
|
||||
}
|
||||
</KhFieldGroup>
|
||||
}
|
||||
</KhForm>
|
||||
@if (_tab == "esercizi")
|
||||
{
|
||||
<p class="muted kh-pad"><KhIcon Name="info" /> @T["CompanyTables.Profile.YearsHint"] <a href="/tabelle/esercizi">@T["CompanyTables.FiscalYears.Title"]</a></p>
|
||||
}
|
||||
@if (_tab == "stampa")
|
||||
{
|
||||
<p class="muted kh-pad"><KhIcon Name="info" /> @T["CompanyTables.Profile.LogoHint"]</p>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
</TablesGuard>
|
||||
|
||||
@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<KhTabItem> 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)),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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. *@
|
||||
<KhPageTitle Text="@T["CompanyTables.Rates.Title"]" Icon="euro" />
|
||||
|
||||
<TablesGuard>
|
||||
<div class="phead">
|
||||
<div>
|
||||
<div class="crumbs"><a href="@TableScreens.BasePath">@T["Shell.Menu.CompanyTables"]</a> / @T["CompanyTables.Rates.Title"]</div>
|
||||
<h1>@T["CompanyTables.Rates.Title"]</h1>
|
||||
<div class="sub">@T["CompanyTables.Rates.Hint"]</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="kh-tables">
|
||||
<KhRadar TItem="ExchangeRate" @ref="_radar" Id="tables.exchange-rates" Columns="Columns" Source="ListAsync" KeyOf="r => r.Id" Selectable="false"
|
||||
QuickFilters="QuickFilters" ShowHints="false" Compact="true" Height="360px" ExportName="cambi" Label="@T["CompanyTables.Rates.Title"]" />
|
||||
|
||||
@if (CanWrite)
|
||||
{
|
||||
<KhPanel Title="@T["CompanyTables.Rates.Manual"]" Icon="edit">
|
||||
<KhForm Validation="_validation" Layout="KhFormLayout.Grid">
|
||||
<KhSelect TValue="string" Label="@T["CompanyTables.Fields.CurrencyCode"]" Name="CurrencyCode" Options="_currencies" @bind-Value="_currency" Required="true" Span="4" />
|
||||
<KhDateBox Label="@T["CompanyTables.Fields.RateDate"]" Name="RateDate" @bind-Value="_date" Required="true" Span="4" />
|
||||
<KhNumberBox Label="@T["CompanyTables.Fields.Rate"]" Name="Rate" @bind-Value="_rate" Decimals="6" Min="0" Required="true" Span="4" />
|
||||
</KhForm>
|
||||
<div class="kh-pad">
|
||||
<button type="button" class="btn primary" disabled="@_busy" @onclick="SaveAsync"><KhIcon Name="save" /> @T["CompanyTables.Rates.Save"]</button>
|
||||
<span class="muted sm">@T["CompanyTables.Rates.ManualHint"]</span>
|
||||
</div>
|
||||
</KhPanel>
|
||||
}
|
||||
</div>
|
||||
</TablesGuard>
|
||||
|
||||
@code {
|
||||
private readonly KhValidation _validation = new();
|
||||
private KhRadar<ExchangeRate>? _radar;
|
||||
private IReadOnlyList<KhOption<string>> _currencies = [];
|
||||
private string? _currency;
|
||||
private DateOnly? _date;
|
||||
private decimal? _rate;
|
||||
private bool _busy;
|
||||
|
||||
private bool CanWrite => Session.Permissions.Allows(TableService.WritePermission);
|
||||
|
||||
private IReadOnlyList<KhColumn<ExchangeRate>> 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<KhQuickFilter> 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"]),
|
||||
]),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
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<Currency>(actor, company);
|
||||
_currencies = [.. currencies.Where(c => c.Code != "EUR").Select(c => new KhOption<string>(c.Code, c.Code + " · " + c.Description))];
|
||||
}
|
||||
}
|
||||
|
||||
private Task<ListPage<ExchangeRate>> ListAsync(ListQuery query, CancellationToken cancellationToken) =>
|
||||
Session.Actor is { } actor && Session.Company?.Code is { } company
|
||||
? Rates.ListAsync(actor, company, query, cancellationToken)
|
||||
: Task.FromResult(new ListPage<ExchangeRate>([], 0, new Dictionary<string, decimal>()));
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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. *@
|
||||
<KhPageTitle Text="@T["CompanyTables.FiscalYears.Title"]" Icon="calendar" />
|
||||
|
||||
<TablesGuard>
|
||||
<div class="phead">
|
||||
<div>
|
||||
<div class="crumbs"><a href="@TableScreens.BasePath">@T["Shell.Menu.CompanyTables"]</a> / @T["CompanyTables.FiscalYears.Title"]</div>
|
||||
<h1>@T["CompanyTables.FiscalYears.Heading"]</h1>
|
||||
<div class="sub">@T["CompanyTables.FiscalYears.Hint"]</div>
|
||||
</div>
|
||||
<div class="grow"></div>
|
||||
<div class="toolbar">
|
||||
<button type="button" class="btn primary" disabled="@(!CanWrite || _busy)" @onclick="CreateAsync"><KhIcon Name="plus" /> @T["CompanyTables.FiscalYears.New"]</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="kh-tables">
|
||||
<KhPanel Title="@T["CompanyTables.FiscalYears.Years"]" Icon="calendar" Tight="true">
|
||||
@if (_years.Count == 0)
|
||||
{
|
||||
<p class="muted kh-pad">@T["CompanyTables.FiscalYears.None"]</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<table class="grid" aria-label="@T["CompanyTables.FiscalYears.Years"]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>@T["CompanyTables.FiscalYears.Year"]</th>
|
||||
<th>@T["CompanyTables.FiscalYears.Start"]</th>
|
||||
<th>@T["CompanyTables.FiscalYears.End"]</th>
|
||||
<th>@T["CompanyTables.FiscalYears.State"]</th>
|
||||
<th>@T["CompanyTables.FiscalYears.LockedMonths"]</th>
|
||||
<th>@T["CompanyTables.FiscalYears.LastSettled"]</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var view in _years)
|
||||
{
|
||||
var year = view.Year;
|
||||
<tr class="@(year.Id == _selected?.Year.Id ? "sel" : null)" @onclick="() => _selected = view" style="cursor:pointer">
|
||||
<td><b class="mono">@year.Code</b></td>
|
||||
<td>@T.Date(year.StartDate)</td>
|
||||
<td>@T.Date(year.EndDate)</td>
|
||||
<td><KhBadge Tone="ToneOf(year.Status)">@T[TableScreens.EnumKey(year.Status)]</KhBadge></td>
|
||||
<td>@view.Periods.Count(p => p.Status != FiscalPeriodStatus.Open) / @view.Periods.Count</td>
|
||||
<td>@(view.Periods.LastOrDefault(p => p.Status == FiscalPeriodStatus.Settled) is { } last ? MonthName(last) : "-")</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
}
|
||||
</KhPanel>
|
||||
|
||||
@if (_selected is { } selected)
|
||||
{
|
||||
<KhPanel Title="@T.Format("CompanyTables.FiscalYears.Periods", selected.Year.Code, T[TableScreens.EnumKey(_periodicity)])" Icon="lock" Tight="true">
|
||||
<table class="grid" aria-label="@T["CompanyTables.FiscalYears.PeriodsLabel"]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>@T["CompanyTables.FiscalYears.Period"]</th>
|
||||
<th>@T["CompanyTables.FiscalYears.From"]</th>
|
||||
<th>@T["CompanyTables.FiscalYears.To"]</th>
|
||||
<th>@T["CompanyTables.FiscalYears.State"]</th>
|
||||
<th>@T["CompanyTables.FiscalYears.Lock"]</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var period in selected.Periods)
|
||||
{
|
||||
<tr>
|
||||
<td>@MonthName(period)</td>
|
||||
<td>@T.Date(period.StartDate)</td>
|
||||
<td>@T.Date(period.EndDate)</td>
|
||||
<td><KhBadge Tone="ToneOf(period.Status)">@T[TableScreens.EnumKey(period.Status)]</KhBadge></td>
|
||||
<td>
|
||||
@if (period.Status == FiscalPeriodStatus.Settled)
|
||||
{
|
||||
<span class="muted">@T["CompanyTables.FiscalYears.SettledLock"]</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
var locked = period.Status == FiscalPeriodStatus.Locked;
|
||||
<button type="button" class="btn sm" disabled="@(!CanWrite || _busy || selected.Year.Status != FiscalYearStatus.Open)"
|
||||
@onclick="() => LockAsync(period, !locked)">
|
||||
<KhIcon Name="@(locked ? "key" : "lock")" /> @T[locked ? "CompanyTables.FiscalYears.Unlock" : "CompanyTables.FiscalYears.LockMonth"]
|
||||
</button>
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</KhPanel>
|
||||
}
|
||||
</div>
|
||||
</TablesGuard>
|
||||
|
||||
@code {
|
||||
private IReadOnlyList<FiscalYearView> _years = [];
|
||||
private FiscalYearView? _selected;
|
||||
private Khaemhat.Core.Tax.VatPeriodicity _periodicity;
|
||||
private bool _busy;
|
||||
|
||||
/// <summary>The service of the company profile, for the VAT periodicity shown on the months.</summary>
|
||||
[Inject]
|
||||
private CompanyProfileService Profiles { get; set; } = default!;
|
||||
|
||||
private bool CanWrite => Session.Permissions.Allows(TableService.WritePermission);
|
||||
|
||||
/// <inheritdoc />
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -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. *@
|
||||
<TablesGuard>
|
||||
@if (TableScreens.Find(Slug) is { } screen)
|
||||
{
|
||||
<DynamicComponent @key="screen.Slug" Type="EditorOf(screen)" Parameters="ParametersOf(screen)" />
|
||||
}
|
||||
else
|
||||
{
|
||||
<KhPageTitle Text="@T["Pages.NotFound.Title"]" Icon="layers" />
|
||||
<div class="kh-message">
|
||||
<KhIcon Name="layers" Class="lg" />
|
||||
<h1>@T["Pages.NotFound.Title"]</h1>
|
||||
<a class="btn" href="@TableScreens.BasePath">@T["Shell.Menu.CompanyTables"]</a>
|
||||
</div>
|
||||
}
|
||||
</TablesGuard>
|
||||
|
||||
@code {
|
||||
/// <summary>The last part of the address.</summary>
|
||||
[Parameter]
|
||||
public string? Slug { get; set; }
|
||||
|
||||
private static Type EditorOf(TableScreen screen) => typeof(KhTableEditor<>).MakeGenericType(screen.Entity);
|
||||
|
||||
private static Dictionary<string, object?> ParametersOf(TableScreen screen) => new() { ["Screen"] = screen };
|
||||
}
|
||||
@@ -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)
|
||||
{
|
||||
<p class="muted kh-pad">@T["Common.Loading"]</p>
|
||||
}
|
||||
else if (Session.Company is null)
|
||||
{
|
||||
<div class="kh-message">
|
||||
<KhIcon Name="building" Class="lg" />
|
||||
<h1>@T["CompanyTables.NoCompany.Title"]</h1>
|
||||
<p class="lead">@T["CompanyTables.NoCompany.Lead"]</p>
|
||||
</div>
|
||||
}
|
||||
else if (!Session.Permissions.Allows(Khaemhat.Application.Tables.TableService.ReadPermission))
|
||||
{
|
||||
<div class="kh-message">
|
||||
<KhIcon Name="lock" Class="lg" />
|
||||
<h1>@T["Pages.AccessDenied.Title"]</h1>
|
||||
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
|
||||
<a class="btn" href="./">@T["Common.BackHome"]</a>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
@ChildContent
|
||||
}
|
||||
|
||||
@code {
|
||||
private bool _loaded;
|
||||
|
||||
/// <summary>The page.</summary>
|
||||
[Parameter]
|
||||
public RenderFragment? ChildContent { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await Session.EnsureLoadedAsync();
|
||||
_loaded = true;
|
||||
}
|
||||
}
|
||||
@@ -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. *@
|
||||
<KhPageTitle Text="@T["Shell.Menu.CompanyTables"]" Icon="layers" />
|
||||
|
||||
<TablesGuard>
|
||||
<div class="phead">
|
||||
<div>
|
||||
<h1>@T["Shell.Menu.CompanyTables"]</h1>
|
||||
<div class="sub">@T["CompanyTables.Index.Subtitle"]</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="kh-tables">
|
||||
<KhPanel Title="@T["CompanyTables.Index.Company"]" Icon="building">
|
||||
<div class="kh-table-index kh-pad">
|
||||
@foreach (var (href, icon, title, hint) in Pages)
|
||||
{
|
||||
<a href="@href"><KhIcon Name="@icon" /><span><b>@T[title]</b><small>@T[hint]</small></span></a>
|
||||
}
|
||||
</div>
|
||||
</KhPanel>
|
||||
@foreach (var group in TableScreens.All.GroupBy(s => s.Group))
|
||||
{
|
||||
<KhPanel Title="@T["CompanyTables.Groups." + group.Key]" Icon="@group.First().Icon">
|
||||
<div class="kh-table-index kh-pad">
|
||||
@foreach (var screen in group)
|
||||
{
|
||||
<a href="@screen.Href"><KhIcon Name="@screen.Icon" /><span><b>@T[screen.TitleKey]</b><small>@T[screen.HintKey]</small></span></a>
|
||||
}
|
||||
</div>
|
||||
</KhPanel>
|
||||
}
|
||||
</div>
|
||||
</TablesGuard>
|
||||
|
||||
@code {
|
||||
/// <summary>The pages of the company that are not tables.</summary>
|
||||
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"),
|
||||
];
|
||||
}
|
||||
@@ -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%. *@
|
||||
<KhPanel Title="@T["CompanyTables.Lines.Title"]" Icon="calendar">
|
||||
<Actions>
|
||||
@if (!ReadOnly)
|
||||
{
|
||||
<button type="button" class="btn" @onclick="Add"><KhIcon Name="plus" /> @T["CompanyTables.Lines.Add"]</button>
|
||||
<button type="button" class="btn primary" disabled="@(!_modified || _busy)" @onclick="SaveAsync"><KhIcon Name="save" /> @T["CompanyTables.Lines.Save"]</button>
|
||||
}
|
||||
</Actions>
|
||||
<ChildContent>
|
||||
<table class="kh-lines" aria-label="@T["CompanyTables.Lines.Title"]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="n">#</th>
|
||||
<th class="n">@T["CompanyTables.Lines.Days"]</th>
|
||||
<th>@T["CompanyTables.Lines.EndOfMonth"]</th>
|
||||
<th class="n">@T["CompanyTables.Lines.FixedDay"]</th>
|
||||
<th class="n">@T["CompanyTables.Lines.Percent"]</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (var i = 0; i < _lines.Count; i++)
|
||||
{
|
||||
var line = _lines[i];
|
||||
var number = i + 1;
|
||||
<tr>
|
||||
<td class="n">@number</td>
|
||||
<td class="n">
|
||||
<input class="in num" inputmode="numeric" value="@line.Days" disabled="@ReadOnly" aria-label="@T["CompanyTables.Lines.Days"]"
|
||||
@onchange="e => Set(() => line.Days = Integer(e.Value) ?? 0)" />
|
||||
</td>
|
||||
<td>
|
||||
<input type="checkbox" checked="@line.EndOfMonth" disabled="@ReadOnly" aria-label="@T["CompanyTables.Lines.EndOfMonth"]"
|
||||
@onchange="e => Set(() => line.EndOfMonth = e.Value is true)" />
|
||||
</td>
|
||||
<td class="n">
|
||||
<input class="in num" inputmode="numeric" value="@line.FixedDay" disabled="@ReadOnly" aria-label="@T["CompanyTables.Lines.FixedDay"]"
|
||||
@onchange="e => Set(() => line.FixedDay = Integer(e.Value))" />
|
||||
</td>
|
||||
<td class="n">
|
||||
<input class="in num" inputmode="decimal" value="@ItalianNumber.Format(line.Percent, 2, Italian)" disabled="@ReadOnly"
|
||||
aria-label="@T["CompanyTables.Lines.Percent"]" @onchange="e => Set(() => line.Percent = Decimal(e.Value) ?? 0m)" />
|
||||
</td>
|
||||
<td>
|
||||
@if (!ReadOnly)
|
||||
{
|
||||
<KhIconButton Icon="trash" Text="@T["CompanyTables.Lines.Remove"]" Danger="true" OnClick="() => Remove(line)" />
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr>
|
||||
<td colspan="4">@T["CompanyTables.Lines.Total"]</td>
|
||||
<td class="n @(Total == 100m ? null : "err")">@ItalianNumber.Format(Total, 2, Italian)</td>
|
||||
<td></td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
@if (_error is not null)
|
||||
{
|
||||
<p class="err kh-pad">@_error</p>
|
||||
}
|
||||
</ChildContent>
|
||||
</KhPanel>
|
||||
|
||||
@code {
|
||||
private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT");
|
||||
|
||||
private List<PaymentTermLine> _lines = [];
|
||||
private bool _modified;
|
||||
private bool _busy;
|
||||
private string? _error;
|
||||
|
||||
/// <summary>The payment term.</summary>
|
||||
[Parameter, EditorRequired]
|
||||
public long PaymentTermId { get; set; }
|
||||
|
||||
/// <summary>Whether the installments can only be read.</summary>
|
||||
[Parameter]
|
||||
public bool ReadOnly { get; set; }
|
||||
|
||||
private decimal Total => _lines.Sum(l => l.Percent);
|
||||
|
||||
/// <inheritdoc />
|
||||
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;
|
||||
}
|
||||
@@ -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:
|
||||
<KhNumberBox Label="@Label" Name="@Field.Property" Value="TableValues.GetNumber(Row, Property)" Decimals="Field.Decimals" Min="Field.Min" Max="Field.Max"
|
||||
ValueChanged="v => ChangeAsync(() => TableValues.SetNumber(Row, Property, v))" Required="Field.Required" ReadOnly="IsReadOnly" Span="Field.Span" />
|
||||
break;
|
||||
case TableFieldKind.Bool:
|
||||
<KhCheck Label="@Label" Name="@Field.Property" Value="Property.GetValue(Row) is true"
|
||||
ValueChanged="v => ChangeAsync(() => Property.SetValue(Row, v))" ReadOnly="IsReadOnly" Span="Field.Span" />
|
||||
break;
|
||||
case TableFieldKind.Date:
|
||||
<KhDateBox Label="@Label" Name="@Field.Property" Value="(DateOnly?)Property.GetValue(Row)"
|
||||
ValueChanged="v => ChangeAsync(() => Property.SetValue(Row, v))" Required="Field.Required" ReadOnly="IsReadOnly" Span="Field.Span" />
|
||||
break;
|
||||
case TableFieldKind.Choice or TableFieldKind.Lookup or TableFieldKind.CodeList:
|
||||
<KhSelect TValue="string" Label="@Label" Name="@Field.Property" Value="TableValues.GetText(Row, Property)" Options="Options.For(Field, Property, Row, T)"
|
||||
Empty="@(Field.Required || (Field.Kind == TableFieldKind.Choice && Field.Values is null) ? null : string.Empty)"
|
||||
ValueChanged="v => ChangeAsync(() => TableValues.SetText(Row, Property, v))" Required="Field.Required" ReadOnly="IsReadOnly" Span="Field.Span" />
|
||||
break;
|
||||
default:
|
||||
if (Field.Rows > 1)
|
||||
{
|
||||
<KhTextArea Label="@Label" Name="@Field.Property" Value="@TableValues.GetText(Row, Property)" Rows="Field.Rows" MaxLength="Field.MaxLength"
|
||||
ValueChanged="v => ChangeAsync(() => TableValues.SetText(Row, Property, v))" Required="Field.Required" ReadOnly="IsReadOnly" Span="Field.Span" />
|
||||
}
|
||||
else
|
||||
{
|
||||
<KhTextBox Label="@Label" Name="@Field.Property" Value="@TableValues.GetText(Row, Property)" Mono="Field.Kind == TableFieldKind.Code" MaxLength="Field.MaxLength"
|
||||
ValueChanged="v => ChangeAsync(() => TableValues.SetText(Row, Property, Field.Kind == TableFieldKind.Code ? v?.ToUpperInvariant() : v))"
|
||||
Required="Field.Required" ReadOnly="IsReadOnly" Span="Field.Span" />
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
@code {
|
||||
/// <summary>The row.</summary>
|
||||
[Parameter, EditorRequired]
|
||||
public object Row { get; set; } = default!;
|
||||
|
||||
/// <summary>The field.</summary>
|
||||
[Parameter, EditorRequired]
|
||||
public TableField Field { get; set; } = default!;
|
||||
|
||||
/// <summary>The choices of the page.</summary>
|
||||
[Parameter, EditorRequired]
|
||||
public TableOptions Options { get; set; } = default!;
|
||||
|
||||
/// <summary>Whether the page cannot be changed.</summary>
|
||||
[Parameter]
|
||||
public bool ReadOnly { get; set; }
|
||||
|
||||
/// <summary>Called after every change.</summary>
|
||||
[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();
|
||||
}
|
||||
}
|
||||
@@ -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. *@
|
||||
<KhPageTitle Text="@T[Screen.TitleKey]" Icon="@Screen.Icon" />
|
||||
|
||||
<div class="phead">
|
||||
<div>
|
||||
<div class="crumbs"><a href="@TableScreens.BasePath">@T["Shell.Menu.CompanyTables"]</a> / @T[Screen.TitleKey]</div>
|
||||
<h1>@T[Screen.TitleKey]</h1>
|
||||
<div class="sub">@T[Screen.HintKey]</div>
|
||||
</div>
|
||||
<div class="grow"></div>
|
||||
@if (_modified)
|
||||
{
|
||||
<KhBadge Tone="KhTone.Warning">@T["CompanyTables.Modified"]</KhBadge>
|
||||
}
|
||||
</div>
|
||||
|
||||
<KhIconToolbar Items="ToolbarItems" Label="@T[Screen.TitleKey]" />
|
||||
|
||||
<div class="kh-tables">
|
||||
<KhRadar TItem="TRow" @ref="_radar" Id="@("tables." + Screen.Key)" Columns="Columns" Source="ListAsync" KeyOf="r => r.Id" Selectable="false"
|
||||
QuickFilters="QuickFilters" InitialFilters="EnabledOnly" OnCurrent="OpenAsync" OnOpen="OpenAsync" RowClass="DisabledClass"
|
||||
ShowHints="false" Compact="true" Height="320px" ExportName="@Screen.Slug" Label="@T[Screen.TitleKey]" />
|
||||
|
||||
@if (_row is not null)
|
||||
{
|
||||
<KhPanel Title="@DetailTitle" Icon="edit">
|
||||
<KhForm Validation="_validation" ReadOnly="!CanWrite" Layout="KhFormLayout.Grid">
|
||||
<KhTextBox Label="@T["CompanyTables.Fields.Code"]" Name="Code" Value="@_row.Code" ValueChanged="v => Change(() => _row.Code = v ?? string.Empty)"
|
||||
Required="true" Mono="true" MaxLength="Definition.CodeLength" Span="3" />
|
||||
<KhTextBox Label="@T["CompanyTables.Fields.Description"]" Name="Description" Value="@_row.Description"
|
||||
ValueChanged="v => Change(() => _row.Description = v ?? string.Empty)" Required="true" MaxLength="200" Span="7" />
|
||||
<KhCheck Label="@T["CompanyTables.Fields.Disabled"]" Name="Disabled" Value="_row.Disabled" ValueChanged="v => Change(() => _row.Disabled = v)" Span="2" />
|
||||
@foreach (var field in Screen.Fields)
|
||||
{
|
||||
<KhRowField Row="_row" Field="field" Options="_options" ReadOnly="!CanWrite" OnChanged="() => _modified = true" />
|
||||
}
|
||||
</KhForm>
|
||||
@if (_warnings.Count > 0)
|
||||
{
|
||||
<ul class="callout warn kh-warnings">
|
||||
@foreach (var warning in _warnings)
|
||||
{
|
||||
<li><KhIcon Name="alert" /> @warning</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
</KhPanel>
|
||||
|
||||
@if (_row is PaymentTerm { Id: > 0 } term)
|
||||
{
|
||||
<KhPaymentTermLines @key="term.Id" PaymentTermId="term.Id" ReadOnly="!CanWrite" />
|
||||
}
|
||||
}
|
||||
</div>
|
||||
|
||||
<KhDialog Open="_importOpen" Title="@T["CompanyTables.Import.Title"]" Icon="upload" OnClose="CloseImport">
|
||||
<ChildContent>
|
||||
<p>@T["CompanyTables.Import.Text"]</p>
|
||||
<p class="muted sm">@T.Format("CompanyTables.Import.Columns", string.Join(", ", Definition.CsvColumns.Select(c => c.Header)))</p>
|
||||
<label class="btn primary @(_busy ? "disabled" : null)">
|
||||
<KhIcon Name="upload" /> @T["CompanyTables.Import.Choose"]
|
||||
<InputFile OnChange="ImportAsync" accept=".csv,text/csv" disabled="@_busy" />
|
||||
</label>
|
||||
@if (_import is { } result)
|
||||
{
|
||||
@if (result.Succeeded)
|
||||
{
|
||||
<p class="ok">@T.Format("CompanyTables.Import.Done", result.Inserted, result.Updated)</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p class="err">@T.Format("CompanyTables.Import.Refused", result.Errors.Count)</p>
|
||||
<ul class="kh-import-errors">
|
||||
@foreach (var error in result.Errors.Take(50))
|
||||
{
|
||||
<li>@T.Format("CompanyTables.Import.Error", error.Row, error.Field ?? "-", ErrorText(error.Code))</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
}
|
||||
</ChildContent>
|
||||
<Footer>
|
||||
<button type="button" class="btn" @onclick="CloseImport">@T["Common.Close"]</button>
|
||||
</Footer>
|
||||
</KhDialog>
|
||||
|
||||
@code {
|
||||
private const long MaxImportBytes = 20L * 1024 * 1024;
|
||||
|
||||
private readonly KhValidation _validation = new();
|
||||
private readonly TableOptions _options = new();
|
||||
private KhRadar<TRow>? _radar;
|
||||
private TRow? _row;
|
||||
private TRow? _saved;
|
||||
private bool _modified;
|
||||
private bool _busy;
|
||||
private bool _importOpen;
|
||||
private TableImportResult? _import;
|
||||
private List<string> _warnings = [];
|
||||
private IReadOnlyList<KhColumn<TRow>>? _columns;
|
||||
|
||||
/// <summary>The table.</summary>
|
||||
[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<ListFilter> EnabledOnly => [new("disabled", ListFilterOperator.Equals, ["false"])];
|
||||
|
||||
private IReadOnlyList<KhQuickFilter> 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<KhColumn<TRow>> 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<ToolbarItem> 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 },
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await Session.EnsureLoadedAsync();
|
||||
if (Company is { } company)
|
||||
{
|
||||
await LoadOptionsAsync(company);
|
||||
}
|
||||
}
|
||||
|
||||
private KhColumn<TRow> 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<ListPage<TRow>> ListAsync(ListQuery query, CancellationToken cancellationToken) =>
|
||||
Session.Actor is { } actor && Company is { } company
|
||||
? Tables.ListAsync<TRow>(actor, company, query, cancellationToken)
|
||||
: Task.FromResult(new ListPage<TRow>([], 0, new Dictionary<string, decimal>()));
|
||||
|
||||
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<bool> 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<TRow>(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<TRow>(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<TRow>(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;
|
||||
}
|
||||
}
|
||||
@@ -141,6 +141,7 @@ internal static class KhaemhatServices
|
||||
services.AddSingleton<TableService>();
|
||||
services.AddSingleton<CompanyProfileService>();
|
||||
services.AddSingleton<FiscalYearService>();
|
||||
services.AddSingleton<PaymentTermService>();
|
||||
services.AddSingleton<ExchangeRateService>();
|
||||
services.AddHttpClient<EcbRatesClient>(c => c.Timeout = TimeSpan.FromSeconds(30));
|
||||
services.AddHttpClient<ViesClient>(c => c.Timeout = TimeSpan.FromSeconds(20));
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// The command line of <c>scripts/seed.sh</c> (SPEC §4, §14): <c>seed --base [--company CODE]</c> 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).
|
||||
/// </summary>
|
||||
public static class SeedCommand
|
||||
{
|
||||
/// <summary>The first argument that selects the command.</summary>
|
||||
public const string Verb = "seed";
|
||||
|
||||
/// <summary>Exit code of a wrong command line.</summary>
|
||||
public const int UsageError = 64;
|
||||
|
||||
/// <summary>Whether the arguments ask for this command.</summary>
|
||||
/// <param name="args">The arguments.</param>
|
||||
/// <returns><see langword="true"/> for <c>seed ...</c>.</returns>
|
||||
public static bool Matches(string[] args) => args is [Verb, ..];
|
||||
|
||||
/// <summary>Reads the options after the verb.</summary>
|
||||
/// <param name="args">The arguments, verb included.</param>
|
||||
/// <param name="company">The company, or <see langword="null"/> for every active one.</param>
|
||||
/// <param name="error">The problem, or <see langword="null"/>.</param>
|
||||
/// <returns><see langword="true"/> when the line is valid.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Runs the command.</summary>
|
||||
/// <param name="args">The arguments, verb included.</param>
|
||||
/// <returns>The exit code: 0 done, 1 failed, 64 wrong command line.</returns>
|
||||
public static async Task<int> 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<StartupOrchestrator>().RunAsync().ConfigureAwait(false);
|
||||
var registry = services.GetRequiredService<ICompanyRegistry>();
|
||||
IReadOnlyList<string> 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<SeedRunner>();
|
||||
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<DbLogSink>().DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Web.Tables;
|
||||
|
||||
/// <summary>A group of fields of a tab of the company profile.</summary>
|
||||
/// <param name="Key">The text key of the title, under <c>CompanyTables.Profile.Groups</c>.</param>
|
||||
/// <param name="Icon">The icon.</param>
|
||||
/// <param name="Fields">The fields.</param>
|
||||
public sealed record ProfileGroup(string Key, string Icon, IReadOnlyList<TableField> Fields);
|
||||
|
||||
/// <summary>A tab of the company profile.</summary>
|
||||
/// <param name="Id">The id in the address (<c>?scheda=fiscale</c>).</param>
|
||||
/// <param name="Icon">The icon.</param>
|
||||
/// <param name="Groups">The groups.</param>
|
||||
public sealed record ProfileTab(string Id, string Icon, IReadOnlyList<ProfileGroup> Groups);
|
||||
|
||||
/// <summary>The tabs of the company profile (SPEC §11.1, mockup 075).</summary>
|
||||
public static class ProfileLayout
|
||||
{
|
||||
/// <summary>The tabs, in order.</summary>
|
||||
public static IReadOnlyList<ProfileTab> 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 },
|
||||
]),
|
||||
]),
|
||||
];
|
||||
|
||||
/// <summary>Every field, in order.</summary>
|
||||
public static IEnumerable<TableField> Fields => Tabs.SelectMany(t => t.Groups).SelectMany(g => g.Fields);
|
||||
|
||||
/// <summary>The tab of a field, to show the one with an error.</summary>
|
||||
/// <param name="property">The property.</param>
|
||||
/// <returns>The tab, or <see langword="null"/>.</returns>
|
||||
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<IEInvoiceFormat>()?.TaxRegimes;
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>The choices of the fields of a page: rows of other tables, lists of the fiscal pack, enumerations, fixed values.</summary>
|
||||
public sealed class TableOptions
|
||||
{
|
||||
private readonly Dictionary<string, IReadOnlyList<KhOption<string>>> _lookups = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>The fiscal pack of the company.</summary>
|
||||
public IFiscalPack? Pack { get; private set; }
|
||||
|
||||
/// <summary>Reads the pack of the company and the rows every lookup field points to.</summary>
|
||||
/// <param name="tables">The tables.</param>
|
||||
/// <param name="fiscal">The fiscal context.</param>
|
||||
/// <param name="fields">The fields.</param>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="company">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task LoadAsync(TableService tables, CompanyFiscalContext fiscal, IEnumerable<TableField> 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<string>(c.Value, c.Text))];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The choices of a field for a row.</summary>
|
||||
/// <param name="field">The field.</param>
|
||||
/// <param name="property">Its property.</param>
|
||||
/// <param name="row">The row, to keep an obsolete code or leave out the row itself.</param>
|
||||
/// <param name="texts">The texts.</param>
|
||||
/// <returns>The choices.</returns>
|
||||
public IReadOnlyList<KhOption<string>> 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<string>(v, texts[ValueKey(field, v)]))];
|
||||
|
||||
case TableFieldKind.Choice:
|
||||
return [.. TableValues.EnumChoices(property, v => texts[TableScreens.EnumKey(v)]).Select(c => new KhOption<string>(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<string>(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<long> { Id: > 0 } entity
|
||||
? [.. options.Where(o => o.Value != entity.Id.ToString(CultureInfo.InvariantCulture))]
|
||||
: options;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The code shown in the grid for the value of a lookup.</summary>
|
||||
/// <param name="field">The field.</param>
|
||||
/// <param name="value">The stored value.</param>
|
||||
/// <returns>The code.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The text key of a fixed value: <c>CompanyTables.Values.<Property>.<Value></c>.</summary>
|
||||
/// <param name="field">The field.</param>
|
||||
/// <param name="value">The value.</param>
|
||||
/// <returns>The key.</returns>
|
||||
public static string ValueKey(TableField field, string value)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(field);
|
||||
return "CompanyTables.Values." + field.Property + "." + value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Web.Tables;
|
||||
|
||||
/// <summary>How a field of a company table is edited.</summary>
|
||||
public enum TableFieldKind
|
||||
{
|
||||
/// <summary>Free text.</summary>
|
||||
Text = 0,
|
||||
|
||||
/// <summary>A short code in monospace, upper case.</summary>
|
||||
Code = 1,
|
||||
|
||||
/// <summary>A number (decimal or integer property).</summary>
|
||||
Number = 2,
|
||||
|
||||
/// <summary>A yes/no flag.</summary>
|
||||
Bool = 3,
|
||||
|
||||
/// <summary>A date.</summary>
|
||||
Date = 4,
|
||||
|
||||
/// <summary>A value of an enumeration.</summary>
|
||||
Choice = 5,
|
||||
|
||||
/// <summary>A row of another company table, by id or by code.</summary>
|
||||
Lookup = 6,
|
||||
|
||||
/// <summary>A code of a list of the fiscal pack (payment methods of the e-invoice, VAT natures).</summary>
|
||||
CodeList = 7,
|
||||
}
|
||||
|
||||
/// <summary>A field of the detail panel of a company table (mockup 076).</summary>
|
||||
/// <param name="Property">The property of the entity; its label is <c>CompanyTables.Fields.<Property></c>.</param>
|
||||
/// <param name="Kind">How it is edited.</param>
|
||||
public sealed record TableField(string Property, TableFieldKind Kind = TableFieldKind.Text)
|
||||
{
|
||||
/// <summary>The columns of the form it takes, out of 12.</summary>
|
||||
public int Span { get; init; } = 6;
|
||||
|
||||
/// <summary>The decimals of a number.</summary>
|
||||
public int Decimals { get; init; }
|
||||
|
||||
/// <summary>The smallest number.</summary>
|
||||
public decimal? Min { get; init; }
|
||||
|
||||
/// <summary>The largest number.</summary>
|
||||
public decimal? Max { get; init; }
|
||||
|
||||
/// <summary>The longest text.</summary>
|
||||
public int? MaxLength { get; init; }
|
||||
|
||||
/// <summary>Whether the field must be filled.</summary>
|
||||
public bool Required { get; init; }
|
||||
|
||||
/// <summary>The table a lookup points to.</summary>
|
||||
public Type? Lookup { get; init; }
|
||||
|
||||
/// <summary>Whether a lookup stores the code (a string property) instead of the id.</summary>
|
||||
public bool ByCode { get; init; }
|
||||
|
||||
/// <summary>The list of the fiscal pack a <see cref="TableFieldKind.CodeList"/> field takes its codes from.</summary>
|
||||
public Func<IFiscalPack, CodeList?>? CodeList { get; init; }
|
||||
|
||||
/// <summary>Whether the field is also a column of the grid.</summary>
|
||||
public bool InGrid { get; init; }
|
||||
|
||||
/// <summary>The width of the grid column.</summary>
|
||||
public string? Width { get; init; }
|
||||
|
||||
/// <summary>Whether the value is computed and only shown.</summary>
|
||||
public bool ReadOnly { get; init; }
|
||||
|
||||
/// <summary>The fixed values of a <see cref="TableFieldKind.Choice"/> on a text property; their texts are <c>CompanyTables.Values.<Property>.<Value></c>.</summary>
|
||||
public IReadOnlyList<string>? Values { get; init; }
|
||||
|
||||
/// <summary>The rows of a multi-line text.</summary>
|
||||
public int Rows { get; init; }
|
||||
|
||||
/// <summary>The text key of the label.</summary>
|
||||
public string LabelKey => "CompanyTables.Fields." + Property;
|
||||
}
|
||||
|
||||
/// <summary>A company table as the interface shows it: address, icon, group and fields.</summary>
|
||||
/// <param name="Slug">The last part of the address, such as <c>codici-iva</c>.</param>
|
||||
/// <param name="Key">The key of the <see cref="TableDefinition"/>, such as <c>tax-codes</c>.</param>
|
||||
/// <param name="Entity">The entity.</param>
|
||||
/// <param name="Icon">The icon.</param>
|
||||
/// <param name="Group">The group of the index page.</param>
|
||||
public sealed record TableScreen(string Slug, string Key, Type Entity, string Icon, TableGroup Group)
|
||||
{
|
||||
/// <summary>The fields after code and description, in order.</summary>
|
||||
public IReadOnlyList<TableField> Fields { get; init; } = [];
|
||||
|
||||
/// <summary>The address.</summary>
|
||||
public string Href => TableScreens.BasePath + "/" + Slug;
|
||||
|
||||
/// <summary>The text key of the title.</summary>
|
||||
public string TitleKey => "CompanyTables.Screens." + Key + ".Title";
|
||||
|
||||
/// <summary>The text key of the one-line description.</summary>
|
||||
public string HintKey => "CompanyTables.Screens." + Key + ".Hint";
|
||||
}
|
||||
|
||||
/// <summary>The groups of the index page of the company tables.</summary>
|
||||
public enum TableGroup
|
||||
{
|
||||
/// <summary>VAT, payments, banks, currencies.</summary>
|
||||
Fiscal = 0,
|
||||
|
||||
/// <summary>Documents, numbering, price lists, discounts.</summary>
|
||||
Sales = 1,
|
||||
|
||||
/// <summary>Warehouses, reasons, units, transport.</summary>
|
||||
Logistics = 2,
|
||||
|
||||
/// <summary>Countries, provinces, municipalities.</summary>
|
||||
Geography = 3,
|
||||
|
||||
/// <summary>Categories, salespeople, cost centres, jobs.</summary>
|
||||
Classification = 4,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The company tables of SPEC §11.1 with the fields of their detail panel. The page <c>/tabelle/{slug}</c> is generic
|
||||
/// (<c>KhTableEditor</c>); the company profile, the fiscal years and the exchange rates have pages of their own.
|
||||
/// </summary>
|
||||
public static class TableScreens
|
||||
{
|
||||
/// <summary>The address of the area.</summary>
|
||||
public const string BasePath = "/tabelle";
|
||||
|
||||
/// <summary>Every screen, in the order of the index page.</summary>
|
||||
public static IReadOnlyList<TableScreen> 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 },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
/// <summary>The screen of an address.</summary>
|
||||
/// <param name="slug">The last part of the address.</param>
|
||||
/// <returns>The screen, or <see langword="null"/>.</returns>
|
||||
public static TableScreen? Find(string? slug) =>
|
||||
All.FirstOrDefault(s => string.Equals(s.Slug, slug, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
/// <summary>The screen of an entity.</summary>
|
||||
/// <param name="entity">The entity.</param>
|
||||
/// <returns>The screen, or <see langword="null"/>.</returns>
|
||||
public static TableScreen? Of(Type entity) => All.FirstOrDefault(s => s.Entity == entity);
|
||||
|
||||
/// <summary>The text key of a value of an enumeration: <c>CompanyTables.Enums.<Type>.<Value></c>.</summary>
|
||||
/// <param name="value">The value.</param>
|
||||
/// <returns>The key.</returns>
|
||||
public static string EnumKey(Enum value)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(value);
|
||||
return "CompanyTables.Enums." + value.GetType().Name + "." + value;
|
||||
}
|
||||
|
||||
private static Func<IFiscalPack, CodeList?> EInvoice(Func<IEInvoiceFormat, CodeList> list) =>
|
||||
pack => pack.GetFeature<IEInvoiceFormat>() is { } format ? list(format) : null;
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>A choice of a lookup or code list: the stored value and the text shown.</summary>
|
||||
/// <param name="Value">The value: the id or the code, as text.</param>
|
||||
/// <param name="Text">The text, such as <c>BB30 · Bonifico 30 gg</c>.</param>
|
||||
public sealed record TableChoice(string Value, string Text);
|
||||
|
||||
/// <summary>Reads and writes the fields of a company table row by name, converting between the editors and the properties.</summary>
|
||||
public static class TableValues
|
||||
{
|
||||
/// <summary>The property of a field.</summary>
|
||||
/// <param name="entity">The entity.</param>
|
||||
/// <param name="field">The field.</param>
|
||||
/// <returns>The property.</returns>
|
||||
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}.");
|
||||
}
|
||||
|
||||
/// <summary>The value as text (codes, lookups, choices).</summary>
|
||||
/// <param name="row">The row.</param>
|
||||
/// <param name="property">The property.</param>
|
||||
/// <returns>The text, or <see langword="null"/>.</returns>
|
||||
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(),
|
||||
};
|
||||
|
||||
/// <summary>Writes a text into a string, id or enumeration property; an empty text clears what can be cleared.</summary>
|
||||
/// <param name="row">The row.</param>
|
||||
/// <param name="property">The property.</param>
|
||||
/// <param name="text">The text.</param>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>The value of a number property.</summary>
|
||||
/// <param name="row">The row.</param>
|
||||
/// <param name="property">The property.</param>
|
||||
/// <returns>The number, or <see langword="null"/>.</returns>
|
||||
public static decimal? GetNumber(object row, PropertyInfo property) =>
|
||||
property.GetValue(row) is { } value ? Convert.ToDecimal(value, CultureInfo.InvariantCulture) : null;
|
||||
|
||||
/// <summary>Writes a number into a decimal, integer or long property; an empty value is zero unless it may be empty.</summary>
|
||||
/// <param name="row">The row.</param>
|
||||
/// <param name="property">The property.</param>
|
||||
/// <param name="number">The number.</param>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>The choices of an enumeration, with their texts.</summary>
|
||||
/// <param name="property">The property.</param>
|
||||
/// <param name="text">The text of a value.</param>
|
||||
/// <returns>The choices.</returns>
|
||||
public static IReadOnlyList<TableChoice> EnumChoices(PropertyInfo property, Func<Enum, string> text)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(property);
|
||||
ArgumentNullException.ThrowIfNull(text);
|
||||
var type = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
|
||||
return [.. Enum.GetValues(type).Cast<Enum>().Select(v => new TableChoice(v.ToString(), text(v)))];
|
||||
}
|
||||
|
||||
/// <summary>Reads the rows of a coded table, whatever its type, as choices.</summary>
|
||||
/// <param name="tables">The service.</param>
|
||||
/// <param name="entity">The table.</param>
|
||||
/// <param name="byCode">Whether the value is the code instead of the id.</param>
|
||||
/// <param name="actor">Who asks.</param>
|
||||
/// <param name="company">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The choices, enabled rows only.</returns>
|
||||
public static async Task<IReadOnlyList<TableChoice>> 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<ICodedRecord>)task.GetType().GetProperty(nameof(Task<object>.Result))!.GetValue(task)!;
|
||||
return [.. rows.Select(r => new TableChoice(byCode ? r.Code : r.Id.ToString(CultureInfo.InvariantCulture), r.Code + " · " + r.Description))];
|
||||
}
|
||||
|
||||
/// <summary>Splits the errors of a refused save (<c>Field:code</c>) into field and code.</summary>
|
||||
/// <param name="error">The error.</param>
|
||||
/// <returns>The field (or <see langword="null"/>) and the code.</returns>
|
||||
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;
|
||||
}
|
||||
@@ -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); }
|
||||
@@ -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<TableService>();
|
||||
var terms = app.Services.GetRequiredService<PaymentTermService>();
|
||||
var term = (await tables.AllAsync<PaymentTerm>(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<ValidationFailedException>(() =>
|
||||
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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>The screens of the company tables (mockups 052, 075, 076): every table has one, every field and text exists.</summary>
|
||||
[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<string>();
|
||||
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<TableGroup>().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<Enum>()).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<PeriodState>().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();
|
||||
}
|
||||
Reference in new issue
Block a user