Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e53b14a3c5 | ||
|
|
b323d70f83 | ||
|
|
caa33a2cee | ||
|
|
3dbbaba86e | ||
|
|
c8241a414e | ||
|
|
3401271483 | ||
|
|
a9eda510f2 | ||
|
|
321aae7e81 | ||
|
|
07555de700 | ||
|
|
9bcf8c1082 | ||
|
|
34e196424f | ||
|
|
25f8a7ad30 | ||
|
|
49d2bb166b | ||
|
|
8079d3da69 | ||
|
|
f7c9cf6da8 | ||
|
|
4ecf15b609 | ||
|
|
b4a2802bed | ||
|
|
8198e0a754 | ||
|
|
f415dc37a8 | ||
|
|
acb7e598d1 | ||
|
|
75d60ee4c4 | ||
|
|
d0f9d0e651 | ||
|
|
d958e7372d | ||
|
|
b341ade9e9 | ||
|
|
cf6f849cc1 |
No files matched your search
@@ -10,6 +10,10 @@
|
||||
.data/
|
||||
out/
|
||||
docs/
|
||||
# ...except the copy of the wiki and the images it shows, shipped as the in-app help (ADR 0023).
|
||||
!docs/wiki/
|
||||
!docs/mockups/thumbs/
|
||||
!docs/mockups/png/
|
||||
deploy/
|
||||
*.md
|
||||
!README.md
|
||||
|
||||
@@ -7,6 +7,169 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.4.0] - 2026-11-12
|
||||
|
||||
M4 — Tabelle, anagrafiche, articoli. Il pacchetto fiscale italiano, il profilo e le tabelle dell'azienda con i dati
|
||||
di base (province, comuni e CAP compresi), clienti, fornitori e contatti, articoli e listini, i codici automatici,
|
||||
l'import/export guidato e i dati di esempio: le prime maschere gestionali vere.
|
||||
|
||||
### Added
|
||||
- Pacchetto fiscale (ADR 0025): `IFiscalPack` con codici IVA, motore delle imposte e calendario fiscale, più funzioni
|
||||
facoltative per paese; `FiscalPackCatalog` sceglie il pacchetto dal paese dell'azienda. Il pacchetto italiano
|
||||
(`IT 2026.2`) porta nature IVA N1-N7, codici IVA di base, code list FatturaPA (specifiche **1.9.1**: TD, MP, TP,
|
||||
RF, ritenute, casse previdenziali), castelletto IVA con arrotondamento sul totale per aliquota, regola del bollo,
|
||||
scadenze IVA mensili e trimestrali con slittamenti di agosto e dei festivi, ritenute, regole di base dei cespiti e
|
||||
codici tributo F24.
|
||||
- Controlli degli identificativi: IBAN (mod 97 e lunghezza per paese), codici a barre EAN/GTIN, e-mail; partita IVA
|
||||
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.3`).
|
||||
- Province e comuni dall'elenco ISTAT dei codici dei comuni al 26/02/2026 (ADR 0028, CC BY 4.0): 110 province e
|
||||
7.894 comuni con codice catastale, provincia, regione e codice ISTAT, nei dati di base del pacchetto italiano
|
||||
(`IT 2026.3`), con i CAP di GeoNames (CC BY 4.0) per 7.750 comuni; i mancanti si completano nella tabella
|
||||
*Comuni*. `tools/Khaemhat.PlacesTool` rigenera i due elenchi dai file scaricati.
|
||||
- `scripts/seed.sh --base [--company CODICE]`, incluso nell'immagine in `/app/scripts/`.
|
||||
- Codici automatici (ADR 0027): maschere per clienti, fornitori, lead, articoli, cespiti, opportunità, ticket,
|
||||
contratti e interventi con `{seq:0000}`, `{anno}` e `{categoria}`, anteprima del prossimo codice, codice manuale
|
||||
ammesso o no, progressivi in `code_sequences` assegnati nella transazione del salvataggio (nessun doppione, nessun
|
||||
numero perso se il salvataggio fallisce, codici già presenti saltati).
|
||||
- Compilazione automatica: comune, provincia e regione dal CAP e CAP dal comune, codice fiscale, verifica VIES, ABI,
|
||||
CAB, banca e BIC dall'IBAN, data di consegna sul calendario lavorativo; ogni opzione si spegne nelle preferenze, e
|
||||
il job dei cambi BCE salta le aziende che l'hanno spento. Pagina *Preferenze azienda* (`/tabelle/preferenze`).
|
||||
- Anagrafiche (ADR 0029): clienti, fornitori, prospect e lead in un solo archivio, con tre radar
|
||||
(`/anagrafiche/clienti`, `/fornitori`, `/contatti`) con ricerca, filtri rapidi, disattivazione e riattivazione di
|
||||
più righe, e la scheda a otto schede: dati principali, indirizzi, contatti, condizioni di vendita e di acquisto,
|
||||
fiscale e SDI (fatturazione elettronica, regime IVA, ritenute e casse, dichiarazione d'intento), banche, note e
|
||||
allegati, storico. Controlli del pacchetto fiscale su partita IVA, codice fiscale, codice destinatario e paese, con
|
||||
avvisi che non bloccano (P.IVA doppia, privato senza codice fiscale); codice destinatario proposto per privati ed
|
||||
esteri; verifica VIES al salvataggio e su richiesta; calcolo del codice fiscale; CAP e comune compilati a vicenda.
|
||||
*Converti in cliente* per prospect e lead (nuovo codice, il vecchio resta come codice precedente) e per i fornitori
|
||||
(diventano anche clienti con lo stesso codice). Un'anagrafica usata da altri dati si disattiva invece di cancellarsi.
|
||||
- Dati di esempio delle anagrafiche con `KHAEMHAT_SEED_DEMO=true`: 3 agenti, 12 clienti di ogni tipo soggetto,
|
||||
5 fornitori, 2 prospect e 2 lead, con numeri inventati ma formalmente validi.
|
||||
- Articoli (ADR 0030): radar `/anagrafiche/articoli` con ricerca anche per codice a barre, filtri per tipo,
|
||||
categoria, magazzino e stato, disattivazione e riattivazione; scheda con dati principali, UM alternative, codici
|
||||
alternativi, listini e prezzi netti dei clienti, fornitori con il fornitore abituale, sostitutivi, note e allegati,
|
||||
storico. Codice dalla maschera per categoria, verifica EAN con duplicati bloccati o segnalati secondo le
|
||||
preferenze, NC8, solo le merci a magazzino; costi visibili solo con `items.cost.read` e conservati per chi non li
|
||||
vede; un articolo usato si disattiva invece di cancellarsi.
|
||||
- Listini (ADR 0030): prezzi con data di validità e storico, listino base, listini derivati con ricarico e
|
||||
arrotondamento, griglia `/anagrafiche/listini` articoli x listini con modifica in cella, prezzi netti di un
|
||||
cliente, margine e aggiornamento massivo con anteprima; ricerca del prezzo per i documenti (netto, listino del
|
||||
documento o del cliente, base, articolo) con la fonte e gli sconti del cliente a cascata.
|
||||
- Scheda *Articoli e codici* delle anagrafiche: i codici con cui un cliente o un fornitore chiama i tuoi articoli,
|
||||
trovati dalla ricerca nei suoi documenti.
|
||||
- 120 articoli di esempio con listini *Pubblico* e *Rivenditori*, prezzi dell'anno precedente, fornitori, UM e
|
||||
codici alternativi, sostitutivi e prezzi netti di un cliente; `scripts/seed.sh --demo [--scale N]` carica i dati
|
||||
di esempio da riga di comando e moltiplica il catalogo per le prove di prestazione.
|
||||
- Import/export guidato (ADR 0031) in *Amministrazione → Import / export dati*: CSV (separatore e codifica dedotti),
|
||||
XLSX (lettore interno, primo foglio) e JSON per clienti, fornitori, articoli e prezzi di listino e netti cliente;
|
||||
mappatura automatica delle colonne con alias, validazione riga per riga con le regole della scheda, esiti *nuovo*,
|
||||
*aggiorna*, *avviso*, *errore*, opzioni per codici esistenti o mancanti, VIES e comune da CAP, report errori CSV,
|
||||
esito nel log. Export con le stesse colonne dell'import e modelli vuoti. Giacenze iniziali e piano dei conti (tracciato
|
||||
`codice;descrizione;livello;padre;natura;tipo;voce_cee;riclassifica;flag` e `khaemhat-coa.json`) si verificano
|
||||
già, la scrittura arriva con M6 e M7.
|
||||
|
||||
### Changed
|
||||
- Tabella *Listini*: nuovi campi *Listino base* (uno solo) e *Derivato da*; la migrazione marca come base il listino
|
||||
`BASE` esistente.
|
||||
- Il componente dei passi verticali mette il dettaglio di ogni passo su una riga propria.
|
||||
|
||||
### Known issues
|
||||
- L'azienda demo creata da `KHAEMHAT_SEED_DEMO` ha il profilo vuoto (indirizzo, partita IVA): va compilato prima dei
|
||||
documenti (M5).
|
||||
- Mancano le banche ABI/CAB nei dati di base: non c'è ancora una fonte con licenza compatibile (#45).
|
||||
|
||||
## [0.3.0] - 2026-11-11
|
||||
|
||||
M3 — Framework UI. La shell dell'applicazione, la libreria di componenti `Kh*` con griglie, radar e pagine record, la
|
||||
dashboard a widget, le preferenze dell'utente, ricerca, aiuto e notifiche, allegati e anteprima di stampa, tutto
|
||||
provato su un documento di sviluppo in attesa delle maschere vere (da M4).
|
||||
|
||||
### Added
|
||||
- Libreria di componenti `Kh*` (ADR 0024): campi con numeri e date all'italiana (`T`, `F`, `I`, `+n`, cifre senza
|
||||
separatori) e calcolo `=10*3`, messaggi accanto al campo e riepilogo che porta al campo, pannelli, tessere, badge,
|
||||
chip, importi, schede con `Alt+1`…`Alt+9`, passi, finestre di dialogo, pannelli laterali e messaggi a comparsa.
|
||||
- `KhIconToolbar` su una riga con il menu `…`, `KhDocHead` a tre blocchi e le basi `RecordPage`, `DocumentPage`,
|
||||
`MasterDataPage` con comandi standard, conferme e scorciatoie `Ctrl+S`, `Ctrl+N`, `Ctrl+P`, `Ctrl+Canc`, `F9`.
|
||||
- Liste con un solo modello di richiesta (`ListQuery`, `ListFields`): la stessa descrizione dei campi diventa SQL o
|
||||
filtra righe in memoria. `KhGrid` virtualizzata (100.000 righe) con ordinamento, selezione, tastiera, modifica in
|
||||
riga, totali, menu di riga, colonne salvate ed esportazione CSV/XLSX; `KhRadar` con ricerca, filtri rapidi,
|
||||
costruttore di filtri e filtri salvati; finestra radar per la ricerca `F4`; `KhLinesGrid` per le righe dei
|
||||
documenti.
|
||||
- *Il mio profilo*: dati personali, cambio password che chiude le altre sessioni, attivazione e disattivazione della
|
||||
verifica in due passaggi con codici di recupero.
|
||||
- Catalogo dei componenti e documento di prova per gli sviluppatori (`/sviluppo/componenti`, `/sviluppo/documento`,
|
||||
solo in sviluppo).
|
||||
- Primi screenshot reali nella wiki (`docs/wiki/img/`): finestra, menu compresso, ricerca, notifiche, aiuto,
|
||||
dashboard, profilo, tema scuro, documento, allegati, storico, anteprima di stampa, telefono.
|
||||
- Shell (mockup 004, 007, 013): barra superiore con marchio e versione, cambio azienda per gli account di istanza,
|
||||
ricerca, recenti, notifiche, tema rapido, aiuto e menu utente; menu laterale per sezioni con voci filtrate da
|
||||
licenza e permessi, compresso a sole icone con sottomenu a comparsa (`Ctrl+B`, stato ricordato per utente,
|
||||
compresso sotto i 1100 px); barra di stato con azienda, esercizio, utente, latenza, cache e versione.
|
||||
- Schede tenute in vita: ogni pagina aperta resta com'era passando da una scheda all'altra, pallino delle modifiche,
|
||||
conferma alla chiusura, massimo 12 schede (si chiude la meno usata senza modifiche) (ADR 0020).
|
||||
- Scorciatoie da tastiera in un'unica tabella, con le varianti `Alt+W`, `Alt+PagGiù`/`Alt+PagSu`, `Alt+N` per le
|
||||
combinazioni che i browser tengono per sé; ricerca rapida `Ctrl+K` di pagine e comandi; `F1` apre la pagina wiki
|
||||
della maschera.
|
||||
- Testi dell'interfaccia in `Resources/it-IT/*.json` letti da `ITexts`, formati italiani per importi e date; test che
|
||||
vietano i testi letterali nei componenti e controllano che ogni chiave esista.
|
||||
- *Il mio profilo*: aspetto (tema automatico, chiaro, scuro, alto contrasto; otto accenti; densità; dimensione del
|
||||
testo; menu; numeri tabellari, animazioni ridotte, suggerimenti, evidenza della riga) con anteprima dal vivo,
|
||||
pagina iniziale, sessioni attive con chiusura, elenco delle scorciatoie.
|
||||
- Preferenze salvate per utente in `sys_user_settings` (account di istanza) e `user_settings` (utenti aziendali); il
|
||||
tema è già nella pagina inviata dal server.
|
||||
- Aiuto in app (mockup 011): `F1` e `?` aprono in una scheda la pagina wiki della maschera dalla copia della wiki
|
||||
contenuta nell'immagine (`/aiuto`, funziona senza Internet), con indice, *Apri nel wiki* e *Segnala un problema*;
|
||||
Markdown convertito in casa; nuova variabile facoltativa `KHAEMHAT_HELP_URL` per la wiki online (ADR 0023).
|
||||
- Pannello notifiche (mockup 010): filtri *Tutte* e *Non lette*, segna come letta, *Segna tutte come lette*,
|
||||
conteggio aggiornato ogni minuto; le notifiche per tutti si segnano lette per ciascun utente (tabelle
|
||||
`sys_notification_reads` e `notification_reads`).
|
||||
- Ricerca globale a fornitori (`GlobalSearchService`, `ISearchProvider`): oltre a pagine e comandi trova le pagine e
|
||||
le sezioni dell'aiuto; prefissi `#` documenti e `@` persone pronti per i moduli successivi.
|
||||
- Allegati nell'interfaccia (mockup 024): `KhAttachmentList` con caricamento, anteprima, download, blocco, cestino
|
||||
con ripristino, versioni precedenti, *Scarica tutto (ZIP)* e *Genera file* / *Rigenera*; anteprima di PDF e
|
||||
immagini nel browser, di XML e testo come testo, di CSV e XLSX come griglia (lettore XLSX scritto in casa).
|
||||
- Anteprima di stampa (mockup 025): `KhPrintPreview` con foglio A4 in HTML e CSS, *Stampa* del solo foglio, PDF da
|
||||
aprire o scaricare e *Salva come allegato*; prova sul documento di sviluppo con `Ctrl+P`.
|
||||
- Storico di un record: `AuditTrailService` legge il registro delle modifiche e `KhAuditList` mostra chi ha cambiato
|
||||
cosa, con i valori prima e dopo.
|
||||
- Indirizzi `/files/{id}`, `/files/zip` e `/files/generate` per scaricare gli allegati, tutti gli allegati di un
|
||||
record e un file generato al volo; solo PDF e immagini si aprono nel browser, con una politica di sicurezza propria
|
||||
che permette l'anteprima dentro Khaemhat.
|
||||
- Con la dashboard spenta, Home con licenza, moduli, azienda e aree disponibili; le aree delle prossime versioni
|
||||
aprono una pagina che dice con quale milestone arrivano.
|
||||
- Dashboard a widget (mockup 004-006, ADR 0022): Da fare oggi, Fatto oggi, Scadenze 30 giorni, Promemoria personali,
|
||||
Scorciatoie e Stato del sistema con dati veri; i widget dei moduli futuri si possono già accendere e dicono da quale
|
||||
versione arrivano i dati. Pannello *Personalizza* con pagina iniziale, interruttore della dashboard, widget da
|
||||
accendere, ordinare e dimensionare, trascinamento sulla griglia e pulsanti equivalenti da tastiera, *Ripristina* e
|
||||
layout predefinito per ruolo. Le liste raccolgono le righe da sorgenti che ogni modulo registra.
|
||||
- Impostazioni dell'azienda nella tabella `company_settings`, scritte con il permesso `company.settings.write`.
|
||||
- Token, temi e classi dei mockup in `css/tokens.css` e `css/components.css`, sprite di icone proprie, stampa sempre
|
||||
in chiaro.
|
||||
|
||||
### Changed
|
||||
- `Esc` chiude anche un pannello laterale aperto quando il focus non è in un campo.
|
||||
- Su telefono la barra superiore mostra solo le icone e la barra di stato solo connessione, cache e versione.
|
||||
|
||||
### Fixed
|
||||
- L'etichetta *Totale documento* dell'intestazione era tagliata: prendeva lo stile della timeline (`.tl`).
|
||||
- Le schede dei temi e dei colori nel profilo andavano in colonna: la classe `.kh-choices` del radar le
|
||||
ridefiniva; il gruppo di scelte del radar ora si chiama `.kh-radio-set`.
|
||||
- Pagine di accesso, errori e riconnessione con i testi localizzati e i colori del tema.
|
||||
|
||||
## [0.2.0] - 2026-11-11
|
||||
|
||||
M2 — Sistema e sicurezza. L'istanza si avvia da sola, crea super utente e prima azienda, e si entra con password e
|
||||
|
||||
@@ -88,6 +88,11 @@ fermandosi solo per blocchi reali (SDK mancante, credenziali, PNG o dati che sol
|
||||
inglese che dicono *cosa cambia e perché*. Il push su Gitea e le pull request seguono le indicazioni dell'utente;
|
||||
il tag `vX.Y.Z` si crea alla chiusura di ogni milestone (§20).
|
||||
|
||||
**E7 — Versioni 0.x fino al via dell'utente** (sostituisce la colonna versione di §20 per M13 e M14; deciso
|
||||
dall'utente il 2026-11-12). Finché il prodotto è in sviluppo le versioni restano **0.x**: ogni milestone chiude con
|
||||
`v0.<n>.0` (M13 `v0.13.0`, M14 `v0.14.0` e seguenti). La **1.0.0 non si crea** (tag, immagine, release, CHANGELOG)
|
||||
finché l'utente non lo dice esplicitamente. L'icona versionata `icon-v1.0` resta il modello grafico.
|
||||
|
||||
## 4. Vincoli non negoziabili (sintesi di SPEC §1 — leggere l'originale)
|
||||
|
||||
1. C# 14 su .NET 10; JavaScript solo come interop minimo in `wwwroot/js`, senza framework né bundler.
|
||||
|
||||
@@ -43,6 +43,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.LicenseTool", "too
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.DataModelTool", "tools\Khaemhat.DataModelTool\Khaemhat.DataModelTool.csproj", "{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Khaemhat.PlacesTool", "tools\Khaemhat.PlacesTool\Khaemhat.PlacesTool.csproj", "{04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -257,6 +259,18 @@ Global
|
||||
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Release|x64.Build.0 = Release|Any CPU
|
||||
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F}.Release|x86.Build.0 = Release|Any CPU
|
||||
{04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Release|x64.Build.0 = Release|Any CPU
|
||||
{04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{04C6CC82-F19E-437A-BDFE-7A6F66E29D2E}.Release|x86.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
@@ -279,5 +293,6 @@ Global
|
||||
{FDCAC352-BB40-4B5E-948A-2CDAA48B9E6A} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
|
||||
{4317FFD0-9473-43FD-8543-F80EF9BA812A} = {07C2787E-EAC7-C090-1BA3-A61EC2A24D84}
|
||||
{7CA26565-5E1A-46AA-A2F7-C38FBADF0E3F} = {07C2787E-EAC7-C090-1BA3-A61EC2A24D84}
|
||||
{04C6CC82-F19E-437A-BDFE-7A6F66E29D2E} = {07C2787E-EAC7-C090-1BA3-A61EC2A24D84}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -32,6 +32,7 @@
|
||||
<Config Name="KHAEMHAT_LICENSE_MODE" Target="KHAEMHAT_LICENSE_MODE" Default="production" Mode="" Description="production oppure test (abilita i codici di licenza fittizi)" Type="Variable" Display="advanced" Required="false" Mask="false">production</Config>
|
||||
<Config Name="KHAEMHAT_LICENSE" Target="KHAEMHAT_LICENSE" Default="" Mode="" Description="Licenza firmata (.khl, testo). Vuoto = Trial" Type="Variable" Display="advanced" Required="false" Mask="true"></Config>
|
||||
<Config Name="KHAEMHAT_SEED_DEMO" Target="KHAEMHAT_SEED_DEMO" Default="false" Mode="" Description="true = dati dimostrativi al primo avvio (solo database vuoto)" Type="Variable" Display="advanced" Required="false" Mask="false">false</Config>
|
||||
<Config Name="KHAEMHAT_HELP_URL" Target="KHAEMHAT_HELP_URL" Default="" Mode="" Description="Opzionale: wiki online aperta da Apri nel wiki (predefinita https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/)" Type="Variable" Display="advanced" Required="false" Mask="false"></Config>
|
||||
<Config Name="KHAEMHAT_UPDATE_FEED" Target="KHAEMHAT_UPDATE_FEED" Default="" Mode="" Description="Opzionale: URL API pacchetti Gitea per il controllo aggiornamenti (https://gitea.encke-hake.ts.net/api/v1/packages/BalboSoft?type=container&q=khaemhat)" Type="Variable" Display="advanced" Required="false" Mask="false"></Config>
|
||||
<Config Name="TZ" Target="TZ" Default="Europe/Rome" Mode="" Description="Fuso orario" Type="Variable" Display="advanced" Required="false" Mask="false">Europe/Rome</Config>
|
||||
<Config Name="PUID" Target="PUID" Default="99" Mode="" Description="UID per i file in /data" Type="Variable" Display="advanced" Required="false" Mask="false">99</Config>
|
||||
|
||||
@@ -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" \
|
||||
|
||||
@@ -75,6 +75,7 @@ client degli aggiornamenti è `GiteaPackagesClient`.
|
||||
| `Khaemhat.Web` | host ASP.NET Core 10, Blazor Interactive Server, Minimal API, MCP, autenticazione | M0 → M13 |
|
||||
| `tools/Khaemhat.LicenseTool` | CLI per chiavi ed emissione licenze (chiave privata mai nel repository; non distribuito) | M2 |
|
||||
| `tools/Khaemhat.DataModelTool` | rigenera la sezione generata di `docs/DATA-MODEL.md` dalle migrazioni (non distribuito, ADR 0018) | M1 |
|
||||
| `tools/Khaemhat.PlacesTool` | rigenera province e comuni del pacchetto italiano dall'elenco ISTAT e dai CAP GeoNames (non distribuito, ADR 0028) | M4 |
|
||||
| `tests/*` | `Core`, `Data`, `Infrastructure`, `Fiscal.Italy`, `Application`, `Web` (MSTest) | ogni milestone |
|
||||
|
||||
## 3. Regole di dipendenza
|
||||
@@ -380,7 +381,7 @@ Khaemhat/
|
||||
│ └── Khaemhat.Web/ Program.cs Configuration/ Auth/ Api/ Mcp/ Help/ Components/
|
||||
│ (App, Routes, Layout/, Ui/, Pages/<Modulo>/, Shared/) Localization/ wwwroot/
|
||||
├── tests/ Core, Data, Infrastructure, Fiscal.Italy, Application, Web
|
||||
├── tools/Khaemhat.LicenseTool/
|
||||
├── tools/ Khaemhat.LicenseTool, Khaemhat.DataModelTool, Khaemhat.PlacesTool
|
||||
└── docs/
|
||||
├── SPEC.md ARCHITECTURE.md DATA-MODEL.md MODULES.md API.md MCP.md
|
||||
├── DEPLOY.md DEVELOPMENT.md SECURITY.md STATUS.md
|
||||
|
||||
@@ -219,7 +219,8 @@ Regole (SPEC §16.6, E1):
|
||||
VERSION` (`/p:Version`) insieme a `GIT_SHA` (`/p:SourceRevisionId`, mostrato come `+sha`).
|
||||
- Dove compare (SPEC §16.5): barra superiore (`major.minor`), barra di stato (completa), *Stato sistema*,
|
||||
`manifest.webmanifest`, etichette OCI, icona versionata.
|
||||
- Milestone: `v0.0.1` (M0) … `v0.12.0` (M12), `v1.0.0` (M13), `v1.1.0`+ (M14) — SPEC §20.
|
||||
- Milestone: `v0.0.1` (M0) … `v0.12.0` (M12), `v0.13.0` (M13), `v0.14.0`+ (M14). La `1.0.0` si crea solo quando
|
||||
l'utente lo decide (emendamento E7 in `CLAUDE.md`, che modifica SPEC §20).
|
||||
- Le migrazioni non si riscrivono mai dopo un rilascio: una correzione è una migrazione nuova.
|
||||
|
||||
## 8. Endpoint di salute
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -2,17 +2,19 @@
|
||||
|
||||
> Punto di ripresa per ogni sessione. Aggiornare a fine sessione.
|
||||
|
||||
**Ultimo aggiornamento:** 2026-11-11
|
||||
**Milestone corrente:** M2 — Sistema e sicurezza, completata nel ramo `feat/15-sistema-e-sicurezza` (PR verso `main`);
|
||||
il tag `v0.2.0` si crea dopo il merge.
|
||||
**Prossimo passo:** M3 — Interfaccia (issue #25-#36): layout, navigazione e componenti sopra le pagine di accesso di M2.
|
||||
Da recuperare: misure di riferimento su PostgreSQL in `docs/DATA-MODEL.md` §6.1; pagina di cambio password con
|
||||
indicatore di robustezza (mockup 003) in M3.
|
||||
**Ultimo aggiornamento:** 2026-11-12
|
||||
**Milestone corrente:** M4 — Tabelle, anagrafiche, articoli: chiusa sul ramo `feat/37-tabelle-anagrafiche` (#46),
|
||||
in attesa del merge in `main` con l'approvazione del titolare; poi tag `v0.4.0`, immagine e release.
|
||||
**Prossimo passo:** dopo il merge, M5 — Motore documenti e Vendite (#47-#54). #35 (PNG ad alta risoluzione) resta
|
||||
aperta e non blocca; #45 resta aperta solo per le banche ABI/CAB (manca una fonte con licenza compatibile).
|
||||
Da recuperare: profilo dell'azienda demo (indirizzo, partita IVA) prima dei documenti di M5; misure di riferimento su PostgreSQL in `docs/DATA-MODEL.md` §6.1; indicatore di robustezza della
|
||||
password (mockup 003); schede *Layout salvati* e *Notifiche* (con le e-mail, M5) del profilo; rinomina e
|
||||
filtro predefinito nei radar.
|
||||
|
||||
## Fatto
|
||||
|
||||
- Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E6.
|
||||
- ADR 0001-0019.
|
||||
- Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E7.
|
||||
- ADR 0001-0031.
|
||||
- Mockup in `docs/mockups/` (22 in alta risoluzione + galleria, 88 miniature, `mockup.css`, indice).
|
||||
- Icone in `assets/`; deploy in `deploy/` (compose Unraid, `.env.example`, template Unraid).
|
||||
- Documentazione tecnica: `ARCHITECTURE.md`, `DATA-MODEL.md` (provvisorio, sarà generato), `MODULES.md`, `API.md`,
|
||||
@@ -30,7 +32,7 @@ indicatore di robustezza (mockup 003) in M3.
|
||||
(AES-256-GCM, formato `khs1`), `tools/Khaemhat.DataModelTool` e gli script `new-migration.sh` e
|
||||
`gen-datamodel.sh`; ADR 0018. Test: 106 test dello strato dati verdi su SQLite in locale e su PostgreSQL 16 e 17 in CI
|
||||
(in locale Docker non è disponibile).
|
||||
- **M2 (`v0.2.0`, PR da aprire):** avvio da variabili con elenco degli errori, migrazioni all'avvio, super utente e
|
||||
- **M2 (chiusa, `v0.2.0`, PR #118):** avvio da variabili con elenco degli errori, migrazioni all'avvio, super utente e
|
||||
prima azienda; account di istanza e aziendali, password con storico e blocco, sessioni nel database, TOTP con codici
|
||||
di recupero, pagine di accesso (mockup 001-003); ruoli, permessi e attributi di autorizzazione; licenze firmate,
|
||||
codici di attivazione, modalità test, `tools/Khaemhat.LicenseTool`; DataProtection nel database cifrata; cache
|
||||
@@ -38,6 +40,24 @@ indicatore di robustezza (mockup 003) in M3.
|
||||
job di sistema; storico dei record; aziende con stati e contesto (`X-Company`); header di sicurezza; ADR 0019.
|
||||
Test: 180 verdi in locale, più 21 di PostgreSQL saltati senza Docker (girano in CI). La chiave privata delle licenze è fuori dal
|
||||
repository (`Khaemhat-private/khaemhat-license.khkey`) e va conservata dal titolare.
|
||||
- **M3 (chiusa, `v0.3.0`, PR #119):** shell con barra superiore, menu comprimibile con sottomenu a comparsa,
|
||||
schede tenute in vita, barra di stato, scorciatoie con varianti `Alt`; testi in `Resources/it-IT/*.json` con test
|
||||
anti-testo-letterale; preferenze utente e *Il mio profilo* (aspetto, pagina iniziale, dati personali, password e
|
||||
2FA, sessioni, scorciatoie); libreria `Kh*` con campi all'italiana, toolbar a icone, intestazione documento e basi
|
||||
`RecordPage`/`DocumentPage`/`MasterDataPage`; liste con `ListQuery`/`ListFields`, `KhGrid` virtualizzata, `KhRadar`
|
||||
e `KhLinesGrid`; dashboard a widget con layout per utente e per ruolo e `company_settings`; ricerca globale a
|
||||
fornitori, aiuto in app dalla copia della wiki, pannello notifiche; allegati con anteprime, *Genera file*, ZIP,
|
||||
cestino e storico; anteprima di stampa A4; catalogo dei componenti e documento di prova per gli sviluppatori;
|
||||
primi screenshot reali in `docs/wiki/img/`; ADR 0020-0024. Test: 368 verdi in locale, 21 di PostgreSQL saltati;
|
||||
immagine costruita in locale e avviata da zero con SQLite.
|
||||
- **M4 (chiusa, `v0.4.0`):** pacchetto fiscale `IT 2026.3` (codici IVA, nature, code list FatturaPA, motore IVA,
|
||||
calendario, ritenute, F24; ADR 0025); validatori e `ViesClient`; 26 tabelle azienda con un'unica maschera, profilo
|
||||
azienda, esercizi e cambi BCE (ADR 0026); dati di base con province e comuni ISTAT e CAP GeoNames (ADR 0028) e
|
||||
`scripts/seed.sh --base|--demo`; codici automatici e compilazione automatica (ADR 0027); clienti, fornitori e
|
||||
contatti con radar, scheda, controlli e VIES (ADR 0029); articoli e listini con prezzi a validità, listini derivati e
|
||||
aggiornamento massivo (ADR 0030); import/export guidato CSV/XLSX/JSON con tracciato del piano dei conti (ADR 0031);
|
||||
21 anagrafiche e 120 articoli di esempio; screenshot reali nella wiki. Test: 631 verdi in locale, 21 di PostgreSQL
|
||||
saltati; immagine costruita in locale e avviata da zero con SQLite e dati di esempio.
|
||||
- Su Gitea: etichette, milestone M0-M14, 114 issue con checklist, progetti *Khaemhat 1.0 — Sviluppo* (M0-M13)
|
||||
e *Khaemhat 1.1+ — Fase 2* (M14). Numerazione: M0 #1-#6 e #114, M1 #7-#14, M2 #15-#24, M3 #25-#36,
|
||||
M4 #37-#46, M5 #47-#54, M6 #55-#61, M7 #62-#68, M8 #69-#73, M9 #74-#81, M10 #82-#87, M11 #88-#91,
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
# ADR 0020 - Shell dell'interfaccia: schede, testi, preferenze, scorciatoie
|
||||
|
||||
- **Stato:** accettata
|
||||
- **Data:** 2026-11-11
|
||||
- **Modifica:** SPEC §1.9, §10.2, §10.5, §10.6, §10.8, §11.12; milestone M3, issue #25, #26, #31, #33
|
||||
|
||||
## Contesto
|
||||
|
||||
M3 costruisce la shell (barra superiore, menu comprimibile, schede, barra di stato), i testi localizzati e le
|
||||
preferenze utente. La specifica fissa il risultato visivo (mockup 004, 007, 008, 013) ma lascia aperti alcuni punti
|
||||
tecnici; altri si scontrano con il browser o con Blazor. Questo ADR fissa le scelte.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Schede tenute in vita.** Ogni indirizzo aperto diventa una scheda (`TabService`, massimo 12). La scheda conserva
|
||||
il **tipo di pagina e una copia dei parametri di rotta** (`RouteData` passato in cascata da `Routes.razor`), non il
|
||||
`Body` del layout: `Body` disegna sempre la pagina corrente, quindi tutte le schede avrebbero mostrato l'ultima.
|
||||
Il layout disegna un pannello per scheda e nasconde quelli inattivi (`hidden`), così passando da una scheda
|
||||
all'altra lo stato della pagina resta. La stessa pagina con un'altra query (`/profilo?scheda=sessioni`) riusa la
|
||||
scheda. Alla tredicesima si chiude la scheda meno usata **senza modifiche**; se tutte hanno modifiche l'apertura
|
||||
è rifiutata con un avviso. Il titolo del browser lo scrive il layout dalla scheda attiva; `KhPageTitle` imposta
|
||||
solo il titolo della scheda.
|
||||
2. **Scorciatoie riservate dal browser.** `Ctrl+W`, `Ctrl+Tab` e `Ctrl+N` restano dei browser, che non le passano alla
|
||||
pagina. Si tengono come da specifica e si aggiungono `Alt+W`, `Alt+PagGiù` / `Alt+PagSu` e `Alt+N`, che arrivano
|
||||
sempre. Le scorciatoie sono un'unica tabella (`KeyboardShortcuts.All`) usata dal gestore JavaScript, dalla
|
||||
ricerca e dalla scheda *Scorciatoie* del profilo; un test controlla che ogni combinazione sia unica.
|
||||
3. **Testi in JSON incorporati.** I testi stanno in `src/Khaemhat.Web/Resources/<cultura>/*.json`, risorse incorporate
|
||||
lette da `JsonTextProvider` (`ITexts`). Gli oggetti annidati danno chiavi puntate (`Shell.Menu.Parties`), la
|
||||
proprietà `_` dà il testo all'oggetto che ha anche figli, una chiave definita due volte è un errore all'avvio, una
|
||||
chiave mancante si vede come `[chiave]`. Niente `.resx`: il JSON si legge e si confronta meglio nelle revisioni e
|
||||
non richiede generatori. Due test lo fanno rispettare: nessun testo letterale nei componenti `.razor` (testo fra i
|
||||
tag e attributi `title`, `placeholder`, `alt`, `aria-label`, `label`) e ogni chiave usata nel codice esiste.
|
||||
4. **Preferenze per utente nel database del proprietario.** `UserSettingsService` salva coppie chiave/valore in
|
||||
`sys_user_settings` per gli account di istanza e in `user_settings` per gli utenti aziendali (valore massimo 64 KB,
|
||||
chiave massimo 200 caratteri). `UserPreferences` legge e scrive l'insieme tipizzato (tema, accento, densità,
|
||||
dimensione testo, numeri tabellari, animazioni, suggerimenti, evidenza riga, menu, pagina iniziale) e scarta i
|
||||
valori non validi; la pagina iniziale accetta solo percorsi locali.
|
||||
5. **Tema scritto dal server.** Le preferenze diventano attributi `data-*` sull'elemento `<html>` già nella risposta
|
||||
del server (`App.razor`), così la prima pagina ha i colori giusti; il cambio dal profilo o dalla barra superiore li
|
||||
aggiorna dal vivo con `khaemhat.applyRoot`. Prima dell'accesso vale `data-theme="auto"`, che segue il sistema. Il
|
||||
profilo mostra ogni scelta subito (anteprima) e la conserva solo con **Salva**; chiudendo la scheda senza salvare
|
||||
torna l'aspetto salvato.
|
||||
6. **Aree non ancora costruite.** Il menu mostra le aree concesse da licenza e permessi anche se arrivano con
|
||||
milestone successive; aprono una pagina che dice con quale milestone arrivano (`MenuItem.Milestone`). Quando una
|
||||
pagina vera esiste, la sua rotta prende il posto di quella generica e la milestone si toglie dal catalogo.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Le pagine aperte restano in memoria nel circuito finché la scheda è aperta: il limite di 12 schede tiene il
|
||||
consumo sotto controllo.
|
||||
- Una pagina che usa parametri da query li riceve anche quando è nascosta e cambia la query di un'altra scheda con
|
||||
lo stesso nome di parametro: i nomi dei parametri da query vanno scelti specifici della pagina.
|
||||
- Aggiungere un testo vuol dire aggiungere una chiave al JSON; i test falliscono se manca.
|
||||
@@ -0,0 +1,73 @@
|
||||
# ADR 0021 - File e allegati: archivio su volume, versioni, cestino, scrittori in casa
|
||||
|
||||
- **Stato:** accettata
|
||||
- **Data:** 2026-11-11
|
||||
- **Modifica:** SPEC §2 (riga *PDF e file*), §9.4; milestone M3, issue #34
|
||||
|
||||
## Contesto
|
||||
|
||||
La specifica chiede allegati per azienda con versioni, cestino di 30 giorni, archivio su volume con limite, quota e
|
||||
aggancio per l'antivirus, e scrittori PDF, CSV, XLSX e ZIP scritti in casa (nessuna libreria esterna, ADR 0002). Lascia
|
||||
aperti la regola di numerazione delle versioni, la forma dell'archivio, il perimetro della prima versione del PDF e le
|
||||
impostazioni predefinite del CSV. Questo ADR fissa le scelte.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Archivio.** `IFileStore` sta in `Khaemhat.Core.Files` (l'implementazione è in Infrastructure, che non vede
|
||||
Application); `VolumeFileStore` scrive in `<KHAEMHAT_DATA_DIR>/files/<AZIENDA>/<aaaa>/<guid>`. Ogni file è scritto
|
||||
prima come `<guid>.part` **nella stessa cartella**, contando i byte (limite) e calcolando lo SHA-256 durante la
|
||||
copia; poi passa quota e scanner e viene rinominato. Mai file temporanei fuori dal volume dei dati. La chiave
|
||||
salvata nel database è `aaaa/guid` (relativa alla cartella dell'azienda) e viene validata: non può uscire dalla
|
||||
cartella. I `.part` rimasti da caricamenti interrotti si cancellano dopo un giorno.
|
||||
2. **Limiti.** 25 MB per file e nessuna quota per impostazione predefinita; gli amministratori li cambiano con le
|
||||
impostazioni di istanza `files.max-upload-mb` e `files.company-quota-mb`. Il limite di dimensione vale per i file
|
||||
caricati; i file generati hanno solo la quota. La quota si calcola sommando i file della cartella dell'azienda.
|
||||
3. **Antivirus.** `IFileScanner` riceve il file completo prima che diventi visibile; quello registrato
|
||||
(`NoOpFileScanner`) accetta tutto.
|
||||
4. **Versioni.** Ogni allegato ha una *serie* (`version_key`): per i file generati il codice del generatore
|
||||
(`gen:<codice>`), per gli altri il nome in minuscolo (`name:<nome>`). La versione è il massimo della serie nel
|
||||
record più uno, contando anche gli allegati nel cestino; un indice unico su record + serie + versione impedisce due
|
||||
versioni uguali (in caso di conflitto si riprova). *Rigenera* è una nuova generazione: non sovrascrive mai.
|
||||
Caricare un file con lo stesso nome ne crea la versione successiva e lascia consultabile la precedente. L'elenco
|
||||
mostra di norma solo l'ultima versione di ogni serie; il nome di download porta il suffisso `_vN` dalla v2.
|
||||
5. **Cestino.** Cancellare un allegato o il documento lo sposta nel cestino (`deleted_at`); il job di sistema
|
||||
`system.attachments-trash` (ogni notte alle 3:45) elimina righe e file dopo 30 giorni. Un allegato **bloccato**
|
||||
(`locked`, ad esempio l'XML inviato allo SDI) non si cancella, e un documento con allegati bloccati non può mandarli
|
||||
nel cestino. Il blocco è definitivo.
|
||||
6. **Permessi.** `attachments.read` per vedere e scaricare, `attachments.write` per caricare, generare e bloccare,
|
||||
`attachments.delete` per cancellare e ripristinare. Il permesso sul documento lo verifica chi chiama, che lo
|
||||
conosce. Ogni modifica scrive lo storico (`audit_log`); l'utente che ha caricato o generato il file è salvato anche
|
||||
in `attachments.user_name`, perché le colonne di audit conoscono l'utente solo dentro una richiesta HTTP.
|
||||
7. **Tipi di file.** Il tipo MIME si ricava dall'estensione quando è nota; quello dichiarato dal browser si usa solo
|
||||
per estensioni sconosciute. I nomi file sono ripuliti (niente cartelle né caratteri vietati, massimo 255).
|
||||
8. **CSV.** Predefiniti per Excel in italiano: separatore `;`, BOM UTF-8, virgola decimale, date `gg/mm/aaaa`,
|
||||
righe CRLF, virgolette RFC 4180. Le celle di testo che iniziano con `=`, `+`, `-`, `@`, tabulazione o ritorno a capo
|
||||
ricevono un apostrofo davanti (iniezione di formule); i numeri non vengono toccati. Disponibile anche il profilo
|
||||
invariante (`,`, punto decimale, date ISO, senza BOM).
|
||||
9. **Scrittura in streaming.** CSV, XLSX, ZIP e PDF scrivono sull'uscita solo con chiamate asincrone, quindi possono
|
||||
scrivere direttamente nella risposta HTTP (dove le scritture sincrone sono vietate). `ZipArchive` scrive ancora in
|
||||
modo sincrono le chiusure delle voci e la directory centrale: quei pochi byte passano da un piccolo buffer in
|
||||
memoria (`AsyncOutputBuffer`) e vengono inviati con la chiamata asincrona successiva.
|
||||
10. **PDF, prima versione.** PDF 1.7 con i 12 font Type1 standard latini (Symbol e ZapfDingbats esclusi) in
|
||||
`WinAnsiEncoding` (lettere accentate, `€`, virgolette tipografiche), testo, linee, rettangoli, colori RGB,
|
||||
immagini JPEG incorporate così come sono (`DCTDecode`), più pagine, dizionario *Info*, flussi compressi
|
||||
`FlateDecode`, tabella xref. Coordinate in punti dall'angolo **in basso a sinistra**, testo posizionato sulla linea
|
||||
di base. Le larghezze per misurare e andare a capo sono quelle AFM di Helvetica, Helvetica-Bold e Times-Roman;
|
||||
corsivi e grassetti di Times usano quelle del tondo, Courier è a passo fisso. Una pagina viene scritta sull'uscita
|
||||
quando inizia la successiva. **PDF/A-3** (font incorporati, XMP, output intent, allegati XML per la copia di
|
||||
cortesia FatturaPA) è rimandato: annotato come TODO in `PdfWriter`.
|
||||
11. **Generatori.** Un'uscita di *Genera file* è un `IFileGenerator` (codice, chiave del testo, tipo, estensione,
|
||||
entità supportate, nome file, `GenerateAsync`); `FileGenerationService` scrive il risultato direttamente
|
||||
nell'archivio e lo registra come allegato generato con la versione successiva, oppure lo scrive su un flusso senza
|
||||
salvarlo (anteprima di stampa). Per il *documento di prova* dell'issue #34 ci sono tre generatori dell'entità
|
||||
fittizia `demo.document`: PDF, CSV e XLSX con righe e importi inventati.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Gli allegati nel cestino occupano spazio e quota per 30 giorni.
|
||||
- Il calcolo della quota legge la cartella dell'azienda a ogni caricamento quando una quota è impostata: va bene per
|
||||
le dimensioni attese; se diventasse lento si terrà un contatore.
|
||||
- Un file rimasto senza riga (crash fra scrittura del file e inserimento) è solo spazio perso; il contrario non può
|
||||
accadere, perché la riga si scrive dopo il file e il file si cancella se l'inserimento fallisce.
|
||||
- I moduli che producono file (stampe, FatturaPA, report) registrano i loro `IFileGenerator`; quelli che ricevono
|
||||
file dall'esterno (SDI, e-mail) usano `AttachmentService.AddAsync` con il tipo giusto e, se serve, `Locked`.
|
||||
@@ -0,0 +1,47 @@
|
||||
# ADR 0022 - Dashboard a widget: layout per utente e per ruolo, liste fornite dai moduli
|
||||
|
||||
- **Stato:** accettata
|
||||
- **Data:** 2026-11-11
|
||||
- **Modifica:** SPEC §10.3, §11.12; milestone M3, issue #30 e #31
|
||||
|
||||
## Contesto
|
||||
|
||||
La specifica descrive la dashboard (mockup 004-006) con widget attivabili, ordinabili e ridimensionabili, una pagina
|
||||
iniziale scelta dall'utente e un layout predefinito per ruolo, ma non dice dove si salvano i layout dei ruoli, quale
|
||||
layout vede chi non ha mai personalizzato, né come i moduli che arrivano dopo M3 (vendite, magazzino, CRM) riempiono
|
||||
i widget. Lascia anche aperto il comando per tornare alla disposizione iniziale.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Catalogo fisso.** I widget sono un catalogo nel codice (`WidgetCatalog`): id, titolo, icona, larghezza
|
||||
predefinita, modulo di licenza, permesso di lettura, solo amministratori, milestone che porta i dati. Un widget è
|
||||
*disponibile* se il modulo è attivo, l'utente ha il permesso e, per *Stato del sistema*, è un account di istanza.
|
||||
2. **Layout in JSON.** `{"v":1,"widgets":[{"id":"todo","w":4}]}`: l'ordine è quello dell'elenco, le larghezze sono 3,
|
||||
4, 6, 8 o 12 colonne (una larghezza diversa va alla più vicina, la più larga a parità). Leggendolo si scartano id
|
||||
sconosciuti e ripetuti; un layout illeggibile vale come assente. Al massimo 30 widget.
|
||||
3. **Dove si salva.** Il layout dell'utente è un'impostazione utente (`dashboard.layout`, ADR 0020: sistema per gli
|
||||
account di istanza, azienda per gli utenti aziendali). Il layout di un ruolo è un'impostazione **dell'azienda**
|
||||
(`dashboard.layout.role.<CODICE>`) nella nuova tabella `company_settings`, scritta da `CompanySettingsService`
|
||||
con il permesso `company.settings.write`. Promemoria (`dashboard.notes`) e scorciatoie (`dashboard.shortcuts`)
|
||||
sono impostazioni utente.
|
||||
4. **Quale layout si vede.** Quello dell'utente; altrimenti quello del primo ruolo dell'utente (per id) che ne ha uno;
|
||||
altrimenti il layout di Khaemhat. In ogni caso si tolgono i widget non disponibili. **Ripristina** cancella il
|
||||
layout dell'utente e riporta quello del ruolo o di Khaemhat.
|
||||
5. **Layout di Khaemhat.** Solo widget che hanno già dati: Da fare oggi, Fatto oggi, Scadenze, Scorciatoie,
|
||||
Promemoria, Stato del sistema. I widget dei moduli futuri (KPI, Da evadere, Fatturato, Sottoscorta, CRM, Ultimi
|
||||
documenti) si possono già accendere e mostrano da quale milestone arrivano i dati, senza numeri finti.
|
||||
6. **Liste dai moduli.** *Da fare oggi*, *Fatto oggi* e *Scadenze 30 giorni* raccolgono le righe da sorgenti
|
||||
registrate nel contenitore (`ITodoSource`, `IDoneSource`, `IDeadlineSource`): ogni modulo aggiunge le sue. Le
|
||||
sorgenti si chiamano una dopo l'altra; una che fallisce si scrive nel log e si salta, il widget mostra le altre.
|
||||
In M3 ci sono licenza, avvisi non letti e attività programmate.
|
||||
7. **Personalizza.** Pannello laterale non modale (la pagina resta visibile) con pagina iniziale, interruttore della
|
||||
dashboard, elenco dei widget con interruttore, larghezza e frecce, e il predefinito per ruolo per chi gestisce
|
||||
l'azienda. Sulla griglia i widget si trascinano (HTML drag and drop) e hanno anche pulsanti per spostare,
|
||||
allargare, restringere e nascondere, così tutto funziona da tastiera. Ogni modifica si salva subito.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- I moduli di M5, M6 e M11 riempiono i widget registrando sorgenti e sostituendo il componente del widget; il layout
|
||||
salvato dagli utenti resta valido.
|
||||
- `company_settings` è il posto per le altre impostazioni di azienda delle prossime milestone.
|
||||
- Un utente con più ruoli prende il predefinito del primo; se servirà una priorità esplicita fra ruoli si aggiungerà.
|
||||
@@ -0,0 +1,55 @@
|
||||
# ADR 0023 - Aiuto in app dalla copia della wiki, notifiche lette per utente, ricerca a fornitori
|
||||
|
||||
- **Stato:** accettata
|
||||
- **Data:** 2026-11-11
|
||||
- **Modifica:** SPEC §10.2, §17; milestone M3, issue #32 (mockup 009, 010, 011)
|
||||
|
||||
## Contesto
|
||||
|
||||
La specifica chiede che `F1` apra la pagina wiki della maschera dentro l'applicazione (mockup 011), con indice,
|
||||
*Apri nel wiki* e *Segnala un problema*, e che l'aiuto funzioni anche nelle installazioni senza Internet servendo
|
||||
una copia della wiki "all'indirizzo `/help`". Non dice come la copia arriva nell'immagine, come si converte il
|
||||
Markdown senza librerie esterne (SPEC §1.2), né come una notifica "per tutti" diventa letta per un utente e non per
|
||||
gli altri. Per la ricerca globale (mockup 009) dice cosa trovare, ma i dati (clienti, articoli, documenti) arrivano
|
||||
con le milestone successive.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **La wiki viaggia con il programma.** La compilazione copia `docs/wiki/*.md` in `help/wiki/` accanto al
|
||||
programma, e in `help/media/` le immagini che le pagine mostrano (miniature e PNG dei mockup, icone, `img/` della
|
||||
wiki), con lo stesso percorso che hanno nel repository. `.dockerignore` lascia entrare solo quelle cartelle di
|
||||
`docs/`. Nessun download all'avvio, nessuna scrittura: la copia è di sola lettura e corrisponde alla versione.
|
||||
2. **Markdown in casa.** `WikiMarkdown` converte il sottoinsieme che la wiki usa: titoli con ancora, paragrafi,
|
||||
elenchi annidati, tabelle, citazioni, blocchi di codice, linee, immagini, collegamenti, grassetto, corsivo,
|
||||
codice. Tutto il testo è codificato (niente HTML grezzo); diventano collegamenti solo indirizzi `http(s)`,
|
||||
ancore `#` e nomi di pagina. La citazione `> **Stato:** …` in testa a ogni pagina è lo stato della pagina e si
|
||||
mostra come tale, riga per riga; le altre citazioni sono riquadri informativi.
|
||||
3. **Indirizzi.** L'aiuto è la pagina Blazor `/aiuto/{Pagina}` (nelle schede come ogni altra maschera); le immagini
|
||||
sono servite da `/aiuto/media/{percorso}` solo se il percorso è fra quelli copiati e ha un'estensione d'immagine.
|
||||
L'indirizzo `/help` della specifica resta come rinvio a `/aiuto`. Le immagini che puntano ai file del repository
|
||||
(`…/raw/branch/main/<percorso>`) si servono dalla copia locale; le altre restano sul web.
|
||||
4. **Una pagina per ogni maschera.** `HelpLinks` associa a ogni prefisso di percorso una pagina wiki; un test
|
||||
controlla che ogni pagina dell'applicazione e ogni voce di menu porti a una pagina che esiste, e che tutti i
|
||||
collegamenti fra pagine della wiki trovino la loro pagina.
|
||||
5. **Wiki online configurabile.** `KHAEMHAT_HELP_URL` (facoltativa, indirizzo assoluto `http(s)`) è la wiki aperta da
|
||||
*Apri nel wiki*; predefinita la wiki del progetto. *Segnala un problema* apre `…/issues/new` del repository della
|
||||
wiki quando l'indirizzo finisce con `/wiki/` (Gitea e GitHub), altrimenti non compare.
|
||||
6. **Notifiche lette per utente.** Una notifica personale (con destinatario) usa la sua colonna `read_at`. Una
|
||||
notifica per tutti resta una riga sola; chi la legge aggiunge una riga in `sys_notification_reads` (notifiche di
|
||||
sistema) o `notification_reads` (notifiche dell'azienda), con vincolo unico su notifica e utente. Il pannello
|
||||
mostra le ultime 100 notifiche dell'utente, filtri *Tutte* e *Non lette*, *Segna tutte come lette*; la campanella
|
||||
aggiorna il conteggio ogni minuto.
|
||||
7. **Ricerca a fornitori.** Pagine del menu e comandi si cercano subito nel browser. I record arrivano da
|
||||
`ISearchProvider` registrati nel contenitore e interrogati in parallelo da `GlobalSearchService` dopo una pausa di
|
||||
200 ms e almeno 2 caratteri: ognuno dichiara gli ambiti (tutto, `#` documenti, `@` persone), dà al massimo 8
|
||||
risultati, e uno lento (oltre 3 secondi) o in errore si scrive nel log e si salta. In M3 c'è il fornitore delle
|
||||
pagine dell'aiuto (titoli e sezioni); `#` e `@` dicono con quali moduli arriveranno i risultati.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- L'aiuto funziona senza Internet ed è sempre quello della versione installata; l'immagine cresce delle sole pagine
|
||||
e immagini citate (qualche MB).
|
||||
- Il convertitore copre solo la sintassi usata dalla wiki: una pagina nuova con sintassi diversa si vede come testo,
|
||||
e il test di conversione di tutte le pagine la segnala.
|
||||
- I moduli successivi aggiungono i propri fornitori di ricerca e le proprie sorgenti di notifiche senza toccare la
|
||||
shell.
|
||||
@@ -0,0 +1,53 @@
|
||||
# ADR 0024 - Componenti `Kh*`, pagine record e liste con un solo modello di richiesta
|
||||
|
||||
- **Stato:** accettata
|
||||
- **Data:** 2026-11-11
|
||||
- **Modifica:** SPEC §10.5, §10.6, §10.7, §19; milestone M3, issue #27, #28, #29
|
||||
|
||||
## Contesto
|
||||
|
||||
SPEC §10.7 elenca i componenti `Kh*` e §10.5 la struttura comune di documenti e anagrafiche (toolbar a icone,
|
||||
intestazione, schede, scorciatoie), ma non dice come si condividono il comportamento delle pagine che modificano un
|
||||
record, come una griglia legge 100.000 righe senza librerie esterne, né dove finiscono filtri e colonne salvati. Le
|
||||
maschere vere arrivano da M4 in poi: se ogni modulo scrivesse il proprio markup e le proprie query, toolbar,
|
||||
scorciatoie e filtri divergerebbero subito.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Una libreria, nomi dei mockup.** I componenti vivono in `Components/Ui` con prefisso `Kh` e riproducono le
|
||||
classi di `mockup.css` con gli stessi nomi semantici (`toolbar.icons`, `dochead`, `fgroup`, `grid`…). Le varianti
|
||||
che i mockup non hanno prendono un nome nuovo `kh-…`: una classe ha un solo significato (in 0.3.0 `.tl` e
|
||||
`.kh-choices` usati in due sensi hanno rotto il totale documento e le schede dei temi).
|
||||
2. **Campi all'italiana.** `KhTextBox`, `KhNumberBox`, `KhDateBox`, `KhSelect`, `KhCheck`, `KhSwitch`, `KhHotlink`
|
||||
dentro `KhForm`. Numeri con virgola e punto delle migliaia e calcolo `=…` (quattro operazioni e parentesi, parser
|
||||
in casa); date con `T`, `F`, `I`, `+n`, `-n` e cifre senza separatori (`ItalianDate`). Gli errori del servizio
|
||||
tornano per nome di campo, il riepilogo porta il focus sul campo.
|
||||
3. **Pagine record come classi base.** `RecordPage<T>` gestisce comandi standard, stato modificato sulla scheda della
|
||||
shell, conferme prima di scartare o eliminare e le scorciatoie di §10.5.7, attive solo quando la pagina è la
|
||||
scheda visibile. `DocumentPage<TDoc, TLine>` apre sulla scheda **Righe**; `MasterDataPage<T>` sui dati principali.
|
||||
I comandi sono `Func<Task>`: chi li ridefinisce chiama `StateHasChanged` se cambia lo stato della pagina.
|
||||
4. **`KhIconToolbar` su una riga.** I comandi meno usati scendono nel menu `…` invece di andare a capo.
|
||||
5. **Un modello di richiesta per tutte le liste.** `ListQuery` (testo cercato, filtri, ordinamento, pagina) e
|
||||
`ListPage<T>` (righe, totale, totali di colonna su tutte le righe selezionate). `ListFields<T>` descrive una volta i
|
||||
campi e li applica sia a una query del micro-ORM (SQL, `LIKE` senza distinzione di maiuscole) sia a righe in
|
||||
memoria (`InMemoryListSource`). I valori dei filtri sono testi invarianti, così un filtro si salva e si rilegge
|
||||
uguale.
|
||||
6. **`KhGrid` virtualizzata.** `Virtualize` di Blazor con righe alte 30 px e 20 righe di margine legge le pagine
|
||||
mentre si scorre (oppure a pagine con il pager); ordinamento, selezione, tastiera, modifica in riga, totali, menu
|
||||
di riga, esportazione CSV/XLSX con gli scrittori in casa (ADR 0021). Una ricerca nuova annulla quella in corso.
|
||||
7. **Salvati per utente.** Disposizione delle colonne di una griglia e filtri del radar (stella) sono impostazioni
|
||||
utente (ADR 0020) con chiave della lista; si eliminano dalla griglia e dal radar. La scheda *Layout salvati* del
|
||||
profilo arriva con le prime maschere che li usano (M4).
|
||||
8. **`KhRadar` intorno alla griglia**: ricerca, filtri rapidi, costruttore di filtri, filtri salvati; la stessa
|
||||
finestra serve la ricerca `F4` degli hotlink. `KhLinesGrid` è la griglia delle righe dei documenti, pensata per la
|
||||
tastiera (`Invio` cella successiva, `Ctrl+↓` nuova riga, `Ctrl+Canc` togli la riga).
|
||||
9. **Catalogo per gli sviluppatori.** `/sviluppo/componenti` e `/sviluppo/documento` (solo in ambiente di sviluppo)
|
||||
mostrano ogni componente con dati finti; gli screenshot della wiki si fanno da lì finché mancano le maschere vere.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Le maschere di M4 e seguenti sono composizione di componenti e di una `ListFields<T>`; un comportamento comune si
|
||||
corregge in un punto.
|
||||
- La griglia non usa librerie esterne e regge 100.000 righe in memoria; con PostgreSQL la paginazione è nella query.
|
||||
- I nomi di classe nuovi vanno controllati contro `mockup.css` e i fogli esistenti prima di introdurli.
|
||||
- Rinomina e scelta del filtro predefinito, e la scheda *Layout salvati* del profilo, restano da fare (M4).
|
||||
@@ -0,0 +1,51 @@
|
||||
# ADR 0025 - Pacchetto fiscale con parti obbligatorie e funzioni facoltative
|
||||
|
||||
- **Stato:** accettata
|
||||
- **Data:** 2026-11-11
|
||||
- **Modifica:** SPEC §1.10, §3, §21 (Fiscal e Validatori); ADR 0007; milestone M4, issue #37 e #40
|
||||
|
||||
## Contesto
|
||||
|
||||
ADR 0007 isola la fiscalità in `Khaemhat.Fiscal.Abstractions` (interfacce) e `Khaemhat.Fiscal.Italy`
|
||||
(implementazione). SPEC §21 elenca una dozzina di interfacce (`ITaxEngine`, `IEInvoiceFormat`, `IWithholdingRules`,
|
||||
`IIntrastatExporter`…), ma non dice come il pacchetto le espone né cosa succede a quelle che arrivano con milestone
|
||||
successive (FatturaPA in M9, bilancio CEE e Intrastat in M10). Inoltre non tutti i paesi hanno tutte le funzioni:
|
||||
un paese fuori dall'UE non ha Intrastat, non ovunque esistono le ritenute d'acconto.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Tre parti obbligatorie** come proprietà di `IFiscalPack`: `TaxCodes` (`ITaxCodeCatalog`: nature, codici IVA di
|
||||
base, regole del codice IVA), `TaxEngine` (`ITaxEngine`: arrotondamenti, castelletto, bollo) e `Calendar`
|
||||
(`IFiscalCalendar`: periodi, scadenze, festivi). Ogni paese ha imposte e scadenze.
|
||||
2. **Funzioni facoltative** chieste per tipo: `GetFeature<T>()` restituisce `null` se il paese (o la versione) non
|
||||
la offre; `Require<T>()` lancia `FiscalFeatureNotAvailableException` con paese e funzione. In 0.4.0 il pacchetto
|
||||
italiano offre `IEInvoiceFormat` (versione delle specifiche e code list FatturaPA), `IWithholdingRules`,
|
||||
`IFixedAssetRules` e `ITaxPaymentFormExporter` (codici tributo F24); `IFinancialStatementsSchema`,
|
||||
`IChartOfAccountsTemplate` e `IIntrastatExporter` sono definite ma arrivano con la milestone che le usa.
|
||||
3. **Le interfacce crescono con le milestone.** Ognuna contiene oggi solo ciò che serve e si può verificare
|
||||
(code list, regole, costanti); scrittori e lettori di file si aggiungono quando arriva la loro maschera.
|
||||
4. **Problemi come codici.** Le regole restituiscono `FiscalProblem` (campo, codice stabile come
|
||||
`fiscal.tax.nature-required`, errore o avviso); l'interfaccia traduce il codice con le risorse.
|
||||
5. **Risoluzione per paese.** `FiscalPackCatalog` raccoglie i pacchetti registrati e li trova per
|
||||
`company_profile.country` (senza distinzione di maiuscole). La composizione in `Hosting/KhaemhatServices.cs` è
|
||||
l'unico file fuori dal pacchetto che nomina `Khaemhat.Fiscal.Italy`: lo verifica `FiscalPackIsolationTests`, che
|
||||
controlla anche che le astrazioni non contengano nomi italiani.
|
||||
6. **Identificativi italiani nel pacchetto.** SPEC §21 mette `ItalianVatNumberValidator`, `FiscalCodeValidator`,
|
||||
`FiscalCodeCalculator` e `SdiRecipientCodeValidator` in `Khaemhat.Core`; il vincolo non negoziabile di SPEC §1.10
|
||||
("tutto ciò che è italiano sta in `Fiscal.Italy`") prevale: stanno nel pacchetto italiano dietro la funzione
|
||||
`ITaxIdentifierRules`, e la banca da IBAN dietro `IBankDirectory`. In `Core` restano i controlli internazionali:
|
||||
`IbanValidator` (mod 97 e lunghezza per paese), `EanValidator` (EAN-8, UPC-A, EAN-13, GTIN-14), `EmailValidator`.
|
||||
Il controllo VIES è `ViesClient` in `Infrastructure` (servizio REST della Commissione europea): un servizio che
|
||||
non risponde dà *non disponibile*, mai *non valida*.
|
||||
7. **Versione delle specifiche.** `FatturaPaCodeLists.SpecVersion` è **1.9.1** (pubblicata il 31 marzo 2026, in
|
||||
vigore dal 15 maggio 2026; non cambia le code list della 1.9, che aveva introdotto TD29 e ridefinito TD20). Va
|
||||
ricontrollata sul sito dell'Agenzia delle Entrate a ogni rilascio.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Un modulo che usa una funzione facoltativa decide cosa mostrare quando manca (per esempio nascondere Intrastat),
|
||||
invece di fallire alla prima chiamata.
|
||||
- Codici IVA di base, nature e code list del seed (#45) vengono dal pacchetto: c'è un'unica fonte.
|
||||
- La regola del bollo considera le nature N1, N2.x, N3.5, N3.6, N4 e N5; esportazioni, cessioni intracomunitarie,
|
||||
San Marino, operazioni assimilate, inversione contabile e N7 non contano. È da rivedere con i documenti di
|
||||
vendita (M5) se la normativa cambia.
|
||||
@@ -0,0 +1,53 @@
|
||||
# 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.
|
||||
*Aggiornato dall'ADR 0028:* province e comuni ISTAT, con i CAP di GeoNames, sono nei dati di base dalla
|
||||
versione `IT 2026.3`; le banche restano fuori.
|
||||
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`.
|
||||
@@ -0,0 +1,49 @@
|
||||
# ADR 0027 - Codici automatici con sequenze per chiave e compilazione a opzioni
|
||||
|
||||
- **Stato:** accettata
|
||||
- **Data:** 2026-11-11
|
||||
- **Modifica:** SPEC §11.12 (codici automatici, compilazione automatica); ADR 0025, 0026; milestone M4, issue #43
|
||||
|
||||
## Contesto
|
||||
|
||||
SPEC §11.12 chiede maschere di codice per archivio (`C{seq:000000}`, `{categoria}-{seq:0000}`, `L{anno}-{seq:0000}`…),
|
||||
progressivo globale o per categoria/anno, codice manuale ammesso o no, anteprima del prossimo codice e sequenze in
|
||||
`code_sequences` con assegnazione atomica. Non dice dove stanno le regole, come si chiamano le sequenze, cosa succede
|
||||
se il codice successivo è già stato scritto a mano o se la maschera cambia. Per la compilazione automatica elenca le
|
||||
opzioni senza dire chi le applica, e la banca dall'IBAN dipende da un elenco ABI che non è ancora nel repository
|
||||
(ADR 0026).
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Regole nelle impostazioni dell'azienda.** La maschera e il codice manuale di ogni archivio stanno in
|
||||
`company_settings` (`codes.<archivio>.mask`, `codes.<archivio>.manual`, `codes.items.unique-barcode`); un archivio
|
||||
senza impostazioni usa la maschera di SPEC. Gli archivi sono un elenco fisso in `CodeRuleService.Definitions`, con
|
||||
il modulo di licenza e la lunghezza massima del codice.
|
||||
2. **Una sequenza per chiave.** `code_sequences` ha una riga per chiave: il nome dell'archivio, più l'anno se la
|
||||
maschera contiene `{anno}`, più la categoria se contiene `{categoria}` (`customers`, `leads:2026`, `items:VALV`).
|
||||
La maschera non fa parte della chiave: **cambiare maschera continua lo stesso progressivo** e non riscrive i codici
|
||||
già assegnati.
|
||||
3. **Assegnazione nella transazione del salvataggio.** `CodeRuleService.AssignAsync` prende un lock applicativo sulla
|
||||
chiave (`AcquireLockAsync`, vuoto su SQLite dove le scritture sono già in fila), incrementa la sequenza e la scrive
|
||||
nella stessa unità di lavoro del record: se il salvataggio fallisce il numero torna libero, e due salvataggi
|
||||
contemporanei non ottengono mai lo stesso codice. Un codice già presente nella tabella (scritto a mano) viene
|
||||
saltato; dopo 1.000 salti il salvataggio è rifiutato.
|
||||
4. **Maschere controllate.** Letterali `A-Z 0-9 - _ / .` in maiuscolo, esattamente un `{seq}`, segnaposto
|
||||
`{anno}`/`{year}` e `{categoria}`/`{category}`, lunghezza minima entro quella della tabella. Gli errori sono codici
|
||||
(`codes.mask.*`) tradotti dall'interfaccia.
|
||||
5. **Compilazione a opzioni.** `AutoFillService` raccoglie le funzioni (comune da CAP e viceversa, codice fiscale dal
|
||||
pacchetto fiscale, VIES, banca da IBAN, data di consegna sul calendario del pacchetto) e le opzioni accese o spente
|
||||
(`autofill.<opzione>`); le maschere chiedono `IsOnAsync` prima di compilare. Il job dei cambi BCE salta le aziende
|
||||
che hanno spento l'opzione. Le opzioni sulle righe dei documenti e sui conti si applicano con i documenti (M5).
|
||||
6. **Banca da IBAN senza elenco ABI.** `IBankDirectory.ReadIban` restituisce sempre ABI e CAB di un IBAN italiano;
|
||||
nome e BIC arrivano dall'elenco quando c'è, altrimenti da un conto dell'azienda presso la stessa banca.
|
||||
7. **Modulo.** SPEC mette codici automatici e preferenze nel modulo AUTO, ma servono a ogni azienda (mockup 074, M4):
|
||||
stanno nel modulo CORE come le tabelle; le maschere degli archivi di CRM, Servizi e Cespiti si preparano anche
|
||||
senza il modulo.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Le anagrafiche (#41) e gli articoli (#42) chiamano `AssignAsync` quando il codice è vuoto e `CheckManual` quando è
|
||||
scritto; gli import li trattano allo stesso modo.
|
||||
- Una sequenza per categoria nasce al primo articolo della categoria; rinominare il codice di una categoria fa
|
||||
ripartire il suo progressivo, ma i codici già assegnati restano e quelli ripetuti vengono saltati.
|
||||
@@ -0,0 +1,53 @@
|
||||
# ADR 0028 - Province e comuni dall'elenco ISTAT e CAP da GeoNames nel pacchetto fiscale
|
||||
|
||||
- **Stato:** accettata
|
||||
- **Data:** 2026-11-12
|
||||
- **Modifica:** ADR 0026 punto 6; SPEC §11.1, §11.12, §14; milestone M4, issue #45
|
||||
|
||||
## Contesto
|
||||
|
||||
L'ADR 0026 rimandava province, comuni con CAP e banche ABI/CAB a file di dati con origine e licenza verificate,
|
||||
caricati dopo il via dell'utente. Il via è arrivato il 2026-11-12 per due fonti:
|
||||
|
||||
- l'**elenco dei codici dei comuni dell'ISTAT** (*Codici statistici delle unità amministrative territoriali*),
|
||||
pubblicato con licenza **CC BY 4.0** (note legali ISTAT). Il file CSV allo stesso indirizzo è fermo al gennaio 2024
|
||||
e ha ancora le 107 province precedenti al riordino della Sardegna; il file xlsx è aggiornato al **26/02/2026** e ha
|
||||
le **110 province** e i **7.894 comuni** in vigore;
|
||||
- il repository **comuni-json** per i CAP. La sua licenza non è MIT come si era ipotizzato: i comuni vengono
|
||||
dall'ISTAT (CC BY), ma per i CAP l'autore dichiara che le fonti non indicano una licenza e che al repository
|
||||
**non si applica nessuna licenza**. I dati sono fermi al 01/01/2020, prima delle fusioni di comuni successive.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Province e comuni nel pacchetto fiscale.** Sono dati italiani, quindi stanno in `Khaemhat.Fiscal.Italy`
|
||||
(`Data/province.csv`, `Data/comuni.csv`, risorse incorporate) dietro una nuova funzione facoltativa del pacchetto,
|
||||
`IPlaceDirectory` (province, comuni, origine). `BaseTablesSeeder` li aggiunge come il resto dei dati di base: solo
|
||||
i codici mancanti, mai modificando una riga già presente.
|
||||
2. **Formato ridotto.** Dal foglio ISTAT si tengono, per le province, sigla, denominazione e regione; per i comuni,
|
||||
codice catastale (il **codice** del comune, ADR 0026), denominazione in italiano, sigla della provincia, regione e
|
||||
codice ISTAT a 6 cifre. I file si rigenerano dal foglio ISTAT con lo stesso schema; ogni aggiornamento porta una
|
||||
nuova versione dei dati del pacchetto (da `IT 2026.2` a `IT 2026.3`).
|
||||
3. **Attribuzione.** L'origine (ISTAT, data dell'elenco, CC BY 4.0; GeoNames per i CAP) è scritta in
|
||||
`ItalianPlaces.ListSource`, nella wiki *Dati di base e di esempio* e in questo ADR.
|
||||
4. **Niente CAP da comuni-json.** Un file senza licenza non entra in un repository pubblico né nell'immagine
|
||||
distribuita, e i CAP del 2020 sarebbero comunque incompleti.
|
||||
5. **CAP da GeoNames.** Con un secondo via dell'utente (2026-11-12) i CAP vengono dall'elenco dei codici postali
|
||||
italiani di **GeoNames** (`IT.zip`, CC BY 4.0, attribuzione a www.geonames.org). GeoNames elenca località, non
|
||||
comuni: una riga si assegna a un comune quando nome (senza accenti, apostrofi e trattini, parte italiana dei nomi
|
||||
bilingui) e sigla della provincia coincidono con un solo comune; in Sardegna, dove le sigle sono cambiate, basta
|
||||
il nome entro la regione. Le frazioni con nome proprio restano fuori. Risultato: **7.750 comuni su 7.894** hanno i
|
||||
CAP (un CAP, una lista o intervalli come `10121-10156`); i 144 senza sono in gran parte comuni rinominati o nati da
|
||||
fusioni (ad esempio Sanremo, che GeoNames chiama *San Remo*) e si completano a mano o con l'**Importa CSV**.
|
||||
6. **Strumento di rigenerazione.** `tools/Khaemhat.PlacesTool` (non distribuito, solo framework) legge il foglio ISTAT
|
||||
e `IT.zip` e riscrive `Data/province.csv` e `Data/comuni.csv`; i file scaricati restano fuori dal repository.
|
||||
7. **Banche ABI/CAB** restano fuori finché non c'è una fonte aperta con licenza chiara (ADR 0026, ADR 0027 punto 6).
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Un'azienda nuova ha subito province, comuni e CAP: il calcolo del codice fiscale, la scelta del comune e la
|
||||
compilazione dal CAP funzionano senza caricare nulla. Le aziende esistenti li ricevono al primo avvio con la
|
||||
versione `IT 2026.3`, o con *Aggiorna tabelle di base*.
|
||||
- Il caricamento di base aggiunge circa 8.000 righe alla creazione dell'azienda: su SQLite resta sotto i due secondi;
|
||||
su PostgreSQL va misurato insieme alle altre misure di riferimento (`docs/DATA-MODEL.md` §6.1).
|
||||
- Un comune soppresso per fusione resta nella tabella di chi lo aveva già: va disattivato a mano. Le variazioni
|
||||
vanno annotate nel `CHANGELOG` quando si aggiorna l'elenco.
|
||||
@@ -0,0 +1,65 @@
|
||||
# ADR 0029 - Anagrafiche: un archivio per clienti, fornitori, prospect e lead
|
||||
|
||||
- **Stato:** accettata
|
||||
- **Data:** 2026-11-12
|
||||
- **Modifica:** SPEC §9 (modello dati delle anagrafiche), §11.2, §11.12, §14; milestone M4, issue #41
|
||||
|
||||
## Contesto
|
||||
|
||||
SPEC §11.2 descrive clienti, fornitori, prospect e lead con radar (mockup 012-013), scheda a gruppi (014-016),
|
||||
condizioni commerciali, dati fiscali e SDI, banche, contatti e indirizzi. §9 elenca le tabelle `parties` e i
|
||||
dettagli, ma lascia aperti alcuni punti: come si rappresenta un soggetto che è sia cliente sia fornitore, che codice
|
||||
riceve un prospect, quando si verifica il VIES, come si cancella un'anagrafica usata, come sono fatti i dati di
|
||||
esempio prima che esistano gli articoli e i documenti.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Un archivio, quattro tipi.** `parties` ha un `kind` (*Customer*, *Supplier*, *Prospect*, *Lead*) e un
|
||||
`subject_type` (*Company*, *Person*, *PublicAdministration*, *EuCompany*, *NonEuCompany*, *FlatRate*) che decide i
|
||||
controlli e i valori proposti. Un soggetto che è sia cliente sia fornitore è un **cliente** con
|
||||
`is_also_supplier`: compare in entrambi i radar con lo stesso codice cliente. Un fornitore che diventa cliente
|
||||
(azione *Converti in cliente*) diventa quindi `Customer` con `is_also_supplier = true` e tiene il suo codice.
|
||||
2. **Tre radar.** `/anagrafiche/clienti` (tipo *Customer*), `/anagrafiche/fornitori` (*Supplier* più i clienti che
|
||||
sono anche fornitori), `/anagrafiche/contatti` (*Prospect* e *Lead*, con il filtro rapido del tipo).
|
||||
3. **Codici.** Clienti e fornitori usano le maschere `customers` e `suppliers`; prospect e lead la maschera `leads`
|
||||
(`L{anno}-{seq:0000}`, ADR 0027). Alla conversione in cliente un prospect o un lead riceve il codice cliente e il
|
||||
vecchio resta in `previous_code`, così i riferimenti esterni (e-mail, appunti) si ritrovano con la ricerca.
|
||||
4. **Dettagli in tabelle proprie.** Indirizzi, contatti e conti sono liste (`party_addresses`, `party_contacts`,
|
||||
`party_bank_accounts`, al più un predefinito per tipo); condizioni di vendita, di acquisto e dati fiscali sono
|
||||
tabelle 1:1 (`party_sales_terms`, `party_purchase_terms`, `party_fiscal`) create insieme all'anagrafica. Il
|
||||
salvataggio riscrive la scheda intera in una transazione; lo storico registra testata e dettagli. La cancellazione
|
||||
dei dettagli è a cascata.
|
||||
5. **Controlli dal pacchetto fiscale.** Partita IVA, codice fiscale, codice destinatario e PEC passano da
|
||||
`ITaxIdentifierRules` (ADR 0025). Errori bloccanti: ragione sociale, P.IVA per un'impresa, identificativo per una
|
||||
PA, codice fiscale non valido, codice duplicato, paese incoerente con il tipo soggetto, dichiarazione d'intento
|
||||
senza numero o plafond. **Avvisi**, che non bloccano: P.IVA già usata da un'altra anagrafica (filiali, sedi
|
||||
distinte), privato senza codice fiscale. Per un cliente privato o estero, o per un'impresa con sola PEC, il codice
|
||||
destinatario mancante si compila con il valore del formato (`0000000`, `XXXXXXX`).
|
||||
6. **VIES al salvataggio.** Per un'impresa UE la verifica parte dopo il commit, solo se la P.IVA o il paese sono
|
||||
cambiati o non è mai stata verificata, e solo se la compilazione automatica *Vies* è accesa. L'esito (*valida*,
|
||||
*non valida*, *non verificata*) e la data restano sull'anagrafica; un VIES irraggiungibile non impedisce di
|
||||
salvare. L'azione *Verifica VIES* della scheda ripete la verifica. Le date sono `DateTime` in UTC, come nel
|
||||
resto del modello.
|
||||
7. **Cancellare o disattivare.** *Elimina* prova a cancellare; se il database rifiuta per riferimenti (documenti dalle
|
||||
prossime milestone), l'anagrafica viene **disattivata** e l'utente lo legge in un messaggio. Il radar disattiva e
|
||||
riattiva più righe insieme; le disattivate sono escluse per filtro iniziale.
|
||||
8. **Dati di esempio senza documenti.** `DemoPartiesSeeder` (seeder *Demo*, solo se le anagrafiche sono vuote) crea
|
||||
3 agenti e 21 anagrafiche con `is_demo`: 12 clienti che coprono tutti i tipi soggetto (PA con split payment,
|
||||
cliente bloccato, disattivato, anche fornitore, con dichiarazione d'intento), 5 fornitori (ritenuta, ENASARCO, UE),
|
||||
2 prospect e 2 lead. Partite IVA, codici fiscali e IBAN sono **numeri inventati ma formalmente validi** (cifra di
|
||||
controllo, mod 97), scritti come costanti e controllati da un test; nessuno appartiene a un soggetto reale per
|
||||
scelta, ma la coincidenza non si può escludere e per questo non si verificano sul VIES. Il volume completo della
|
||||
SPEC (40 clienti, 15 fornitori, documenti) arriva in M9 con `seed --demo`.
|
||||
9. **Rinviati.** `party_item_codes` (codici articolo del cliente o del fornitore) arriva con gli articoli (#42);
|
||||
fatturato, scaduto, fido usato e *Scheda 360°* con vendite (M5) e scadenzario (M9); il flag utente *vede solo i
|
||||
propri clienti* con i filtri per riga sui permessi, non ancora previsti in una milestone. Gli agenti di esempio non hanno `is_demo` perché la tabella
|
||||
degli agenti (ADR 0026) non ha la colonna: si rimuovono a mano.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Una sola tabella e una sola query per i tre radar; le condizioni commerciali si leggono con un join 1:1.
|
||||
- Il passaggio fornitore → cliente non cambia codice né documenti; il passaggio prospect → cliente cambia codice e
|
||||
lascia traccia in `previous_code` e nello storico.
|
||||
- I controlli fiscali italiani restano nel pacchetto; un altro paese porterà le sue regole senza toccare il servizio.
|
||||
- I dati di esempio non hanno numeri reali e restano validi per i controlli, quindi le prove automatiche li usano come
|
||||
casi realistici (ogni anagrafica di esempio supera `ValidateAsync`).
|
||||
@@ -0,0 +1,67 @@
|
||||
# ADR 0030 - Articoli e listini: prezzi con validità, listini derivati, ricerca del prezzo
|
||||
|
||||
- **Stato:** accettata
|
||||
- **Data:** 2026-11-12
|
||||
- **Modifica:** SPEC §9 (modello dati degli articoli), §11.2, §11.3, §14; milestone M4, issue #42
|
||||
|
||||
## Contesto
|
||||
|
||||
SPEC §11.2 descrive la scheda articolo (mockup 017) con UM alternative, codici alternativi, listini, fornitori,
|
||||
sostitutivi, giacenze e movimenti, e la griglia dei listini (mockup 018) con modifica in cella e aggiornamento
|
||||
massivo. §11.3 fissa l'ordine di ricerca del prezzo di una riga (netto cliente-articolo, listino del cliente o del
|
||||
documento, listino base, prezzo dell'articolo) e dice che i listini hanno validità, possono essere derivati e hanno
|
||||
regole di arrotondamento. Restavano aperti: dove stanno i prezzi netti dei clienti, come convivono prezzi vecchi e
|
||||
nuovi, quale listino è "il base", come si calcola un listino derivato, che cosa vede chi non può vedere i costi, che
|
||||
cosa si fa delle giacenze prima del magazzino (M6).
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Una tabella di prezzi.** `item_prices` tiene sia i prezzi di listino (`price_list_id`) sia i **prezzi netti**
|
||||
di un cliente (`party_id`): una riga ha esattamente uno dei due. Ogni riga ha un `valid_from`; il prezzo in vigore
|
||||
a una data è quello con l'**inizio più recente non successivo** alla data (una riga senza data vale sempre).
|
||||
Scrivere un prezzo con una data nuova aggiunge una riga, così i documenti già fatti e quelli datati prima
|
||||
ritrovano il prezzo di allora; scriverlo con la stessa data cambia la riga, e "nessun prezzo" la toglie. Un prezzo
|
||||
uguale a quello già in vigore non si riscrive.
|
||||
2. **Listino base.** `price_lists.is_base` marca il listino base (al più uno, regola della tabella); in mancanza
|
||||
vale quello con codice `BASE`, che i dati di base creano già marcato. La migrazione marca il `BASE` esistente.
|
||||
3. **Listini derivati.** Un listino con `base_price_list_id` senza un proprio prezzo per l'articolo prende il prezzo
|
||||
del listino di partenza alla stessa data, applica `markup_percent` (anche negativo) e arrotonda a `rounding_step`
|
||||
(al centesimo se zero). Il prezzo scritto nel listino derivato vince su quello calcolato. La derivazione si segue
|
||||
per al più cinque livelli. Il calcolo è in `PriceBook`, che lavora in memoria sui prezzi letti una volta.
|
||||
4. **Ricerca del prezzo** (`PriceListService.QuoteAsync`, usata dai documenti da M5): netto del cliente, poi il
|
||||
listino del documento o del cliente se valido alla data, poi il listino base, poi `items.price`. La risposta dice
|
||||
la **fonte** (`PriceSource`), che la riga del documento conserva. Gli sconti 1 e 2 del cliente si propongono come
|
||||
formula a cascata (`10+5`), **mai su un prezzo netto**.
|
||||
5. **Griglia dei listini.** Legge e scrive tutti i prezzi a **una data di validità** scelta in alto (oggi di
|
||||
default). Le celle modificate e quelle calcolate dall'aggiornamento massivo restano in sospeso, evidenziate, finché
|
||||
non si salva; l'anteprima dell'aggiornamento massivo (`PreviewAsync`) non scrive nulla. Le celle dei listini
|
||||
derivati senza prezzo proprio sono in corsivo.
|
||||
6. **Costi.** Costo standard, ultimo costo e costo medio si vedono solo con `items.cost.read`; per gli altri il
|
||||
servizio li restituisce vuoti e al salvataggio conserva quelli in archivio. Ultimo costo e costo medio non si
|
||||
scrivono dalla scheda: li aggiornano i carichi di magazzino (M6); fino ad allora li valorizzano solo i dati di
|
||||
esempio. Il margine è sul prezzo: (prezzo - costo) / prezzo.
|
||||
7. **Tipi e magazzino.** Solo le merci possono essere *gestite a magazzino*; servizi, spese, righe descrittive e
|
||||
cespiti non lo sono mai (il servizio lo corregge). Giacenze, impegni, movimenti e proposta di riordino arrivano
|
||||
con il magazzino (M6): la scheda li annuncia, i campi di riordino si compilano già.
|
||||
8. **Codici.** Il codice segue la maschera `items` (`{categoria}-{seq:0000}`, ADR 0027); se la maschera usa la
|
||||
categoria, la categoria è obbligatoria. Il codice a barre principale e quelli delle UM alternative hanno la
|
||||
verifica EAN; un codice a barre già usato da un altro articolo è un avviso, o un errore se le preferenze chiedono
|
||||
codici a barre univoci. La ricerca degli articoli trova esattamente anche i **codici alternativi** e, nei
|
||||
documenti di un'anagrafica, i **codici che quell'anagrafica usa** (`party_item_codes`).
|
||||
9. **Codici dell'anagrafica.** `party_item_codes` si gestisce nella scheda *Articoli e codici* dell'anagrafica e si
|
||||
salva con essa (un codice non si ripete per la stessa anagrafica); i controlli sono di `ItemService`.
|
||||
10. **Cancellazione.** Un articolo usato (sostitutivo di un altro, in documenti da M5) si disattiva invece di
|
||||
cancellarsi, come le anagrafiche (ADR 0029). Un cliente con prezzi netti non si cancella.
|
||||
11. **Dati di esempio.** `DemoItemsSeeder` crea 120 articoli fittizi di un grossista termoidraulico (SPEC §14) in dieci
|
||||
categorie, due listini derivati dal base (*Pubblico* +45% arrotondato a 0,10, *Rivenditori* -10%), un prezzo
|
||||
dell'anno precedente per lo storico, prezzi netti e codici di Rossi Impianti, fornitori abituali, UM alternative,
|
||||
codici alternativi e sostitutivi. I codici a barre hanno prefisso 200, riservato all'uso interno. Il comando
|
||||
`seed --demo [--scale N]` esegue prima i dati di base e poi quelli di esempio, ripetendo il catalogo N volte.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- I documenti (M5) chiamano `PriceListService.QuoteAsync` dentro la propria unità di lavoro e salvano prezzo e fonte;
|
||||
la stessa logica serve l'API (`items`, `price-lists`) e il tool MCP `search_items`.
|
||||
- Cambiare un prezzo non tocca i documenti esistenti; per correggere un prezzo sbagliato si riscrive con la stessa
|
||||
data, per un aumento si usa una data nuova.
|
||||
- Il magazzino (M6) aggiornerà `last_cost` e `average_cost` e aggiungerà le schede *Giacenze* e *Movimenti*.
|
||||
@@ -0,0 +1,69 @@
|
||||
# ADR 0031 - Import e export guidato: entità, tracciati, controlli come da scheda
|
||||
|
||||
- **Stato:** accettata
|
||||
- **Data:** 2026-11-12
|
||||
- **Modifica:** SPEC §11.7, §12.12, mockup 077; milestone M4, issue #44
|
||||
|
||||
## Contesto
|
||||
|
||||
SPEC §12.12 chiede una procedura guidata di import/export (CSV, XLSX, JSON) per anagrafiche, articoli, listini,
|
||||
giacenze iniziali, piano dei conti, saldi e partite di apertura, con mappatura delle colonne, validazione riga per
|
||||
riga, report degli errori e un tracciato proprio del piano dei conti (`codice;descrizione;livello;padre;natura;tipo;
|
||||
voce_cee;riclassifica;flag` e `khaemhat-coa.json`). Restavano aperti: dove sta la procedura, quali entità esistono già
|
||||
in M4, come si controllano le righe, che cosa succede ai codici esistenti o mancanti, i valori ammessi di `natura`,
|
||||
`tipo` e `flag`, come si legge un XLSX senza librerie esterne, chi può esportare.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Dove.** Pagina `/amministrazione/import-export` (voce *Import / export dati* sotto *Amministrazione*, visibile
|
||||
agli account di istanza), consegnata in M4 prima del resto dell'area (M13). Una persona dell'azienda la apre se ha
|
||||
il permesso di scrittura o di export di almeno un'entità.
|
||||
2. **Entità.** `IImportTarget` descrive un'entità: chiave, modulo di licenza, permesso di import e di export, colonne
|
||||
(con alias per l'abbinamento automatico), verifica, scrittura ed export. In M4: `clienti`, `fornitori`,
|
||||
`articoli`, `listini` (prezzi di listino e netti cliente), `giacenze-iniziali`, `piano-dei-conti`. Le ultime due
|
||||
**si verificano soltanto** finché non esistono i movimenti di magazzino (M6) e la contabilità (M7): la procedura
|
||||
prepara il file in anticipo, la scrittura arriva con il modulo. Saldi e partite di apertura arrivano con M7 e M9.
|
||||
3. **Le righe passano dalla scheda.** Clienti, fornitori e articoli si leggono per codice (o si creano con i valori
|
||||
proposti dalla scheda), si riempiono con le celle **non vuote** della riga e si controllano e salvano con
|
||||
`PartyService` e `ItemService`: stesse regole, stessi codici di errore, stesso storico. Una cella vuota lascia il
|
||||
valore che c'è. I codici di altre tabelle (categoria, pagamento, listino, agente, UM, IVA, deposito) devono
|
||||
esistere. I prezzi si scrivono con `PriceListService` in una sola transazione (stessa voce e stessa data:
|
||||
sostituisce; data nuova: aggiunge, come la griglia dei listini, ADR 0030).
|
||||
4. **Opzioni.** *Se il codice esiste*: aggiorna (predefinito) o salta la riga (avviso). *Codice mancante*: genera con
|
||||
le regole dei codici automatici (ADR 0027) o errore. Un codice scritto per un record nuovo rispetta la regola
|
||||
(*codice manuale ammesso*). Un codice ripetuto nel file è un errore dalla seconda riga; un codice di un'anagrafica di
|
||||
altro tipo è un errore. *Verifica P.IVA su VIES* chiama VIES durante l'import (spento: nessuna chiamata, qualunque
|
||||
sia l'opzione automatica dell'azienda). *Completa comune da CAP* propone comune e provincia da un CAP con un solo
|
||||
comune, o il CAP da un comune con un solo CAP, come avviso.
|
||||
5. **Esiti.** Ogni riga ha *OK*, *avviso* (importabile) o *errore* (esclusa), con colonna, codice del testo e valore.
|
||||
Si importano solo le righe senza errori; le altre finiscono nel **report errori** (CSV con riga, codice, colonna,
|
||||
esito, messaggio). L'esito dell'import va nel log, sezione *Sistema*.
|
||||
6. **Valori.** Numeri all'italiana (`1.234,56`) o con il punto decimale (`1234.56`, come li scrivono XLSX e JSON);
|
||||
date `gg/mm/aaaa`, ISO, `aaaammgg` o numero seriale del foglio; sì/no come `sì`, `x`, `1`, `VERO`, `true` e i
|
||||
contrari; le parole di una scelta senza badare a maiuscole, accenti e punteggiatura.
|
||||
7. **Piano dei conti.** Codice di 1-3 parti separate da punto (mastro, conto, sottoconto); `livello` è il numero di
|
||||
parti; `padre` è il codice senza l'ultima parte e deve essere nel file; la `natura` (`attivo`, `passivo`, `costo`,
|
||||
`ricavo`, `ordine`) si eredita dal padre e non può essere diversa; `tipo` è `generico`, `clienti`, `fornitori`,
|
||||
`banca`, `cassa`, `iva`, `erario` (nuovo `AccountType` in `Khaemhat.Core.Accounting`); `flag` è un insieme di lettere:
|
||||
`M` movimentabile (solo conti senza sottoconti), `I` rilevante IVA, `P` con partitario, `C` chiusura automatica,
|
||||
`X` disattivato. `khaemhat-coa.json` è un oggetto `{format, version, accounts, statementLines, journalTemplates,
|
||||
mappings}`: `accounts` ha le stesse colonne, le altre sezioni si contano e si importano in M7. Il controllo è puro
|
||||
(`ChartOfAccountsImportValidator`) perché M7 scriva esattamente ciò che accetta.
|
||||
8. **File.** CSV in UTF-8 (con o senza BOM) o, se non è UTF-8 valido, Windows-1252; separatore `;`, `,` o tabulazione
|
||||
dedotto dall'intestazione; l'apostrofo che l'export mette davanti al testo che inizia con `=`, `+`, `-`, `@` si
|
||||
toglie. XLSX: primo foglio letto da `XlsxReader` (System.IO.Compression e XmlReader, DTD vietate, stringhe
|
||||
condivise, celle in linea, numeri formattati come data restituiti come data). JSON: elenco di oggetti. Al più
|
||||
50.000 righe e 25 MB.
|
||||
9. **Export e modelli.** L'export scrive le stesse colonne dell'import in CSV (`;`, UTF-8 con BOM, numeri e date
|
||||
all'italiana), XLSX o JSON, così il file si corregge e si reimporta; richiede il permesso di export dell'entità e
|
||||
il flag utente *Può esportare dati*. Il **modello** è il file con le sole intestazioni (in JSON un oggetto con i
|
||||
valori vuoti).
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- L'import non ha regole proprie: ogni regola nuova di una scheda vale subito anche per i file.
|
||||
- Un file di un altro gestionale con codici propri richiede che la regola dei codici ammetta il codice manuale.
|
||||
- M6 e M7 aggiungono la scrittura di giacenze e piano dei conti senza cambiare tracciati né controlli; M7 e M9
|
||||
aggiungono saldi e partite come nuove entità.
|
||||
- Le righe si scrivono una alla volta (anagrafiche e articoli): un errore a metà non annulla le righe già scritte,
|
||||
che il report indica come create o aggiornate.
|
||||
@@ -1,7 +1,7 @@
|
||||
# Allegati e file
|
||||
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M3, completata in M5)
|
||||
> **Modulo di licenza:** CORE · **Permessi principali:** `attachments.delete`, permessi di lettura del documento · **Specifica:** SPEC §9.4
|
||||
> **Stato:** completa per M3 (invio e-mail e scanner con M5) · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.3.0 (milestone M3)
|
||||
> **Modulo di licenza:** CORE · **Permessi principali:** `attachments.read`, `attachments.write`, `attachments.delete` · **Specifica:** SPEC §9.4
|
||||
|
||||
Ogni documento e ogni anagrafica può avere **allegati**: file caricati dall'utente (l'ordine del cliente in PDF, una
|
||||
foto, un foglio di calcolo) e file **generati** da Khaemhat (PDF di stampa, XML FatturaPA, esportazioni, pacchetti
|
||||
@@ -12,9 +12,17 @@ ZIP). Gli allegati sono archiviati sul volume dei dati dell'istanza, con version
|
||||
Da qualunque documento: icona **Allegati** nella toolbar (con il numero degli allegati) oppure scheda **Allegati (n)**.
|
||||
Si apre il pannello laterale **Allegati e file generati**.
|
||||
|
||||
> **In questa versione** i documenti veri arrivano con le vendite (M5): pannello, anteprime e anteprima di stampa si
|
||||
> provano sul **documento di prova** degli sviluppatori (dal catalogo dei componenti `/sviluppo/componenti`,
|
||||
> solo in ambiente di sviluppo), che ha
|
||||
> tre file generabili (PDF, righe in CSV, righe in Excel). Mancano ancora **Invia** per e-mail e **Da scanner / foto**.
|
||||
|
||||

|
||||
*Mockup 024 — pannello laterale sopra la fattura: elenco degli allegati con azioni, Carica file, Da scanner / foto, Scarica tutto (ZIP) e sezione Genera file (anteprima ridotta).*
|
||||
|
||||

|
||||
*Khaemhat 0.3.0 — la scheda Allegati del documento di prova: tre file generati con le loro versioni, Carica file, Scarica tutto (ZIP) e Genera file.*
|
||||
|
||||
## Regole di base
|
||||
|
||||
- Un allegato appartiene **a un solo documento** (o a una sola anagrafica). Non esistono allegati "sciolti": se lo
|
||||
@@ -42,10 +50,12 @@ caricato o generato e quando, dimensione, versione, eventuale modello usato.
|
||||
|---|---|
|
||||
| occhio | **Anteprima** in app |
|
||||
| freccia in giù | **Scarica** |
|
||||
| busta | **Invia** per e-mail |
|
||||
| frecce circolari | **Rigenera**: crea una nuova versione del file generato |
|
||||
| cestino | **Elimina** (solo file non bloccati e con permesso) |
|
||||
| lucchetto | il file è bloccato |
|
||||
| busta | **Invia** per e-mail (con le vendite) |
|
||||
| frecce circolari | **Rigenera** (nella sezione *Genera file*): crea una nuova versione del file generato |
|
||||
| lucchetto | **Blocca**: da quel momento il file non si può più eliminare; accanto al nome indica un file bloccato |
|
||||
| cestino | **Sposta nel cestino** (solo file non bloccati e con permesso), dopo una conferma |
|
||||
|
||||
La casella **Versioni precedenti** mostra anche le versioni superate dei file generati (`v1` quando c'è già `v2`).
|
||||
|
||||
In fondo all'elenco:
|
||||
|
||||
@@ -79,19 +89,41 @@ Il pannello apre in app l'anteprima di:
|
||||
|
||||
| Formato | Come si vede |
|
||||
|---|---|
|
||||
| PDF | visualizzatore integrato |
|
||||
| Immagini | a dimensione piena con zoom |
|
||||
| XML | testo formattato e indentato |
|
||||
| CSV, XLSX | griglia |
|
||||
| PDF | visualizzatore PDF del browser, dentro la finestra di anteprima |
|
||||
| Immagini (JPEG, PNG, GIF, WebP) | adattate alla finestra |
|
||||
| XML, testo | testo così com'è |
|
||||
| CSV, XLSX | griglia (il primo foglio per gli XLSX) |
|
||||
|
||||
Gli altri formati si scaricano. Per i documenti c'è anche l'**anteprima di stampa** (`Ctrl+P`, mockup 025), descritta
|
||||
in [Vendite](Vendite).
|
||||

|
||||
*Khaemhat 0.3.0 — l'anteprima di un file Excel generato: il primo foglio come griglia.*
|
||||
|
||||
Dei file lunghi l'anteprima mostra l'inizio (200 righe, 200.000 caratteri) e lo dice. Gli altri formati si scaricano;
|
||||
PDF e immagini si aprono anche in una nuova finestra del browser.
|
||||
|
||||
### Anteprima di stampa
|
||||
|
||||

|
||||
*Mockup 025 — anteprima di stampa di una fattura in formato A4 (anteprima ridotta).*
|
||||
|
||||
`Ctrl+P` o l'icona **Stampa** del documento aprono in una scheda l'**anteprima di stampa**: il documento come foglio
|
||||
A4, con ingrandimento al 75, 100 o 125%. In alto:
|
||||
|
||||
- **Stampa** — la stampa del browser, che stampa solo il foglio (non menu e barre);
|
||||
- **Apri PDF** e **Scarica PDF** — il PDF prodotto da Khaemhat, senza salvarlo fra gli allegati;
|
||||
- **Salva come allegato** — salva il PDF fra gli allegati del documento come nuova versione.
|
||||
|
||||
Modello di stampa, copie e lingua arrivano con i documenti di vendita ([Vendite](Vendite)).
|
||||
|
||||

|
||||
*Khaemhat 0.3.0 — l'anteprima di stampa del documento di prova, con Stampa, Apri PDF, Scarica PDF, Salva come allegato e l'ingrandimento.*
|
||||
|
||||
## Cestino
|
||||
|
||||
Quando un documento viene cancellato, i suoi allegati non spariscono subito: restano nel **cestino dell'azienda per
|
||||
30 giorni** e possono essere recuperati in quel periodo; poi vengono eliminati definitivamente. La maschera di
|
||||
consultazione del cestino sarà definita in sviluppo.
|
||||
Quando un allegato viene spostato nel cestino, o quando viene cancellato il suo documento, il file non sparisce
|
||||
subito: resta nel **cestino dell'azienda per 30 giorni** e poi viene eliminato definitivamente da un'attività
|
||||
programmata. In fondo al pannello degli allegati, la sezione **Nel cestino** elenca i file del documento
|
||||
che sono nel cestino, con la data in cui saranno eliminati e il pulsante **Ripristina** (serve
|
||||
`attachments.delete`).
|
||||
|
||||
## Limiti e archiviazione
|
||||
|
||||
@@ -119,8 +151,10 @@ consultazione del cestino sarà definita in sviluppo.
|
||||
|
||||
## Permessi e licenza
|
||||
|
||||
Gli allegati sono nel modulo **CORE**. Chi può leggere un documento ne vede gli allegati; caricare richiede il
|
||||
permesso di modifica del documento; cancellare richiede `attachments.delete`. Gli allegati sono raggiungibili anche
|
||||
Gli allegati sono nel modulo **CORE**. Vedere e scaricare richiede `attachments.read`; caricare, generare e bloccare
|
||||
richiede `attachments.write`; spostare nel cestino e ripristinare richiede `attachments.delete`. Un utente aziendale
|
||||
vede solo gli allegati della propria azienda. I file si scaricano solo dopo l'accesso: un indirizzo copiato non
|
||||
funziona per chi non è collegato. Gli allegati sono raggiungibili anche
|
||||
dalle API (download e caricamento su un documento, modulo API; vedi [API e MCP](API-e-MCP)).
|
||||
|
||||
## Domande frequenti
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Anagrafiche
|
||||
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M4)
|
||||
> **Modulo di licenza:** CORE · **Permessi principali:** famiglia `parties.*` (`read`, `write`, `delete`, `export`; codici esatti definiti in sviluppo) · **Specifica:** SPEC §11.2, §11.12, §22
|
||||
> **Stato:** completa · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (milestone M4)
|
||||
> **Modulo di licenza:** CORE · **Permessi principali:** `parties.party.read` (consultare), `parties.party.write` (inserire, modificare, disattivare, convertire), `parties.party.delete` (eliminare) · **Specifica:** SPEC §11.2, §11.12, §22 · **Decisioni:** ADR 0029
|
||||
|
||||
Le **anagrafiche** sono l'archivio unico delle controparti dell'azienda: **clienti**, **fornitori**, **prospect** e
|
||||
**lead**. Un soggetto è registrato una volta sola; il suo *tipo* (cliente, fornitore…) dice come viene usato. Dalla
|
||||
@@ -10,8 +10,9 @@ codici che il cliente o il fornitore usa per i tuoi articoli.
|
||||
|
||||
## Dove si trova
|
||||
|
||||
Menu **Anagrafiche** → **Clienti**, **Fornitori**, **Contatti** (prospect e lead), **Categorie**. Nello stesso menu ci
|
||||
sono anche *Articoli* e *Listini* (vedi [Articoli e listini](Articoli-e-listini)).
|
||||
Menu **Anagrafiche** → **Clienti** (`/anagrafiche/clienti`), **Fornitori** (`/anagrafiche/fornitori`), **Contatti**
|
||||
(`/anagrafiche/contatti`, prospect e lead). Le categorie sono una tabella azienda (vedi [Tabelle azienda](Tabelle-azienda)).
|
||||
Nello stesso menu arriveranno *Articoli* e *Listini* (vedi [Articoli e listini](Articoli-e-listini)).
|
||||
|
||||
## Tipi di anagrafica
|
||||
|
||||
@@ -19,13 +20,15 @@ sono anche *Articoli* e *Listini* (vedi [Articoli e listini](Articoli-e-listini)
|
||||
|---|---|---|
|
||||
| **Cliente** | intestatario di preventivi, ordini, DDT e fatture di vendita | `C{seq:000000}` → `C000124` |
|
||||
| **Fornitore** | intestatario di ordini fornitore, DDT di carico, fatture di acquisto | `F{seq:000000}` → `F000032` |
|
||||
| **Prospect** | potenziale cliente già qualificato, senza documenti fiscali | assegnato alla conversione in cliente |
|
||||
| **Prospect** | potenziale cliente già qualificato, senza documenti fiscali | come i lead; alla conversione riceve il codice cliente |
|
||||
| **Lead** | contatto commerciale da qualificare (gestito con il CRM) | `L{anno}-{seq:0000}` → `L2026-0001` |
|
||||
|
||||
Lo stesso soggetto può essere sia cliente sia fornitore.
|
||||
Lo stesso soggetto può essere sia cliente sia fornitore: è un **cliente** con la casella *È anche fornitore* e compare
|
||||
in entrambi gli elenchi con lo stesso codice.
|
||||
|
||||
Il **tipo soggetto** (*azienda*, *privato*, *pubblica amministrazione*, *UE*, *extra-UE*, *forfettario*) determina
|
||||
i controlli e i valori proposti: codice destinatario SDI, split payment, bollo, partita IVA estera.
|
||||
Il **tipo soggetto** (*impresa italiana*, *privato*, *pubblica amministrazione*, *impresa UE*, *impresa extra-UE*,
|
||||
*forfettario*) determina i controlli e i valori proposti: codice destinatario SDI, split payment, partita IVA estera,
|
||||
paese della sede.
|
||||
|
||||
## Radar dei clienti
|
||||
|
||||
@@ -35,55 +38,68 @@ i controlli e i valori proposti: codice destinatario SDI, split payment, bollo,
|
||||

|
||||
*Mockup 012 — lo stesso radar con il menu espanso (anteprima ridotta).*
|
||||
|
||||
Il radar elenca le anagrafiche con le colonne **Codice**, **Ragione sociale**, **P.IVA / C.F.**, **Città**,
|
||||
**Pagamento**, **Listino**, **Agente**, **Fatturato** dell'anno, **Scaduto** (in rosso se presente) e **Stato**. Lo
|
||||
stato è un badge: *Attivo*, *Disabilitato*, *PA · split*, *UE*, *Extra-UE*, *Privato*, *Fido superato*.
|
||||

|
||||
*Khaemhat 0.4.0 — il radar dei clienti di esempio con i filtri Soggetto, Agente e Stato e lo stato di ogni anagrafica (impresa UE, PA con split payment, privato, bloccato, anche fornitore). Fatturato e scaduto arrivano con vendite e scadenzario.*
|
||||
|
||||
- Filtri: ricerca libera, **Tipo**, **Agente**, **Stato**, più filtri aggiunti come chip (ad esempio *Scaduto > 0*,
|
||||
*Provincia: CN, TO, AT*).
|
||||
- Il piede mostra i totali della selezione (ad esempio *1.284 clienti · 12 selezionati · fatturato visibile*).
|
||||
- Tasti: `F9` radar, `Invio` apri, `Spazio` seleziona. Con più righe selezionate si possono usare le azioni
|
||||
multiple (stampa, e-mail, esporta, **Disabilita**).
|
||||
Il radar elenca le anagrafiche con le colonne **Codice**, **Ragione sociale**, **P.IVA / C.F.**, **Città** (con la
|
||||
provincia), **Pagamento**, **Listino** (solo clienti), **Agente** e **Stato**; nei *Contatti* al posto di pagamento e
|
||||
listino c'è il **Tipo** (prospect o lead). Lo stato è un badge: *Attivo*, *Disattivato*, *Bloccato*, *PA · split*,
|
||||
*Privato*, *Impresa UE*, *Impresa extra-UE*, *Anche fornitore* / *Anche cliente*. Le colonne **Fatturato** e
|
||||
**Scaduto** del mockup arrivano con le vendite (M5) e lo scadenzario (M9).
|
||||
|
||||
- Ricerca libera su codice, nome, partita IVA, codice fiscale e città.
|
||||
- Filtri rapidi: **Tipo** (solo contatti), **Soggetto**, **Agente**, **Stato**; all'apertura sono mostrate solo le
|
||||
anagrafiche attive.
|
||||
- Tasti: `F9` radar, `Invio` o doppio clic apre la scheda, `Spazio` seleziona. Con più righe selezionate si usano
|
||||
**Disattiva** e **Riattiva**; l'esportazione CSV/XLSX è quella di tutti i radar.
|
||||
|
||||
## La scheda anagrafica
|
||||
|
||||

|
||||
*Mockup 014 — scheda cliente: azioni Scheda 360°, Nuovo documento, VIES, Attività CRM; intestazione con identità, condizioni e fatturato; scheda Dati principali a gruppi (anteprima ridotta).*
|
||||
|
||||
**Toolbar**: comandi standard a icone (vedi [Interfaccia e scorciatoie](Interfaccia-e-scorciatoie)) e le azioni
|
||||
contestuali **Scheda 360°** (visione completa: documenti, partite, attività CRM), **Nuovo documento**, **VIES**
|
||||
(verifica della partita IVA comunitaria), **Attività CRM**.
|
||||

|
||||
*Khaemhat 0.4.0 — la scheda di un cliente di esempio: intestazione con condizioni e agente, schede con i contatori e gruppi Identità, Sede legale, Recapiti, Classificazione e consensi.*
|
||||
|
||||
**Intestazione** in tre blocchi: a sinistra tipo (*Cliente*), codice e nome, stato (*Attivo*), uso del fido, data
|
||||
di inizio rapporto, agente; al centro ragione sociale con P.IVA, indirizzo, contatti e i chip delle condizioni
|
||||
(pagamento, listino e sconto, codice SDI, dichiarazione d'intento, scaduto); a destra il **fatturato** dell'anno con
|
||||
anno precedente, aperto e fido.
|
||||
**Toolbar**: comandi standard a icone (vedi [Interfaccia e scorciatoie](Interfaccia-e-scorciatoie)) e le azioni
|
||||
contestuali **Verifica VIES** (partita IVA comunitaria) e, per prospect, lead e fornitori, **Converti in cliente**;
|
||||
nel menu `…` **Disattiva** o **Riattiva**. *Scheda 360°*, *Nuovo documento* e *Attività CRM* arrivano con vendite e
|
||||
CRM.
|
||||
|
||||
**Intestazione**: tipo, codice e nome, stato, data di inizio rapporto e agente; i chip delle condizioni (pagamento,
|
||||
listino, agente, esito VIES, split payment). Il blocco del **fatturato** arriva con le vendite (M5).
|
||||
|
||||
**Schede**:
|
||||
|
||||
| Scheda | Contenuto |
|
||||
|---|---|
|
||||
| **Dati principali** | gruppi *Identità*, *Sede legale*, *Classificazione e note* |
|
||||
| **Indirizzi** | destinazioni diverse (cantieri, sedi di consegna, indirizzo di fatturazione) |
|
||||
| **Contatti** | persone di riferimento con ruolo, telefono, e-mail |
|
||||
| **Condizioni commerciali** | condizioni di vendita (clienti) o di acquisto (fornitori) |
|
||||
| **Fiscale e SDI** | fatturazione elettronica, regime IVA, ritenute, dichiarazione d'intento, identificativi |
|
||||
| **Banche** | conti correnti della controparte (IBAN) |
|
||||
| **Articoli e codici** | codici con cui la controparte identifica i tuoi articoli |
|
||||
| **Dati principali** | gruppi *Identità*, *Dati di nascita* (privati), *Sede legale*, *Recapiti*, *Classificazione e consensi* |
|
||||
| **Indirizzi** | destinazioni diverse (destinazione merce, fatturazione, cantiere o sede operativa), una predefinita per tipo |
|
||||
| **Contatti** | persone di riferimento con ruolo, telefono, cellulare, e-mail; un contatto principale |
|
||||
| **Condizioni** | condizioni di vendita (clienti), di acquisto (fornitori, e clienti che sono anche fornitori), conti contabili |
|
||||
| **Fiscale e SDI** | fatturazione elettronica, regime IVA, ritenute e casse, dichiarazione d'intento, identificativi |
|
||||
| **Banche** | conti correnti della controparte (IBAN), uno predefinito |
|
||||
| **Articoli e codici** | i codici con cui il cliente o il fornitore identifica i tuoi articoli: codice, articolo (ricerca F4), descrizione; nei documenti di quell'anagrafica la ricerca degli articoli trova anche questi codici (vedi [Articoli e listini](Articoli-e-listini)) |
|
||||
| **Note e allegati** | note libere e file allegati all'anagrafica |
|
||||
| **CRM** | lead, opportunità e attività collegate (con modulo CRM) |
|
||||
| **Storico** | modifiche registrate: chi, quando, cosa |
|
||||
|
||||
Una scheda con errori mostra il numero degli errori nell'etichetta; le liste mostrano quante righe contengono. La
|
||||
scheda *CRM* arriva con il modulo CRM. Nella scheda *Articoli e codici* lo stesso codice non si ripete per la stessa
|
||||
anagrafica.
|
||||
|
||||
### Dati principali
|
||||
|
||||
| Gruppo | Campi |
|
||||
|---|---|
|
||||
| **Identità** | Codice (automatico), Tipo, Tipo soggetto, **Ragione sociale** *, Denominazione fiscale, **Partita IVA** *, Codice fiscale, REA, Categoria |
|
||||
| **Sede legale** | Indirizzo, N., CAP, Comune, Provincia, Paese, Telefono, E-mail, PEC, Sito |
|
||||
| **Classificazione e note** | Agente, Lingua, Valuta, Attivo, Privacy accettata, Marketing, Note |
|
||||
| **Identità** | Codice (automatico), Codice precedente, Tipo, Tipo soggetto, **Ragione sociale** *, Denominazione per i documenti, **Partita IVA** *, Codice fiscale, REA, Categoria |
|
||||
| **Dati di nascita** | Data, Sesso, Comune di nascita (codice catastale) |
|
||||
| **Sede legale** | Indirizzo, Civico, CAP, Comune, Provincia, Paese |
|
||||
| **Recapiti** | Telefono, Cellulare, E-mail, PEC, Sito web |
|
||||
| **Classificazione e consensi** | Agente, Lingua, Valuta, In anagrafica dal, Informativa privacy accettata, Consenso al marketing |
|
||||
|
||||
Per i privati si inseriscono nome e cognome al posto della ragione sociale. Digitando il **CAP** Khaemhat propone
|
||||
comune, provincia e regione; il **codice fiscale** di una persona fisica può essere calcolato dai dati anagrafici.
|
||||
Per i privati si inseriscono cognome e nome al posto della ragione sociale. Digitando il **CAP** Khaemhat propone
|
||||
comune e provincia (se il CAP è di più comuni li elenca e si sceglie); digitando il comune propone il CAP. Il
|
||||
**codice fiscale** di un privato si calcola con il pulsante accanto al campo da cognome, nome e dati di nascita.
|
||||
|
||||
### Fiscale e SDI
|
||||
|
||||
@@ -93,7 +109,8 @@ comune, provincia e regione; il **codice fiscale** di una persona fisica può es
|
||||
| Gruppo | Campi |
|
||||
|---|---|
|
||||
| **Fatturazione elettronica** | **Codice destinatario** *, PEC destinatario, tipo destinatario, formato (FPR12 privati / FPA12 PA), riferimento amministrazione, *Allega PDF di cortesia*, *Invia copia via e-mail all'emissione* |
|
||||
| **Regime IVA e ritenute** | *Split payment* (art. 17-ter), *Reverse charge* predefinito, codice IVA predefinito, esigibilità, *Soggetto a ritenuta*, cassa previdenza, bollo (a carico del cliente o dell'azienda), regime |
|
||||
| **Regime IVA** | *Scissione dei pagamenti* (art. 17-ter), *Inversione contabile*, codice IVA abituale, esigibilità (I, D, S), bollo a carico del cliente |
|
||||
| **Ritenute e casse** | *Ritenuta d'acconto* con aliquota e causale, cassa previdenziale con aliquota, *ENASARCO* |
|
||||
| **Dichiarazione d'intento** (esportatore abituale) | Attiva, Numero, Data, Protocollo AdE, Codice IVA (non imponibile art. 8 c.1 lett. c, natura N3.5), **Plafond**, **Utilizzato**, **Residuo**, Validità |
|
||||
| **Identificativi** | GLN, EORI, nostro codice presso il cliente |
|
||||
|
||||
@@ -101,21 +118,22 @@ comune, provincia e regione; il **codice fiscale** di una persona fisica può es
|
||||
|
||||
| Controparte | Valore |
|
||||
|---|---|
|
||||
| Azienda italiana (B2B) | 7 caratteri, comunicati dal cliente (in alternativa la PEC) |
|
||||
| Azienda italiana (B2B) | 7 caratteri, comunicati dal cliente; con la sola PEC si usa `0000000` (proposto) |
|
||||
| Pubblica amministrazione | **codice IPA** dell'ufficio, 6 caratteri |
|
||||
| Estero (UE ed extra-UE) | `XXXXXXX` |
|
||||
| Privato | `0000000` |
|
||||
| Estero (UE ed extra-UE) | `XXXXXXX` (proposto se vuoto) |
|
||||
| Privato | `0000000` (proposto se vuoto) |
|
||||
|
||||
**Dichiarazione d'intento**: quando il cliente è esportatore abituale, le fatture usano il codice IVA non
|
||||
imponibile collegato e riportano numero e protocollo della dichiarazione; l'utilizzato si aggiorna con le fatture e
|
||||
il residuo avvisa quando il plafond sta per esaurirsi (il mockup mostra un avviso all'80% e un blocco al 100%; le
|
||||
soglie definitive saranno fissate in sviluppo). Il registro completo delle dichiarazioni ricevute ed emesse è nel
|
||||
soglie si fissano con la fatturazione, M5). Una dichiarazione attiva richiede numero e plafond. Il registro completo delle dichiarazioni ricevute ed emesse è nel
|
||||
modulo Fatturazione elettronica (vedi [Fatturazione elettronica](Fatturazione-elettronica)).
|
||||
|
||||
### Condizioni di vendita (clienti)
|
||||
|
||||
Listino, sconti, pagamento, banca d'appoggio per le RiBa, agente, vettore, porto, deposito, **fido** e **blocco**,
|
||||
raggruppamento dei DDT in fattura differita, giorno di fatturazione, invio dei documenti per e-mail o PEC. Queste
|
||||
Listino, due sconti, pagamento, nostra banca d'appoggio per le RiBa, vettore, porto, deposito, **fido** e **ordini
|
||||
bloccati**, raggruppamento dei DDT in fattura differita, giorno di fatturazione, invio dei documenti per e-mail o PEC
|
||||
con l'indirizzo dedicato. Queste
|
||||
condizioni vengono proposte automaticamente nei documenti del cliente (vedi [Vendite](Vendite)).
|
||||
|
||||
Il **fido** è l'esposizione massima ammessa: quando viene superato, o se il cliente ha scaduto, gli ordini
|
||||
@@ -128,13 +146,12 @@ segnalano il blocco, superabile solo da chi ha il permesso di forzarlo.
|
||||
|
||||
| Gruppo | Campi |
|
||||
|---|---|
|
||||
| **Condizioni di acquisto** | Pagamento, Valuta, **Lead time** (giorni), **Minimo d'ordine**, Sconto %, Porto, Registro IVA acquisti, Conto di costo predefinito |
|
||||
| **Ritenute e contributi** | *Professionista (ritenuta d'acconto)*, aliquota ritenuta, causale, cassa previdenza, *Agente ENASARCO*, *Regime forfettario* (niente IVA, bollo), *Reverse charge* (es. subappalto edile) |
|
||||
| **Banca e contatti** | IBAN, BIC, referente, e-mail per gli ordini |
|
||||
| **Condizioni di acquisto** | Pagamento, **Tempo di consegna** (giorni), **Ordine minimo**, Sconto %, Porto, Registro IVA, Conto di costo, E-mail per gli ordini |
|
||||
| **Ritenute e casse** (scheda *Fiscale e SDI*) | *Ritenuta d'acconto* con aliquota e causale, cassa previdenziale, *ENASARCO*; il tipo soggetto *Forfettario* per chi non applica l'IVA |
|
||||
| **Banche** e **Contatti** | IBAN, BIC, banca, ABI e CAB; referenti |
|
||||
|
||||
L'intestazione del fornitore mostra il totale **acquisti** dell'anno, l'aperto, lo scaduto e gli ordini aperti; tra
|
||||
le schede *Articoli forniti* elenca gli articoli che il fornitore ti vende. Il lead time viene usato per calcolare
|
||||
le date di consegna previste negli ordini fornitore.
|
||||
Il tempo di consegna servirà a calcolare le date previste negli ordini fornitore. Il totale **acquisti**, l'aperto,
|
||||
lo scaduto e gli *Articoli forniti* del mockup arrivano con acquisti e articoli.
|
||||
|
||||
## Come si usa
|
||||
|
||||
@@ -142,41 +159,54 @@ le date di consegna previste negli ordini fornitore.
|
||||
|
||||
1. **Anagrafiche → Clienti**, premi **Nuovo cliente** (o `Ctrl+N`).
|
||||
2. Scegli il **tipo soggetto**. Il codice viene assegnato automaticamente al salvataggio (vedi più sotto).
|
||||
3. Inserisci ragione sociale e partita IVA: al salvataggio Khaemhat controlla la partita IVA e, se è comunitaria,
|
||||
3. Inserisci ragione sociale e partita IVA: al salvataggio Khaemhat controlla la partita IVA e, per un'impresa UE,
|
||||
la verifica sul servizio **VIES** (l'esito resta salvato con la data).
|
||||
4. Compila la sede legale partendo dal CAP.
|
||||
5. In **Fiscale e SDI** inserisci il codice destinatario o la PEC.
|
||||
6. In **Condizioni commerciali** imposta pagamento, listino, agente e fido.
|
||||
7. **Salva** (`Ctrl+S`).
|
||||
6. In **Condizioni** imposta pagamento, listino e fido; l'agente è nei dati principali.
|
||||
7. **Salva** (`Ctrl+S`). Gli errori portano alla scheda del primo campo da correggere; gli **avvisi** (ad esempio
|
||||
una partita IVA già usata da un'altra anagrafica, che va bene per filiali e sedi distinte) non bloccano e compaiono
|
||||
in un messaggio dopo il salvataggio.
|
||||
|
||||
Un lead si crea da **Contatti → Nuovo lead**, un prospect da **Contatti → Nuovo prospect**.
|
||||
|
||||
### Convertire un lead o un prospect in cliente
|
||||
|
||||
Dalla scheda del lead o del prospect usa l'azione di conversione: il soggetto diventa **cliente**, riceve il codice
|
||||
cliente secondo la maschera automatica e mantiene la propria storia (attività, opportunità). Con il modulo CRM la
|
||||
conversione si avvia anche dalla maschera dei lead (vedi [CRM](CRM)).
|
||||
Dalla scheda del lead o del prospect usa **Converti in cliente**: il soggetto diventa **cliente**, riceve il codice
|
||||
cliente secondo la maschera automatica e conserva il vecchio come **codice precedente** (si trova ancora con la
|
||||
ricerca), insieme a storico e allegati. Con il modulo CRM la conversione si avvierà anche dalla maschera dei lead
|
||||
(vedi [CRM](CRM)).
|
||||
|
||||
Su un **fornitore** la stessa azione lo rende anche cliente: il codice non cambia e l'anagrafica compare in entrambi
|
||||
gli elenchi.
|
||||
|
||||
### Disabilitare invece di cancellare
|
||||
|
||||
Un'anagrafica che compare in almeno un documento **non si cancella**: si **disabilita** (azione **Disabilita** nel
|
||||
radar o nella scheda). Un'anagrafica disabilitata non viene più proposta nei nuovi documenti né nelle ricerche
|
||||
predefinite, ma resta consultabile con i suoi documenti. Si può cancellare solo un'anagrafica mai usata.
|
||||
Un'anagrafica che compare in almeno un documento **non si cancella**: si **disattiva** (azione **Disattiva** nel
|
||||
radar o nel menu della scheda). Un'anagrafica disattivata non viene più proposta nei nuovi documenti né nelle
|
||||
ricerche predefinite, ma resta consultabile con i suoi documenti. Se si prova a eliminare un'anagrafica usata,
|
||||
Khaemhat la disattiva e lo dice. Si cancella davvero solo un'anagrafica mai usata.
|
||||
|
||||
## Validazioni
|
||||
|
||||
| Dato | Controllo |
|
||||
|---|---|
|
||||
| **Partita IVA italiana** | 11 cifre con cifra di controllo |
|
||||
| **Ragione sociale** | obbligatoria (per i privati cognome e nome) |
|
||||
| **Partita IVA italiana** | 11 cifre con cifra di controllo; obbligatoria per un'impresa; un doppione è un avviso |
|
||||
| **Partita IVA UE** | verifica sul servizio VIES della Commissione europea; esito e data salvati |
|
||||
| **Codice fiscale** | 16 caratteri con carattere di controllo (11 cifre per le società); calcolabile dai dati anagrafici |
|
||||
| **Codice fiscale** | 16 caratteri con carattere di controllo (11 cifre per le società); per un privato senza codice fiscale un avviso |
|
||||
| **Pubblica amministrazione** | serve il codice fiscale o la partita IVA |
|
||||
| **Paese** | nella tabella dei paesi; un'impresa UE ha sede in un altro paese dell'Unione, impresa italiana, privato, PA e forfettario nel paese dell'azienda |
|
||||
| **IBAN** | struttura e controllo modulo 97 |
|
||||
| **Codice destinatario** | 7 caratteri; 6 per la PA (codice IPA); `XXXXXXX` estero; `0000000` privato |
|
||||
| **E-mail / PEC** | formato dell'indirizzo |
|
||||
| **Codice** | unico fra tutte le anagrafiche |
|
||||
|
||||
## Codici automatici
|
||||
|
||||
Il codice di clienti, fornitori e lead è assegnato automaticamente secondo le maschere impostate in
|
||||
Il codice di clienti, fornitori, prospect e lead è assegnato automaticamente secondo le maschere impostate in
|
||||
*Tabelle azienda → Preferenze e codici automatici* (vedi [Tabelle azienda](Tabelle-azienda)): `C{seq:000000}` per i
|
||||
clienti, `F{seq:000000}` per i fornitori, `L{anno}-{seq:0000}` per i lead. La maschera mostra l'anteprima del
|
||||
clienti, `F{seq:000000}` per i fornitori, `L{anno}-{seq:0000}` per prospect e lead. La maschera mostra l'anteprima del
|
||||
prossimo codice; un'impostazione decide se è ammesso scrivere un **codice manuale**. Il progressivo è assegnato in
|
||||
modo atomico: due utenti che salvano insieme non ottengono mai lo stesso codice.
|
||||
|
||||
@@ -184,25 +214,31 @@ modo atomico: due utenti che salvano insieme non ottengono mai lo stesso codice.
|
||||
|
||||
| Quando | Khaemhat propone |
|
||||
|---|---|
|
||||
| inserisci il CAP | comune, provincia e regione |
|
||||
| inserisci i dati anagrafici di una persona | il codice fiscale |
|
||||
| inserisci il CAP | comune e provincia (scelta fra più comuni) |
|
||||
| inserisci il comune | CAP e provincia |
|
||||
| premi *Calcola* accanto al codice fiscale di un privato | il codice fiscale |
|
||||
| salvi una P.IVA UE | la verifica VIES |
|
||||
| inserisci un IBAN | banca e BIC (tabella ABI) |
|
||||
| crei un documento per il cliente | destinazione, listino, pagamento, agente |
|
||||
| inserisci un IBAN | ABI, CAB e banca (dalla tabella delle banche, quando caricata) |
|
||||
| lasci vuoto il codice destinatario di un privato o di un estero | `0000000` o `XXXXXXX` |
|
||||
| crei un documento per il cliente | destinazione, listino, pagamento, agente (con le vendite, M5) |
|
||||
|
||||
Le singole compilazioni si attivano o disattivano in *Tabelle azienda → Preferenze e codici automatici*.
|
||||
|
||||
## Permessi e licenza
|
||||
|
||||
Le anagrafiche fanno parte del modulo **CORE**. Il flag utente *vede solo i propri clienti* limita un agente ai
|
||||
clienti a lui assegnati. Le schede *CRM* e *Scheda 360°* mostrano i dati CRM solo con il modulo **CRM** attivo; il
|
||||
Le anagrafiche fanno parte del modulo **CORE**: `parties.party.read` per consultare, `parties.party.write` per
|
||||
inserire, modificare, disattivare e convertire, `parties.party.delete` per eliminare. Il flag utente *vede solo i
|
||||
propri clienti*, che limiterà un agente ai clienti assegnati, non è ancora attivo. Le schede *CRM* e *Scheda 360°* mostrano i dati CRM solo con il modulo **CRM** attivo; il
|
||||
registro delle dichiarazioni d'intento richiede **EINV**. Ogni modifica è registrata nello **Storico**.
|
||||
|
||||
## Domande frequenti
|
||||
|
||||
- **Non riesco a cancellare un cliente.** Ha documenti collegati: disabilitalo.
|
||||
- **La verifica VIES non risponde.** Il servizio europeo può essere temporaneamente non disponibile: salva
|
||||
comunque e ripeti la verifica con l'azione **VIES** più tardi.
|
||||
comunque e ripeti la verifica con l'azione **Verifica VIES** più tardi.
|
||||
- **Ho convertito un prospect e il vecchio codice è sparito.** È nel campo *Codice precedente* e la ricerca lo trova.
|
||||
- **Un fornitore compare anche fra i clienti.** È un cliente con *È anche fornitore*: un solo soggetto, un solo
|
||||
codice.
|
||||
- **Un cliente privato non ha codice destinatario.** È corretto: si usa `0000000` e la fattura resta disponibile
|
||||
nell'area riservata del cliente sul sito dell'Agenzia delle Entrate; consegnagli comunque una copia di cortesia.
|
||||
|
||||
|
||||
@@ -1,153 +1,212 @@
|
||||
# Articoli e listini
|
||||
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M4)
|
||||
> **Modulo di licenza:** CORE · **Permessi principali:** famiglia `items.*` (es. `items.cost.read` per vedere i costi) · **Specifica:** SPEC §11.2, §11.3 (prezzi), §11.6
|
||||
> **Stato:** completa · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (milestone M4; giacenze e costi dai movimenti con il magazzino, M6)
|
||||
> **Modulo di licenza:** CORE · **Permessi principali:** `items.item.read` (consultare), `items.item.write` (inserire, modificare, disattivare, prezzi), `items.item.delete` (eliminare), `items.cost.read` (vedere costi e margini) · **Specifica:** SPEC §11.2, §11.3 (prezzi), §14 · **Decisioni:** ADR 0030
|
||||
|
||||
L'**articolo** descrive ciò che l'azienda vende o compra: merci, servizi, spese, righe di solo testo e cespiti.
|
||||
Nella scheda articolo stanno codici, unità di misura, IVA, conti contabili, prezzi e costi, i parametri di
|
||||
**riordino** e le **giacenze** per deposito in tempo reale. I **listini** raccolgono i prezzi di vendita per gruppi di
|
||||
clienti e si aggiornano anche in modo massivo.
|
||||
L'**articolo** descrive ciò che l'azienda vende o compra: merci, servizi, spese, righe descrittive e cespiti. Nella
|
||||
scheda articolo stanno codici, unità di misura, IVA, conti, prezzi e costi e i parametri di **riordino**. I
|
||||
**listini** raccolgono i prezzi di vendita per gruppi di clienti, con una data di validità, e si aggiornano anche in
|
||||
modo massivo.
|
||||
|
||||
## Dove si trova
|
||||
|
||||
Menu **Anagrafiche → Articoli** e **Anagrafiche → Listini**; le categorie articolo sono in **Anagrafiche →
|
||||
Categorie**.
|
||||
Menu **Anagrafiche → Articoli** e **Anagrafiche → Listini**. Le **categorie articolo**, le **intestazioni dei
|
||||
listini** e le **unità di misura** sono tabelle dell'azienda (vedi [Tabelle azienda](Tabelle-azienda)).
|
||||
|
||||
## L'elenco degli articoli
|
||||
|
||||
L'elenco è una griglia con ricerca per codice, descrizione, codice a barre (anche alternativo) e marca, e le colonne
|
||||
codice, descrizione, tipo, categoria, UM, **prezzo base**, **costo medio** (solo con il permesso di vedere i costi),
|
||||
magazzino e stato. I filtri rapidi scelgono tipo, categoria, articoli a magazzino e **attivi / disattivati**. Dalla
|
||||
toolbar si disattivano e riattivano gli articoli selezionati e si apre la griglia dei listini.
|
||||
|
||||

|
||||
*Khaemhat 0.4.0 — il radar dei 120 articoli di esempio con categoria, UM, marca, tipo, costo medio e prezzo base.*
|
||||
|
||||
## La scheda articolo
|
||||
|
||||

|
||||
*Mockup 017 — scheda articolo: azioni Movimenti, Etichette, Proposta riordino; intestazione con disponibilità e costo medio; gruppi Identità, Codici UM e fisco, Prezzi e costi, Riordino; giacenze per deposito (anteprima ridotta).*
|
||||
*Mockup 017 — scheda articolo: intestazione con prezzo e costo medio; gruppi Identità, Codici UM e fisco, Prezzi e costi, Riordino; giacenze per deposito (anteprima ridotta).*
|
||||
|
||||
**Toolbar**: comandi standard e le azioni contestuali **Movimenti** (movimenti di magazzino dell'articolo),
|
||||
**Etichette** (stampa etichette), **Proposta riordino**.
|
||||

|
||||
*Khaemhat 0.4.0 — la scheda di un articolo di esempio con prezzo base, costo medio e margine nell'intestazione e le schede UM, codici alternativi, listini, fornitori e sostitutivi.*
|
||||
|
||||
**Intestazione**: a sinistra codice, avvisi (ad esempio *Sotto punto di riordino*), EAN e categoria; al centro
|
||||
descrizione, UM, marca, peso, nomenclatura NC8, aliquota IVA e chip con prezzi di listino, disponibilità
|
||||
(*Disp. · Imp. · Ord.*), fornitore abituale, scorta minima e punto di riordino; a destra il **costo medio** con
|
||||
ultimo costo, costo standard e margine.
|
||||
**Intestazione**: codice, descrizione, tipo e categoria; a destra il **prezzo base in vigore oggi** con costo medio,
|
||||
ultimo costo, costo standard e **margine** (i costi solo con il permesso `items.cost.read`).
|
||||
|
||||
**Schede**: *Dati principali*, *UM alternative*, *Codici alternativi*, *Listini*, *Fornitori*, *Sostitutivi*,
|
||||
*Movimenti*, *Immagini e allegati*.
|
||||
**Schede**:
|
||||
|
||||
| Scheda | Contenuto |
|
||||
|---|---|
|
||||
| **Dati principali** | i gruppi *Identità*, *Unità, codici e IVA*, *Prezzi e costi*, *Magazzino e riordino*, *Contabilità* |
|
||||
| **UM alternative** | unità diverse da quella base con il **fattore** (una scatola da 10 pezzi ha fattore 10) e l'EAN della confezione |
|
||||
| **Codici alternativi** | codici a barre dei produttori e codici dei vecchi gestionali: la ricerca li trova esattamente |
|
||||
| **Listini** | i prezzi in vigore oggi in ogni listino, i prezzi di listino scritti con la loro data e i **prezzi netti dei clienti** |
|
||||
| **Fornitori** | chi fornisce l'articolo, con codice e prezzo del fornitore, giorni di consegna, minimo d'ordine e il **fornitore abituale** |
|
||||
| **Sostitutivi** | articoli equivalenti da proporre quando quello richiesto manca |
|
||||
| **Note e allegati** | note libere e file (immagini, schede tecniche) |
|
||||
| **Storico** | modifiche registrate: chi, quando, cosa |
|
||||
|
||||
Una scheda con errori mostra il numero degli errori nell'etichetta, come nelle [Anagrafiche](Anagrafiche).
|
||||
|
||||
### Campi principali
|
||||
|
||||
| Gruppo | Campi |
|
||||
|---|---|
|
||||
| **Identità** | Codice (automatico), Tipo, Categoria, **Descrizione** *, Descrizione estesa, Marca, Produttore |
|
||||
| **Codici, UM e fisco** | UM base, EAN (con verifica della cifra di controllo), NC8 (Intrastat), IVA vendita, IVA acquisto, Peso netto, Conto ricavo, Conto costo |
|
||||
| **Prezzi e costi** | prezzi dei listini principali (es. base, pubblico IVA inclusa, rivenditori), Costo standard, Ultimo costo, Medio ponderato (gli ultimi due calcolati) |
|
||||
| **Riordino** | Gestito a magazzino, Deposito, **Scorta minima**, **Punto di riordino**, **Lotto di riordino**, Fornitore abituale |
|
||||
| **Giacenze per deposito (tempo reale)** | per ogni deposito: Giacenza, Impegnato, Ordinato, Disponibile, Valore, con riga di totale |
|
||||
| **Unità, codici e IVA** | UM base, codice a barre (EAN, con verifica della cifra di controllo), nomenclatura **NC8** (otto cifre, per Intrastat), IVA vendita, IVA acquisto, Peso netto e lordo |
|
||||
| **Prezzi e costi** | Prezzo dell'articolo (vale solo se nessun listino ha un prezzo), Costo standard, Ultimo costo, Costo medio |
|
||||
| **Magazzino e riordino** | Gestito a magazzino, Deposito, **Scorta minima**, **Punto di riordino**, **Lotto di riordino** |
|
||||
| **Contabilità** | Conto ricavo, Conto costo |
|
||||
|
||||
### Tipi di articolo
|
||||
|
||||
| Tipo | Uso | Magazzino |
|
||||
|---|---|---|
|
||||
| **Merce** | beni venduti o acquistati | sì, se *Gestito a magazzino* |
|
||||
| **Servizio** | prestazioni (es. installazione, assistenza a ore) | no |
|
||||
| **Servizio** | prestazioni (installazione, assistenza a ore) | no |
|
||||
| **Spesa** | spese accessorie in fattura (trasporto, incasso) | no |
|
||||
| **Testo** | righe descrittive ricorrenti | no |
|
||||
| **Cespite** | beni strumentali (collegati al registro cespiti con il modulo Cespiti) | da definire in sviluppo |
|
||||
| **Descrittivo** | righe di solo testo ricorrenti | no |
|
||||
| **Cespite** | beni strumentali (registro cespiti con il modulo Cespiti) | no |
|
||||
|
||||
### Unità di misura e codici
|
||||
Solo le merci possono essere gestite a magazzino: per gli altri tipi l'opzione è spenta e Khaemhat la corregge al
|
||||
salvataggio.
|
||||
|
||||
- **UM base** (ad esempio `PZ`, `MT`, `H`, `NR`) dalla tabella delle unità di misura, con il codice usato nell'XML
|
||||
SDI; le **UM alternative** hanno un fattore di conversione (ad esempio confezione da 10 pezzi).
|
||||
- **Codici alternativi**: altri codici a barre (EAN) e codici interni; nella ricerca F4 un articolo si trova anche
|
||||
per EAN e per il **codice che il cliente usa** per quell'articolo (impostato nella scheda *Articoli e codici* del
|
||||
cliente, vedi [Anagrafiche](Anagrafiche)).
|
||||
- **Fornitori**: chi fornisce l'articolo, con codice e prezzo del fornitore; uno è il **fornitore abituale** usato
|
||||
dalla proposta di riordino.
|
||||
- **Sostitutivi**: articoli equivalenti proposti quando quello richiesto non è disponibile.
|
||||
### Costi
|
||||
|
||||
### Prezzi e costi
|
||||
- **Costo standard**: valore scritto a mano.
|
||||
- **Ultimo costo** e **costo medio**: li aggiornano i carichi di magazzino (DDT di carico, fatture di acquisto) che
|
||||
arrivano con il magazzino (M6); fino ad allora sono valorizzati solo nei dati di esempio. Il costo medio è il
|
||||
criterio di valorizzazione del magazzino (vedi [Magazzino](Magazzino)).
|
||||
- Il **margine** è calcolato sul prezzo: (prezzo - costo) / prezzo.
|
||||
- Chi non ha il permesso `items.cost.read` non vede i costi (né nella scheda né nell'elenco né nei listini) e,
|
||||
quando salva, i costi in archivio restano quelli di prima.
|
||||
|
||||
- I **prezzi di vendita** stanno nei listini (vedi sotto); la scheda mostra quelli dei listini principali.
|
||||
- **Costo standard**: valore impostato a mano.
|
||||
- **Ultimo costo** e **costo medio ponderato**: aggiornati dai carichi di magazzino (DDT di carico, fatture di
|
||||
acquisto). Il costo medio è il criterio di valorizzazione del magazzino (vedi [Magazzino](Magazzino)).
|
||||
- Il **margine** è mostrato solo a chi ha il permesso di vedere costi e margini.
|
||||
### Giacenze e riordino
|
||||
|
||||
### Riordino e giacenze
|
||||
Con **Gestito a magazzino** l'articolo parteciperà a movimenti, giacenze per deposito (*Giacenza, Impegnato,
|
||||
Ordinato, Disponibile, Valore*) e **proposta di riordino**: questi arrivano con il magazzino (M6). Scorta minima,
|
||||
punto e lotto di riordino si possono già compilare.
|
||||
|
||||
Con **Gestito a magazzino** attivo l'articolo partecipa ai movimenti, alle giacenze e alla **proposta di riordino**:
|
||||
quando la disponibilità scende sotto il **punto di riordino** l'articolo viene proposto per un ordine al fornitore
|
||||
abituale, in multipli del **lotto**. La griglia *Giacenze per deposito* mostra:
|
||||
### Controlli al salvataggio
|
||||
|
||||
| Colonna | Significato |
|
||||
|---|---|
|
||||
| **Giacenza** | quantità fisicamente presente |
|
||||
| **Impegnato** | quantità riservata da ordini clienti confermati |
|
||||
| **Ordinato** | quantità in arrivo da ordini fornitore |
|
||||
| **Disponibile** | giacenza - impegnato |
|
||||
| **Valore** | giacenza x costo medio |
|
||||
- Descrizione obbligatoria; categoria obbligatoria se la maschera del codice la usa.
|
||||
- Codice a barre con cifra di controllo corretta (EAN-8, EAN-13, UPC). Un codice a barre già usato da un altro
|
||||
articolo blocca il salvataggio se nelle preferenze è attivo *Blocca duplicati per EAN* (impostazione di
|
||||
partenza), altrimenti è solo un avviso.
|
||||
- NC8 di otto cifre; quantità, pesi, prezzi e costi non negativi; fattori delle UM maggiori di zero.
|
||||
- Nelle schede di dettaglio: la stessa UM, lo stesso codice alternativo, lo stesso fornitore o sostitutivo non si
|
||||
ripetono; un articolo non è sostitutivo di sé stesso; un prezzo netto vale per un cliente.
|
||||
|
||||
### Disattivare ed eliminare
|
||||
|
||||
**Disattiva** toglie l'articolo dalle ricerche dei documenti nuovi senza perdere nulla. **Elimina** cancella
|
||||
l'articolo solo se nessun altro dato lo usa (ad esempio se è sostitutivo di un altro articolo, e da M5 se compare
|
||||
nei documenti); altrimenti Khaemhat lo **disattiva** al posto dell'eliminazione e lo dice.
|
||||
|
||||
## Codici articolo
|
||||
|
||||
Il codice segue la maschera `{categoria}-{seq:0000}` con progressivo **per categoria** (categoria `VALV` →
|
||||
`VALV-0013`). Maschera, codice manuale e blocco dei duplicati per EAN si impostano in *Tabelle azienda →
|
||||
Preferenze e codici automatici* (vedi [Tabelle azienda](Tabelle-azienda)). Il codice si assegna al primo
|
||||
salvataggio.
|
||||
|
||||
I **codici che un cliente o un fornitore usa** per i tuoi articoli si scrivono nella scheda *Articoli e codici*
|
||||
dell'anagrafica (vedi [Anagrafiche](Anagrafiche)): nei documenti di quel cliente la ricerca F4 trova l'articolo
|
||||
anche con il suo codice.
|
||||
|
||||
## Listini
|
||||
|
||||

|
||||
*Mockup 018 — griglia listino x articolo: costo medio, LIST01 Base, LIST02 Pubblico, LIST03 Rivenditori, prezzi netti di un cliente e margine; cella modificata evidenziata e scheda con pallino di modifica.*
|
||||
*Mockup 018 — griglia listino x articolo: costo medio, listini base, pubblico e rivenditori, prezzi netti di un cliente e margine; cella modificata evidenziata.*
|
||||
|
||||
La maschera **Listini** è una **griglia articoli x listini**: per ogni articolo (codice, descrizione, UM, costo
|
||||
medio) una colonna per ciascun listino, più eventuali colonne di **prezzi netti per cliente** e il **margine**.
|
||||

|
||||
*Khaemhat 0.4.0 — la griglia articoli x listini sui 120 articoli di esempio: listino base, Pubblico e Rivenditori derivati (in corsivo i prezzi calcolati), costo medio e margine.*
|
||||
|
||||
- Filtri: ricerca, **Categoria**, **Listino**, **Validità** (la data a cui leggere i prezzi, ad esempio *Oggi*),
|
||||
chip *Mostra margine*.
|
||||
- I prezzi si modificano direttamente nelle celle; le modifiche restano evidenziate e la scheda mostra il pallino
|
||||
arancione finché non salvi. Il piede riporta il numero di articoli, le modifiche non salvate e la data di validità
|
||||
dei nuovi prezzi.
|
||||
- Azioni: **Aggiornamento massivo**, **Nuovo listino**; icone per salvare, annullare, stampare, esportare,
|
||||
applicare una variazione percentuale, ripristinare, duplicare.
|
||||
Un **listino** ha codice, descrizione, valuta, *IVA inclusa*, validità e, se è derivato, il listino da cui
|
||||
**deriva**, il **ricarico %** (anche negativo, come uno sconto) e il **passo di arrotondamento**. Le intestazioni si
|
||||
gestiscono nella tabella *Listini* dell'azienda; uno solo è il **listino base** (in partenza `BASE`).
|
||||
|
||||
Ogni listino ha una **validità** (i prezzi nuovi valgono da una data, i vecchi restano per i documenti precedenti),
|
||||
può essere **derivato** da un altro listino (ad esempio pubblico = base + 40%) e ha le proprie regole di
|
||||
**arrotondamento**.
|
||||
### La griglia dei listini
|
||||
|
||||
**Anagrafiche → Listini** è una griglia **articoli x listini**: per ogni articolo codice, descrizione, UM, costo
|
||||
medio (con il permesso) e una colonna per ciascun listino attivo.
|
||||
|
||||
- In alto: ricerca, **Listino** (tutti o uno solo), **Validità** (la data a cui leggere e scrivere i prezzi, oggi
|
||||
in partenza), **Prezzi netti di** un cliente (aggiunge la colonna dei suoi prezzi netti) e **Mostra margine**.
|
||||
- I prezzi si scrivono nelle celle (vuoto toglie il prezzo a quella data). Le celle cambiate restano **evidenziate
|
||||
da salvare**; il piede riporta articoli, modifiche non salvate e data di validità dei nuovi prezzi. **Salva**
|
||||
scrive tutto insieme, **Annulla modifiche** torna ai prezzi salvati.
|
||||
- Le celle in *corsivo* sono **calcolate** da un listino derivato che non ha un prezzo proprio per l'articolo: il
|
||||
suggerimento dice da quale listino. Scrivere un prezzo nella cella lo rende proprio di quel listino.
|
||||
- Con modifiche non salvate non si cambiano validità o cliente: prima salva o annulla.
|
||||
- **Nuovo listino** apre la tabella dei listini.
|
||||
|
||||
### Validità dei prezzi
|
||||
|
||||
Ogni prezzo vale **dalla sua data** fino al prezzo successivo dello stesso listino (o dello stesso cliente).
|
||||
Scrivere un prezzo con una data nuova **aggiunge** un prezzo e lascia quello vecchio ai documenti datati prima;
|
||||
scriverlo con la stessa data lo corregge. I documenti già fatti conservano sempre il prezzo di allora.
|
||||
|
||||
### Listini derivati
|
||||
|
||||
Un listino derivato senza un proprio prezzo per un articolo prende il prezzo del listino di partenza alla stessa
|
||||
data, applica il ricarico e arrotonda al passo (al centesimo se il passo è zero). Esempio dei dati di esempio:
|
||||
*Pubblico* = base + 45% arrotondato a 0,10; *Rivenditori* = base - 10%. Un prezzo scritto nel listino derivato vince
|
||||
su quello calcolato.
|
||||
|
||||
### Aggiornamento massivo
|
||||
|
||||
1. Premi **Aggiornamento massivo**.
|
||||
2. Scegli **che cosa** aggiornare: un listino, una categoria o le righe selezionate.
|
||||
3. Scegli la **variazione**: percentuale (anche negativa) oppure a partire da un altro listino.
|
||||
4. Scegli l'**arrotondamento**: a 0,10, 0,50 o 1,00, per eccesso o per difetto.
|
||||
5. Indica la **data di validità** dei nuovi prezzi.
|
||||
6. Controlla le righe aggiornate (restano evidenziate) e **Salva**.
|
||||
2. Scegli il **listino da aggiornare** e da dove **calcolare**: i prezzi attuali dello stesso listino o un altro
|
||||
listino.
|
||||
3. Scrivi la **variazione %** (anche negativa).
|
||||
4. Scegli l'**arrotondamento** (0,01, 0,10, 0,50, 1,00) e il **verso** (al più vicino, per eccesso, per difetto).
|
||||
5. Indica la data da cui valgono i nuovi prezzi (**Valido dal**).
|
||||
6. Scegli gli **articoli**: tutti, quelli di una categoria o solo i selezionati.
|
||||
7. Premi **Calcola i prezzi**: le celle calcolate restano evidenziate; controllale e **Salva**.
|
||||
|
||||
L'aggiornamento listini è disponibile anche come procedura pianificabile (vedi [Automazioni](Automazioni)).
|
||||
Il calcolo non scrive nulla finché non salvi; gli articoli il cui prezzo non cambia sono esclusi.
|
||||
|
||||
## Come viene scelto il prezzo in un documento
|
||||
|
||||
Quando inserisci un articolo in una riga di vendita, Khaemhat cerca il prezzo in quest'ordine e si ferma al primo
|
||||
che trova:
|
||||
Quando inserisci un articolo in una riga di vendita (da M5), Khaemhat cerca il prezzo valido alla data del documento
|
||||
in quest'ordine e si ferma al primo che trova:
|
||||
|
||||
| Ordine | Fonte | Esempio |
|
||||
|---|---|---|
|
||||
| 1 | **prezzo netto cliente-articolo** | prezzo concordato con Rossi Impianti per quella valvola |
|
||||
| 2 | **listino del cliente** | il cliente usa LIST03 Rivenditori |
|
||||
| 3 | **listino base** | LIST01 Base |
|
||||
| 4 | **prezzo dell'articolo** | prezzo indicato nella scheda |
|
||||
| 2 | **listino del documento o del cliente** | il cliente usa il listino *Rivenditori* |
|
||||
| 3 | **listino base** | *Base* |
|
||||
| 4 | **prezzo dell'articolo** | prezzo scritto nella scheda |
|
||||
|
||||
La riga ricorda **da dove viene il prezzo** (la fonte), così è sempre possibile capire perché è stato proposto
|
||||
quel valore. Sul prezzo si applicano poi gli sconti del cliente e della riga (anche a cascata, come `5+2`). Se è
|
||||
attiva la compilazione automatica *Ultimo prezzo praticato al cliente*, Khaemhat lo mostra come riferimento.
|
||||
|
||||
## Codici automatici
|
||||
|
||||
Il codice articolo segue la maschera `{categoria}-{seq:0000}` con progressivo **per categoria** (ad esempio
|
||||
categoria `VALV` → `VALV-0013`); la maschera, l'eventuale codice manuale e il blocco dei **duplicati per EAN** si
|
||||
impostano in *Tabelle azienda → Preferenze e codici automatici* (vedi [Tabelle azienda](Tabelle-azienda)).
|
||||
La riga ricorda **da dove viene il prezzo** (la fonte). Sul prezzo di listino si propongono gli sconti del cliente a
|
||||
cascata (come `10+5`); su un **prezzo netto** non si applicano sconti.
|
||||
|
||||
## Permessi e licenza
|
||||
|
||||
Articoli e listini sono nel modulo **CORE**. I costi e i margini sono visibili solo agli utenti con il permesso
|
||||
`items.cost.read` (flag *vede costi e margini*). Il collegamento ai cespiti richiede il modulo **ASSET**; i conti
|
||||
contabili sono usati con il modulo **ACCT**.
|
||||
Articoli e listini sono nel modulo **CORE**. Per scrivere i prezzi nella griglia serve `items.item.write`; i costi
|
||||
e i margini richiedono `items.cost.read` (il ruolo *Magazzino* gestisce gli articoli ma non vede i costi). Il
|
||||
collegamento ai cespiti richiede il modulo **ASSET**; i conti contabili sono usati con il modulo **ACCT**.
|
||||
|
||||
## Dati di esempio
|
||||
|
||||
I dati di esempio (vedi [Dati di base e di esempio](Dati-di-base-e-esempio)) creano 120 articoli fittizi di un
|
||||
grossista termoidraulico in dieci categorie (valvolame, raccorderia, tubi, caldaie, sanitari, consumabili, pompe,
|
||||
utensili, servizi, spese), i listini *Pubblico* e *Rivenditori* derivati dal base, prezzi dell'anno precedente per
|
||||
lo storico, fornitori abituali, UM alternative, codici alternativi, sostitutivi e i prezzi netti e i codici di
|
||||
Rossi Impianti. I codici a barre di esempio iniziano con `200`, prefisso riservato all'uso interno.
|
||||
|
||||
## Domande frequenti
|
||||
|
||||
- **Ho cambiato un prezzo di listino ma la fattura di ieri non cambia.** È corretto: i documenti conservano il
|
||||
prezzo con cui sono stati fatti; la validità del listino vale per i documenti nuovi.
|
||||
- **Perché il prezzo proposto non è quello del listino?** Probabilmente esiste un prezzo netto per quel cliente:
|
||||
la fonte del prezzo è indicata nella riga.
|
||||
- **Un articolo di servizio non compare nelle giacenze.** I servizi e le spese non sono gestiti a magazzino.
|
||||
prezzo con cui sono stati fatti; i prezzi nuovi valgono dalla loro data.
|
||||
- **Ho scritto un prezzo con la data sbagliata.** Imposta quella data in *Validità*, svuota la cella e salva: il
|
||||
prezzo a quella data viene tolto.
|
||||
- **Perché il prezzo proposto non è quello del listino?** Probabilmente esiste un prezzo netto per quel cliente: la
|
||||
fonte del prezzo è indicata nella riga.
|
||||
- **Non vedo il costo medio.** Serve il permesso di vedere costi e margini (`items.cost.read`).
|
||||
- **Un servizio non si può mettere a magazzino.** È voluto: solo le merci vanno a magazzino.
|
||||
|
||||
## Pagine correlate
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Changelog
|
||||
|
||||
> **Stato:** completa per 0.1.0 · **Ultima revisione:** 2026-11-11
|
||||
> **Stato:** completa per 0.4.0 · **Ultima revisione:** 2026-11-12
|
||||
|
||||
Le novità di ogni versione sono nel file
|
||||
[`CHANGELOG.md`](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/src/branch/main/CHANGELOG.md) del repository
|
||||
@@ -11,12 +11,15 @@ Le novità di ogni versione sono nel file
|
||||
|
||||
| Versione | Data | Contenuto |
|
||||
|---|---|---|
|
||||
| 0.4.0 | 2026-11-12 | M4 — Tabelle, anagrafiche, articoli: pacchetto fiscale italiano, profilo azienda, esercizi e cambi, 26 tabelle azienda con province, comuni e CAP, clienti, fornitori e contatti con controlli e VIES, articoli e listini con prezzi a validità, codici automatici, import/export guidato (anche del piano dei conti, per ora solo verifica) e dati di esempio. |
|
||||
| 0.3.0 | 2026-11-11 | M3 — Framework UI: la finestra di Khaemhat con menu, schede e barra di stato, la dashboard a widget, *Il mio profilo* con temi e colori, ricerca globale, aiuto in app, notifiche, componenti per maschere e liste, allegati e anteprima di stampa (provati su un documento di prova, le maschere gestionali arrivano da 0.4.0). |
|
||||
| 0.2.0 | 2026-11-11 | M2 — Sistema e sicurezza: avvio da variabili d'ambiente, super utente e prima azienda, accesso con password e verifica in due passaggi, utenti, ruoli e permessi, licenze e moduli con codici di prova, log per sezioni, attività programmate. |
|
||||
| 0.1.0 | 2026-11-11 | M1 — Strato dati: accesso ai database SQLite e PostgreSQL, migrazioni dello schema, registro delle aziende, cifratura dei dati riservati. Nessuna funzione visibile nell'interfaccia. |
|
||||
| 0.0.1 | 2026-11-11 | M0 — Bootstrap: struttura del codice, immagine Docker con pagina "in costruzione" ed endpoint di salute, compose, CI e rilascio su Gitea Actions. Nessuna funzione gestionale ancora. |
|
||||
| *preparazione* | 2026-11-10 | Documentazione, specifica, mockup, wiki e pianificazione su Gitea. Nessun software. |
|
||||
|
||||
Ogni immagine Docker pubblicata ha lo stesso numero di versione del tag git (senza la `v` iniziale), ad esempio
|
||||
`gitea.encke-hake.ts.net/balbosoft/khaemhat:0.1.0`. Prima di aggiornare leggi [Aggiornamento](Aggiornamento).
|
||||
`gitea.encke-hake.ts.net/balbosoft/khaemhat:0.3.0`. Prima di aggiornare leggi [Aggiornamento](Aggiornamento).
|
||||
|
||||
## Pagine correlate
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Dashboard
|
||||
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M3)
|
||||
> **Stato:** completa · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.3.0 (milestone M3)
|
||||
> **Modulo di licenza:** CORE (alcuni widget richiedono il modulo dell'area, ad esempio CRM) · **Specifica:** SPEC §10.3, §11.12
|
||||
|
||||
La **dashboard** è la pagina *Home*: una griglia di **widget** che riassume che cosa c'è da fare oggi, che cosa è
|
||||
@@ -17,17 +17,33 @@ diversamente in *Pagina iniziale*.
|
||||

|
||||
*Mockup 004 — dashboard con saluto e data, KPI, Da fare oggi, Fatto oggi, Scadenze prossimi 30 giorni, Da evadere, Fatturato 12 mesi (anteprima ridotta).*
|
||||
|
||||

|
||||
*Khaemhat 0.3.0 — la dashboard predefinita di un super utente. Indicatori, Da evadere e Fatturato 12 mesi si accendono quando arrivano i dati (vendite, M5).*
|
||||
|
||||

|
||||
*Mockup 005 — la stessa dashboard in tema scuro (anteprima ridotta).*
|
||||
|
||||

|
||||
*Khaemhat 0.3.0 — la stessa dashboard in tema scuro.*
|
||||
|
||||

|
||||
*Mockup 006 — modalità Personalizza: widget con bordo tratteggiato e pannello laterale con pagina iniziale ed elenco dei widget attivabili (anteprima ridotta).*
|
||||
|
||||
In testa alla pagina: il saluto (*Buongiorno Alberto*) con la data, a destra **Personalizza** e **Nuovo documento**.
|
||||

|
||||
*Khaemhat 0.3.0 — Personalizza: widget con bordo tratteggiato e comandi di spostamento e larghezza, pannello con pagina iniziale ed elenco dei widget.*
|
||||
|
||||
In testa alla pagina: il saluto (*Buongiorno Alberto*, *Buon pomeriggio*, *Buonasera*) con la data, a destra
|
||||
**Personalizza**. Il pulsante **Nuovo documento** arriva con le vendite (M5).
|
||||
|
||||
## Widget disponibili
|
||||
|
||||
La griglia ha 12 colonne; ogni widget può occupare 3, 4, 6, 8 o 12 colonne.
|
||||
La griglia ha 12 colonne; ogni widget può occupare 3, 4, 6, 8 o 12 colonne (sotto i 1000 px di larghezza ogni
|
||||
widget prende tutta la riga).
|
||||
|
||||
Nella versione 0.3.0 hanno già dati **Da fare oggi**, **Fatto oggi**, **Scadenze 30 giorni**, **Promemoria
|
||||
personali**, **Scorciatoie** e **Stato del sistema**. Gli altri si possono già accendere, mettere in ordine e
|
||||
dimensionare: finché il loro modulo non c'è dicono con quale versione arrivano i dati (*Vendite* M5, *Acquisti e
|
||||
magazzino* M6, *CRM* M11), senza numeri finti.
|
||||
|
||||
| Widget | Cosa mostra | Note |
|
||||
|---|---|---|
|
||||
@@ -43,38 +59,63 @@ La griglia ha 12 colonne; ogni widget può occupare 3, 4, 6, 8 o 12 colonne.
|
||||
| **Sottoscorta** | articoli sotto la scorta minima | |
|
||||
| **Pipeline CRM** | valore delle opportunità per fase | richiede il modulo CRM |
|
||||
| **Ultimi documenti** | ultimi documenti aperti o creati | |
|
||||
| **Stato sistema** | stato dell'istanza (database, backup, scheduler) | solo amministratori |
|
||||
| **Stato del sistema** | versione, database, cache, licenza, aziende aperte, attività programmate di oggi, ognuno con un pallino verde, giallo o rosso | solo account di istanza |
|
||||
|
||||
Ogni widget ha in alto a destra un menu **⋯** con le azioni proprie (ad esempio aggiornare o aprire l'elenco
|
||||
completo). I dati rispettano i permessi: un utente che non vede costi e margini non li trova nemmeno nei widget.
|
||||
Ogni widget ha in alto a destra le sue azioni: il numero di righe nelle liste, la matita delle **Scorciatoie** (scegli
|
||||
fino a 12 pagine fra quelle che puoi aprire), il cestino dei **Promemoria** che toglie quelli spuntati. Un clic su una
|
||||
riga di *Da fare oggi*, *Fatto oggi* o *Scadenze* apre la pagina giusta. I dati rispettano i permessi: un utente che
|
||||
non vede costi e margini non li trova nemmeno nei widget.
|
||||
|
||||
Nella versione 0.3.0 le righe vengono da:
|
||||
|
||||
| Widget | Righe |
|
||||
|---|---|
|
||||
| Da fare oggi | licenza scaduta, in tolleranza o in scadenza entro 7 giorni (account di istanza); avvisi non letti di livello *attenzione* o *errore*; attività programmate la cui ultima esecuzione di oggi non è riuscita (account di istanza) |
|
||||
| Fatto oggi | attività programmate riuscite oggi, una riga per attività con il numero di esecuzioni e l'ora dell'ultima |
|
||||
| Scadenze 30 giorni | fine della prova o scadenza della licenza (account di istanza) |
|
||||
|
||||
I moduli delle prossime versioni aggiungono le loro righe (scarti SDI, liquidazioni, incassi, ordini da evadere…).
|
||||
Se una fonte non risponde, il widget mostra le altre e l'errore finisce nel [log](Log).
|
||||
|
||||
I **promemoria** si scrivono nel campo in fondo al widget e si aggiungono con Invio (al massimo 20, di 300 caratteri
|
||||
ciascuno); la casella li segna come fatti, la **×** li toglie.
|
||||
|
||||
## Come si personalizza
|
||||
|
||||
1. Premi **Personalizza** in alto a destra. I widget si contornano con un bordo tratteggiato e si apre il pannello
|
||||
laterale **Personalizza dashboard**.
|
||||
2. Nel pannello, sezione **Widget (trascina per ordinare)**, attiva o disattiva ciascun widget con l'interruttore e
|
||||
trascinalo per cambiarne l'ordine.
|
||||
3. Sulla griglia trascina i widget per spostarli e ridimensionali (3, 4, 6, 8 o 12 colonne).
|
||||
4. Imposta, se vuoi, il periodo dei KPI.
|
||||
5. Chiudi il pannello: la disposizione è salvata.
|
||||
laterale **Personalizza dashboard**; la pagina resta utilizzabile e, sugli schermi larghi almeno 1280 px, si
|
||||
stringe per lasciare spazio al pannello.
|
||||
2. Nel pannello, sezione **Widget**, accendi o spegni ciascun widget con l'interruttore; per quelli accesi scegli la
|
||||
larghezza (*Un quarto*, *Un terzo*, *Metà*, *Due terzi*, *Tutta la riga*) e spostali con le frecce. Un widget
|
||||
acceso si aggiunge in fondo.
|
||||
3. Sulla griglia trascina un widget sopra un altro per prenderne il posto. Ogni widget ha anche i pulsanti
|
||||
**‹ ›** (sposta prima o dopo), **− +** (più stretto o più largo) e **×** (nascondi): tutto si fa anche da tastiera.
|
||||
4. **Ripristina** cancella la tua disposizione: torna quella predefinita del tuo ruolo o, se non c'è, quella di
|
||||
Khaemhat. **Fine** (o Esc) chiude il pannello.
|
||||
|
||||
Disposizione e scelte sono salvate nelle tue preferenze (sul database dell'azienda): le ritrovi su ogni dispositivo.
|
||||
Ogni modifica si salva subito nelle tue preferenze: la ritrovi su ogni dispositivo. Il pannello dice da dove viene la
|
||||
disposizione che stai usando (tua, del ruolo o di Khaemhat).
|
||||
|
||||
## Pagina iniziale e dashboard disattivabile
|
||||
|
||||
La dashboard si può **spegnere**. Nel pannello *Personalizza* (sezione **Pagina iniziale**) o in
|
||||
[Il mio profilo → Pagina iniziale](Preferenze-utente) scegli:
|
||||
|
||||
- **All'accesso apri**: *Dashboard*, oppure l'*ultima scheda aperta*, un *radar* (ad esempio *Clienti*), la *prima
|
||||
nota*, l'*agenda CRM*…
|
||||
- **Pagina da aprire**: *La pagina iniziale* (la dashboard), l'*ultima scheda aperta* o una delle pagine che puoi
|
||||
aprire (ad esempio *Clienti*).
|
||||
- **Mostra la dashboard**: se disattivato, la voce *Home* non mostra più i widget e all'accesso si apre la pagina
|
||||
scelta.
|
||||
|
||||
## Layout per ruolo
|
||||
|
||||
Gli amministratori possono definire un **layout predefinito per ruolo** (ad esempio un layout per *Vendite*, uno per
|
||||
*Contabilità*): un nuovo utente parte dal layout del proprio ruolo e può poi modificarlo per sé. La maschera di
|
||||
gestione dei layout per ruolo sarà definita in sviluppo (vedi [Utenti e permessi](Utenti-e-permessi)).
|
||||
Chi ha il permesso **Modificare le impostazioni dell'azienda** (`company.settings.write`, ad esempio il ruolo
|
||||
*Amministrazione*) trova in fondo al pannello la sezione **Predefinito per ruolo**: sceglie un ruolo e preme **Usa
|
||||
questo layout per il ruolo** per dargli la disposizione che ha sulla pagina in quel momento; **Togli il predefinito**
|
||||
lo riporta a quello di Khaemhat. I ruoli che hanno un predefinito sono segnati nell'elenco.
|
||||
|
||||
Chi non ha mai personalizzato la dashboard parte dal predefinito del suo ruolo (se ha più ruoli, il primo assegnato
|
||||
che ne ha uno); appena cambia qualcosa la disposizione diventa sua. I predefiniti dei ruoli sono impostazioni
|
||||
dell'azienda: ogni azienda ha i suoi. La sezione compare solo quando lavori in un'azienda.
|
||||
|
||||
## Permessi e licenza
|
||||
|
||||
@@ -85,9 +126,10 @@ se l'utente ha i permessi di lettura su quei dati; *Stato sistema* è riservato
|
||||
|
||||
- **Un widget non compare nell'elenco.** Il modulo relativo (ad esempio CRM) non è licenziato o non hai il permesso
|
||||
di vederne i dati.
|
||||
- **Voglio tornare alla disposizione iniziale.** Un comando per ripristinare il layout del ruolo non è ancora
|
||||
definito nella specifica; sarà deciso in sviluppo e documentato qui. Nel frattempo riattiva o riordina i widget
|
||||
da *Personalizza*.
|
||||
- **Voglio tornare alla disposizione iniziale.** *Personalizza* → **Ripristina**: torna il predefinito del tuo ruolo
|
||||
o quello di Khaemhat.
|
||||
- **Ho spento la dashboard e voglio riaccenderla.** La *Home* mostra in alto **Mostra la dashboard**; in alternativa
|
||||
[Il mio profilo → Pagina iniziale](Preferenze-utente).
|
||||
- **"Da fare oggi" mostra cose che non riguardano il mio lavoro.** L'elenco segue i tuoi permessi; se vedi voci non
|
||||
pertinenti, chiedi all'amministratore di verificare il tuo ruolo.
|
||||
|
||||
|
||||
@@ -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:** completa per M4 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (dati di esempio di documenti e contabilità con i moduli, 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
|
||||
@@ -21,26 +21,26 @@ alto a destra, es. *Database: khaemhat_demo*).
|
||||
|
||||
*Mockup 089 — riepilogo di tabelle di base, dati di esempio, documenti reali e utenti demo con i pulsanti **Aggiorna
|
||||
tabelle di base**, **Carica dati di esempio**, **Rimuovi dati di esempio**, **Anteprima differenze**; a destra le
|
||||
ultime migrazioni; sotto, i **pacchetti di dati di base** della versione `IT 2026.2` con contenuto, righe e stato
|
||||
ultime migrazioni; sotto, i **pacchetti di dati di base** della versione `IT 2026.3` con contenuto, righe e stato
|
||||
(anteprima ridotta)*
|
||||
|
||||
Il riepilogo mostra:
|
||||
|
||||
| Voce | Esempio |
|
||||
|---|---|
|
||||
| **Tabelle di base** | versione del pacchetto (`IT 2026.2`), righe, data dell'ultimo aggiornamento |
|
||||
| **Tabelle di base** | versione del pacchetto (`IT 2026.3`), righe, data dell'ultimo aggiornamento |
|
||||
| **Dati di esempio** | *presenti* con i conteggi (clienti, fornitori, articoli, documenti, registrazioni, cespiti, lead) oppure *assenti* |
|
||||
| **Documenti reali** | numero di documenti non dimostrativi (0 in un'azienda demo) |
|
||||
| **Utenti demo** | utenti dimostrativi e relativa password |
|
||||
|
||||
## Le tabelle di base
|
||||
|
||||
Sono raccolte in **pacchetti** con una **versione** (oggi `IT 2026.2`, salvata nelle impostazioni dell'azienda).
|
||||
Sono raccolte in **pacchetti** con una **versione** (oggi `IT 2026.3`, salvata nelle impostazioni dell'azienda).
|
||||
Il pacchetto italiano fa parte del pacchetto fiscale Italia (vedi [Fiscalità italiana](Fiscalita-italiana)).
|
||||
|
||||
| Pacchetto | Contenuto |
|
||||
|---|---|
|
||||
| **Paesi e comuni** | paesi ISO, province, comuni con CAP e codice catastale |
|
||||
| **Paesi e comuni** | paesi ISO, province, comuni con codice catastale, codice ISTAT e CAP |
|
||||
| **Valute e unità di misura** | valute, unità di misura |
|
||||
| **Codici IVA e nature** | aliquote 22, 10, 5, 4; esenti (ESE10 N4); non imponibili (NI8 N3.1, NI41 N3.2, NI71 N3.3, NI8C N3.5); fuori campo (FC7 N2.1, altre N2.2); escluse (ESC15 N1); reverse charge (RC17 N6.x); split payment; non soggette; indetraibili 50% e 100%; forfettari |
|
||||
| **Modalità e condizioni di pagamento** | modalità `MP01`-`MP23`, condizioni di pagamento |
|
||||
@@ -56,6 +56,32 @@ 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 e comuni** (dalla versione `IT 2026.3`) vengono dall'elenco ISTAT dei codici dei comuni aggiornato al
|
||||
26/02/2026: 110 province con sigla e regione, 7.894 comuni con codice catastale, provincia, regione e codice ISTAT.
|
||||
Il **codice** di un comune è il suo codice catastale (es. `H501` per Roma), lo stesso del codice fiscale.
|
||||
I **CAP** vengono dall'elenco dei codici postali di GeoNames e ci sono per 7.750 comuni: un CAP, una lista o un
|
||||
intervallo come `10121-10156` per le città con più CAP.
|
||||
|
||||
> Fonti: ISTAT, *Codici statistici delle unità amministrative territoriali*, e GeoNames
|
||||
> ([www.geonames.org](https://www.geonames.org)), entrambi con licenza
|
||||
> [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/deed.it).
|
||||
|
||||
Ai comuni rinominati o nati da fusioni recenti (ad esempio Sanremo) il CAP può mancare: si completa a mano nella
|
||||
tabella *Comuni* o con l'**Importa CSV** (colonne `Code` e `PostalCodes`, più CAP separati da virgola). La
|
||||
compilazione dal CAP propone solo i comuni che hanno il CAP scritto. Le **banche ABI/CAB** non sono ancora incluse: banca e BIC dall'IBAN vengono da un conto
|
||||
dell'azienda presso la stessa banca. Un comune soppresso per fusione resta nella tabella finché non lo disattivi.
|
||||
|
||||
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 +90,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`).
|
||||
@@ -94,6 +124,16 @@ reale. Contiene:
|
||||
| Log | voci di log di esempio in tutte le sezioni |
|
||||
|
||||
Tutte le righe dimostrative sono marcate come tali (`is_demo`), così si possono rimuovere senza toccare il resto.
|
||||
|
||||
**Oggi (M4)** i dati di esempio contengono 3 agenti e **21 anagrafiche**: 12 clienti che coprono tutti i tipi
|
||||
soggetto (fra cui un comune con split payment, un cliente bloccato, uno disattivato, uno che è anche fornitore e
|
||||
uno con dichiarazione d'intento), 5 fornitori (professionista con ritenuta, agente ENASARCO, fornitore UE),
|
||||
2 prospect e 2 lead. Partite IVA, codici fiscali e IBAN sono numeri inventati ma formalmente validi, perché passino
|
||||
i controlli; non si verificano sul VIES (ADR 0029). Gli agenti di esempio non sono marcati e si rimuovono a mano.
|
||||
Ci sono poi **120 articoli** in dieci categorie con i listini *Pubblico* e *Rivenditori* derivati dal base, prezzi
|
||||
dell'anno precedente, fornitori abituali, UM e codici alternativi, sostitutivi e i prezzi netti e i codici di un
|
||||
cliente (ADR 0030, vedi [Articoli e listini](Articoli-e-listini)). I codici a barre di esempio iniziano con `200`,
|
||||
prefisso riservato all'uso interno. Il resto della tabella arriva con le milestone dei rispettivi moduli.
|
||||
I dati sono costruiti con gli stessi motori del programma (documenti, contabilità): ogni quadratura torna, e lo
|
||||
stesso caricamento è usato come prova automatica di correttezza.
|
||||
|
||||
@@ -125,14 +165,29 @@ 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 e i dati di esempio 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
|
||||
docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --demo --company DEMO
|
||||
docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --demo --scale 10 --company PROVA
|
||||
```
|
||||
|
||||
`--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|--demo [--scale N] [--company CODICE]`.
|
||||
|
||||
| Opzione | Effetto |
|
||||
|---|---|
|
||||
| `--base` | aggiunge i codici di base mancanti |
|
||||
| `--demo` | prima i dati di base, poi i dati di esempio; ogni gruppo (anagrafiche, articoli) si carica solo nell'azienda che non ne ha ancora |
|
||||
| `--scale N` | solo con `--demo`: ripete il catalogo articoli N volte (da 1 a 100), per le prove di prestazione |
|
||||
| `--company CODICE` | lavora solo su quell'azienda invece che su tutte quelle attive |
|
||||
|
||||
I dati di esempio si caricano anche al primo avvio con `KHAEMHAT_SEED_DEMO=true`.
|
||||
|
||||
## Migrazioni
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Design UI
|
||||
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M3)
|
||||
> **Stato:** completa · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.3.0 (milestone M3)
|
||||
> **Pagina per chi sviluppa** · **Specifica:** SPEC §10 (in particolare §10.1, §10.6, §10.7, §10.8), Appendice A
|
||||
|
||||
Questa pagina è il riferimento visivo per chi sviluppa l'interfaccia di Khaemhat: come si usano i mockup, i token di
|
||||
@@ -31,7 +31,18 @@ Regole vincolanti (SPEC §10.1):
|
||||
|
||||
Solo 23 schermate sono disponibili in alta risoluzione; per le altre si lavora dalla miniatura, da `mockup.css` e
|
||||
dalla descrizione in SPEC §10-§12 (emendamento E4 in `CLAUDE.md`). Gli screenshot reali in `docs/wiki/img/`
|
||||
sostituiscono progressivamente i mockup nelle pagine della wiki.
|
||||
affiancano i mockup nelle pagine della wiki: dalla versione 0.3.0 ci sono la shell, la dashboard, il profilo, l'aiuto,
|
||||
le notifiche, il documento di prova con allegati e storico e l'anteprima di stampa.
|
||||
|
||||
Gli screenshot si rifanno su un'istanza nuova (database SQLite vuoto, azienda DEMO, tema chiaro, finestra
|
||||
1440x900, telefono 390x844), così non mostrano dati o notifiche di prova; i nomi dei file sono quelli usati dalle
|
||||
pagine, ad esempio `interfaccia-home.png` o `allegati-pannello.png`.
|
||||
|
||||

|
||||
*Khaemhat 0.3.0 — i mattoni di 020 e 021 dal vero: toolbar a icone, intestazione documento, schede interne, griglia delle righe.*
|
||||
|
||||

|
||||
*Khaemhat 0.3.0 — la dashboard con tema scuro e accento Nilo.*
|
||||
|
||||
## Token di design
|
||||
|
||||
@@ -91,8 +102,8 @@ Altre preferenze di presentazione: dimensione del testo, carattere numerico tabe
|
||||
`AccentColor`, `Density`, `MenuState`). `ThemeService` e `MenuStateService` applicano gli attributi senza ricaricare
|
||||
la pagina.
|
||||
|
||||
`mockup.css` **non contiene ancora i valori del tema alto contrasto**: vanno definiti in `tokens.css` rispettando il
|
||||
contrasto AAA, con gli stessi nomi di token, e documentati in questa pagina.
|
||||
`mockup.css` non contiene i valori del tema **alto contrasto**: sono definiti in `tokens.css` con gli stessi nomi di
|
||||
token (testo nero su bianco, bordi neri, un solo accento blu scuro per tutti gli accenti), per il contrasto AAA.
|
||||
|
||||
## Classi dei mockup e componenti `Kh*`
|
||||
|
||||
@@ -154,6 +165,20 @@ radar, `Ctrl+Invio` apre, creazione al volo; `KhGrid` con colonne tipizzate, ord
|
||||
server, virtualizzazione, selezione multipla, editing inline, riga dei totali, layout colonne salvato, export,
|
||||
evidenziazioni, menu di riga.
|
||||
|
||||
## File CSS
|
||||
|
||||
| File | Contenuto |
|
||||
|---|---|
|
||||
| `css/tokens.css` | token `--kh-*` di `mockup.css`, temi (automatico, chiaro, scuro, alto contrasto), accenti, densità, dimensioni del testo; generato da `mockup.css` |
|
||||
| `css/components.css` | classi dei mockup (shell, toolbar, pannelli, campi, griglie, badge, dialoghi…), riprese da `mockup.css` |
|
||||
| `css/interactive.css` | ciò che i mockup statici non hanno: reset dei pulsanti, focus, suggerimenti, menu a comparsa, schede, notifiche a scomparsa, interruttori `data-*` |
|
||||
| `css/print.css` | stampa sempre in chiaro, shell nascosta |
|
||||
| `app.css` | pagine costruite finora (accesso, home, profilo, messaggi) |
|
||||
|
||||
Gli attributi sull'elemento `<html>` comandano l'aspetto: `data-theme` (`auto`, `light`, `dark`, `high-contrast`),
|
||||
`data-accent`, `data-density`, `data-text-size` (`100`, `110`, `120`), `data-tabular`, `data-motion`,
|
||||
`data-tooltips`, `data-row-hover`. Il server li scrive dalle preferenze dell'utente; il profilo li cambia dal vivo.
|
||||
|
||||
## Shell
|
||||
|
||||
- Griglia: barra superiore 46 px, area centrale, barra di stato 24 px; menu 228 px (60 px compresso).
|
||||
@@ -162,7 +187,9 @@ evidenziazioni, menu di riga.
|
||||
- **Menu**: sezioni in maiuscoletto (`.sec`), voce attiva su `--kh-accent-soft`; compresso: solo icone 20 px, barretta
|
||||
d'accento a sinistra della voce attiva, sottomenu in `.flyout` (min 190 px, ombra grande). Pulsante **Comprimi
|
||||
menu** tratteggiato in fondo. Sotto 1100 px parte compresso; stato salvato per utente.
|
||||
- **Schede** (`.wtab`): altezza 30 px, massimo 260 px di larghezza, pallino `--kh-warn` se modificata.
|
||||
- **Schede** (`.wtab`): altezza 30 px, massimo 260 px di larghezza, pallino `--kh-warn` se modificata. Ogni pagina
|
||||
imposta il titolo della sua scheda con `<KhPageTitle Text="..." Icon="..." />` e segnala le modifiche con il
|
||||
`KhTab` in cascata (`Tab?.SetModified(true)`).
|
||||
- **Barra di stato**: testo 11.5 px, pallino `--kh-ok` per la connessione.
|
||||
|
||||
Dettagli d'uso in [Interfaccia e scorciatoie](Interfaccia-e-scorciatoie).
|
||||
@@ -211,17 +238,26 @@ dal testo. Nessuna libreria di icone esterna. L'icona dell'applicazione è descr
|
||||
**nessun font scaricato**, nessuna CDN.
|
||||
- **Focus sempre visibile**, etichette collegate ai campi (`<label for>`), contrasto **AA** (AAA nel tema alto
|
||||
contrasto), tutto operabile da tastiera.
|
||||
- Desktop-first, usabile da tablet a partire da **768 px**.
|
||||
- **Testi**: nessun testo hard-coded nei componenti (verificato da un test di architettura); `ITexts` risolve chiavi
|
||||
come `Sales.Invoice.Title` da `Resources/it-IT/*.json`.
|
||||
- Desktop-first, usabile da tablet a partire da **768 px** e su telefono con la barra superiore a sole icone (vedi [Interfaccia e scorciatoie](Interfaccia-e-scorciatoie)).
|
||||
- **Nomi di classe unici**: una classe dei mockup ha un solo significato. Se un componente ha bisogno di una variante, usa un nome nuovo (`kh-…`) invece di riusarne uno esistente: in 0.3.0 `.tl` (timeline) e `.kh-choices` usati in due sensi diversi spostavano l'etichetta del totale documento e le schede dei temi.
|
||||
- **Testi**: nessun testo hard-coded nei componenti; `ITexts` (iniettato in ogni componente come `T`) risolve chiavi
|
||||
come `Shell.Menu.Parties` da `src/Khaemhat.Web/Resources/it-IT/*.json` (risorse incorporate). Gli oggetti annidati
|
||||
danno le chiavi puntate, la proprietà `_` dà il testo all'oggetto che ha figli, una chiave doppia blocca l'avvio e
|
||||
una mancante appare come `[chiave]`. Uso: `@T["Pages.Profile.Title"]`, `@T.Format("Pages.Home.Coming", "M4")`,
|
||||
`T.Money(1234.5m)`, `T.Date(...)`. Due test lo garantiscono: nessun testo letterale fra i tag e negli attributi
|
||||
`title`, `placeholder`, `alt`, `aria-label`, `label` dei `.razor`, e ogni chiave usata esiste (ADR 0020).
|
||||
- **Formati**: `CultureInfo("it-IT")` per numeri, importi e date; date memorizzate in UTC e mostrate nel fuso
|
||||
`Europe/Rome`.
|
||||
|
||||
## Stampa
|
||||
|
||||
Le stampe e i PDF sono **sempre in tema chiaro** (`print.css`), indipendentemente dal tema dell'utente. L'anteprima
|
||||
usa `.paper` (pagina bianca larga 794 px, cioè un A4 a 96 dpi, margini 40/44 px, tabelle con intestazione in
|
||||
maiuscoletto e bordo inferiore marcato).
|
||||
Le stampe e i PDF sono **sempre in tema chiaro** (`print.css`), indipendentemente dal tema dell'utente. L'anteprima di
|
||||
stampa (`KhPrintPreview`, mockup 025) mostra il documento come foglio `.kh-sheet` largo 210 mm e alto almeno 297 mm,
|
||||
con ingrandimento 75/100/125%; `@media print` nasconde tutto tranne il foglio e imposta `@page` A4 senza margini.
|
||||
La classe `.paper` di `mockup.css` resta per le anteprime piccole dentro le pagine.
|
||||
|
||||

|
||||
*Khaemhat 0.3.0 — l'anteprima di stampa del documento di prova.*
|
||||
|
||||
## Regola di aggiornamento
|
||||
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
# Fiscalità italiana
|
||||
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M4-M10)
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.4.0 (codici e regole di base; il resto con M5-M10)
|
||||
> **Modulo di licenza:** CORE, ACCT, EINV, INTRA · **Specifica:** SPEC §11.1, §11.3-§11.9, §14
|
||||
|
||||
Questa pagina raccoglie in un solo posto i **codici e le regole fiscali italiane** che Khaemhat usa: tipi documento
|
||||
SDI, nature IVA, modalità e condizioni di pagamento, regimi fiscali, codici tributo F24 e scadenze. Serve come
|
||||
riferimento rapido mentre si compilano anagrafiche, codici IVA e documenti.
|
||||
|
||||
Tutte queste tabelle sono **caricate dai dati di base** (pacchetto dati, per esempio `IT 2026.2`) e si aggiornano da
|
||||
Tutte queste tabelle sono **caricate dai dati di base** (pacchetto dati, per esempio `IT 2026.3`) e si aggiornano da
|
||||
**Amministrazione → Dati di base e di esempio** con **Aggiorna tabelle di base**. Le descrizioni ufficiali complete
|
||||
sono quelle delle *specifiche tecniche della fattura elettronica* dell'Agenzia delle Entrate, caricate nel seed: in
|
||||
caso di dubbio fa fede il testo mostrato dal programma, non questa pagina.
|
||||
@@ -58,6 +58,9 @@ caso di dubbio fa fede il testo mostrato dal programma, non questa pagina.
|
||||
| TD28 | Acquisti da San Marino con IVA (fattura cartacea) | acquisti |
|
||||
| TD29 | Comunicazione per omessa o irregolare fatturazione | regolarizzazione (introdotto con le specifiche v1.9) |
|
||||
|
||||
Versione delle specifiche tecniche seguita: **1.9.1** (pubblicata dall'Agenzia il 31 marzo 2026, in vigore dal
|
||||
15 maggio 2026; non cambia le code list della 1.9, che ha introdotto TD29 e ridefinito TD20).
|
||||
|
||||
Formati di trasmissione: **FPR12** (verso privati), **FPA12** (verso pubbliche amministrazioni), **FSM10** (fattura
|
||||
semplificata). Nome del file: `IT<partita IVA>_<progressivo>.xml`.
|
||||
|
||||
@@ -70,7 +73,7 @@ codice IVA sulla riga del documento la natura viene compilata da sola.
|
||||
|---|---|---|
|
||||
| N1 | Escluse ex art. 15 DPR 633/72 | `ESC15` |
|
||||
| N2.1 | Non soggette ad IVA ai sensi degli artt. da 7 a 7-septies DPR 633/72 | `FC7` |
|
||||
| N2.2 | Non soggette - altri casi | fuori campo altre (anche fatture da forfettari) |
|
||||
| N2.2 | Non soggette - altri casi | `NS`, `FORF` (operazioni in regime forfettario) |
|
||||
| N3.1 | Non imponibili - esportazioni | `NI8` |
|
||||
| N3.2 | Non imponibili - cessioni intracomunitarie | `NI41` |
|
||||
| N3.3 | Non imponibili - cessioni verso San Marino | `NI71` |
|
||||
@@ -79,11 +82,25 @@ codice IVA sulla riga del documento la natura viene compilata da sola.
|
||||
| N3.6 | Non imponibili - altre operazioni che non concorrono alla formazione del plafond | — |
|
||||
| N4 | Esenti | `ESE10` |
|
||||
| N5 | Regime del margine / IVA non esposta in fattura | — (regime del margine previsto in fase 2) |
|
||||
| N6.1 … N6.9 | Inversione contabile (reverse charge): rottami (N6.1), oro e argento (N6.2), subappalto edile (N6.3), cessione di fabbricati (N6.4), telefoni cellulari (N6.5), prodotti elettronici (N6.6), prestazioni comparto edile e connessi (N6.7), settore energetico (N6.8), altri casi (N6.9) | `RC17` (varianti per sotto-codice) |
|
||||
| N6.1 … N6.9 | Inversione contabile (reverse charge): rottami (N6.1), oro e argento (N6.2), subappalto edile (N6.3), cessione di fabbricati (N6.4), telefoni cellulari (N6.5), prodotti elettronici (N6.6), prestazioni comparto edile e connessi (N6.7), settore energetico (N6.8), altri casi (N6.9) | `RC74` (N6.1), `RC17O` (N6.2), `RC17A` (N6.3), `RC17F` (N6.4), `RC17B` (N6.5), `RC17C` (N6.6), `RC17E` (N6.7), `RC17N` (N6.8), `RC17` (N6.9) |
|
||||
| N7 | IVA assolta in altro stato UE | — |
|
||||
|
||||
Altri codici IVA di base: aliquote **22**, **10**, **5**, **4**; **SPLIT** (scissione dei pagamenti), **NS**,
|
||||
**indetraibili 50% e 100%**, codici per **forfettari**.
|
||||
Altri codici IVA di base: aliquote **22**, **10**, **5**, **4**; **22SP** e **10SP** (scissione dei pagamenti,
|
||||
esigibilità S); **22I50** e **22I100** (IVA 22% indetraibile al 50% e al 100%).
|
||||
|
||||
I codici N2, N3 e N6 senza sotto-codice non sono più accettati dallo SDI: Khaemhat li riconosce nei documenti vecchi
|
||||
ma non li lascia scegliere su un codice IVA nuovo.
|
||||
|
||||
**Controlli sul codice IVA.** Salvando un codice IVA Khaemhat verifica che:
|
||||
|
||||
- un'aliquota maggiore di zero non abbia natura e un'aliquota zero ce l'abbia;
|
||||
- la natura esista e sia ancora valida;
|
||||
- la scissione dei pagamenti abbia un'aliquota;
|
||||
- l'inversione contabile (N6.x) abbia esigibilità immediata;
|
||||
- la percentuale di indetraibilità sia fra 0 e 100.
|
||||
|
||||
Sono solo **avvisi** (il codice si salva) un'aliquota diversa da 4, 5, 10 e 22 (per esempio le percentuali di
|
||||
compensazione agricole) e la mancanza del riferimento normativo, che va stampato in fattura quando c'è la natura.
|
||||
|
||||
**Esigibilità** (campo del codice IVA): **I** immediata, **D** differita, **S** scissione dei pagamenti (split
|
||||
payment).
|
||||
@@ -181,12 +198,13 @@ Khaemhat propone il codice tributo e prepara i **dati F24** da passare a interme
|
||||
| Adempimento | Regola | Note in Khaemhat |
|
||||
|---|---|---|
|
||||
| Liquidazione IVA mensile | versamento entro il **16 del mese successivo** | la conferma della liquidazione **blocca il periodo** |
|
||||
| Liquidazione IVA trimestrale | versamento entro il 16 del secondo mese successivo al trimestre (per il secondo trimestre vale la proroga estiva di agosto), con **interessi dell'1%**; il quarto trimestre si versa con il saldo annuale | interessi calcolati in automatico |
|
||||
| Liquidazione IVA trimestrale | versamento entro il 16 del secondo mese successivo al trimestre (per il secondo trimestre vale la proroga estiva di agosto), con **interessi dell'1%**; il quarto trimestre si versa con il saldo annuale entro il 16 marzo | interessi calcolati in automatico |
|
||||
| Scadenze in agosto e nei festivi | i versamenti fra il 1° e il 20 agosto slittano al **20 agosto**; una scadenza di sabato, domenica o festivo slitta al primo giorno lavorativo | festivi nazionali, Pasquetta e, dal 2026, il 4 ottobre |
|
||||
| Versamento minimo | importo fino a **€ 25,82** non versato e riportato al periodo successivo | valore della specifica; da verificare in sviluppo rispetto alla norma vigente |
|
||||
| Acconto IVA | entro il **27 dicembre**; metodo **storico**, **previsionale** o **analitico** | scelta del metodo nella liquidazione di dicembre |
|
||||
| LIPE | 1° trimestre entro 31 maggio, 2° entro 16 settembre, 3° entro 30 novembre, 4° entro fine febbraio (o nella dichiarazione annuale) | XML LIPE generato dalla liquidazione |
|
||||
| Ritenute d'acconto operate | versamento entro il **16 del mese successivo** al pagamento della parcella (1040/1038) | la ritenuta nasce al pagamento della fattura |
|
||||
| Imposta di bollo | **€ 2,00** se le operazioni esenti, non imponibili o fuori campo superano **€ 77,47** | applicato in automatico; addebito al cliente o a carico azienda |
|
||||
| Imposta di bollo | **€ 2,00** se le operazioni esenti, non imponibili o fuori campo superano **€ 77,47** | contano le nature N1, N2.1, N2.2, N3.5, N3.6, N4, N5; non contano esportazioni (N3.1), cessioni intracomunitarie (N3.2), San Marino (N3.3), operazioni assimilate (N3.4), inversione contabile (N6.x) e N7 |
|
||||
| Bollo virtuale | versamento trimestrale: 1° trimestre entro 31 maggio, 2° entro 30 settembre, 3° entro 30 novembre, 4° entro fine febbraio; con importi bassi i primi trimestri possono slittare (soglia di € 5.000) | elenco da confrontare con quello proposto dall'Agenzia |
|
||||
| Autofatture e integrazioni (TD16-TD19) | XML da trasmettere **entro il 15 del mese successivo** | promemoria nella dashboard |
|
||||
| Fattura differita (TD24) | emissione entro il 15 del mese successivo a quello delle consegne documentate da DDT | procedura **Fatturazione differita** |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Khaemhat
|
||||
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** 0.0.1 (M0, pagina "in costruzione"; sviluppo in corso)
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (M4; sviluppo in corso)
|
||||
|
||||

|
||||
|
||||
@@ -12,8 +12,8 @@ Docker** e gestisce più aziende sulla stessa installazione.
|
||||
Il nome viene da uno scriba dell'antico Egitto che sovrintendeva ai granai del regno: vedi
|
||||
[Origine del nome](Origine-del-nome).
|
||||
|
||||
> Il software è **in fase di progettazione**: questa wiki descrive ciò che verrà costruito, milestone dopo
|
||||
> milestone. Ogni pagina indica nel riquadro iniziale lo stato (*bozza* finché la funzione non è consegnata) e la
|
||||
> Il software è **in sviluppo** (versioni 0.x): questa wiki descrive ciò che è già consegnato e ciò che verrà
|
||||
> costruito, milestone dopo milestone. Ogni pagina indica nel riquadro iniziale lo stato (*bozza* finché la funzione non è consegnata) e la
|
||||
> milestone in cui arriva. Vedi la [Roadmap](Roadmap).
|
||||
|
||||
## Per iniziare
|
||||
|
||||
@@ -1,103 +1,169 @@
|
||||
# Import/Export
|
||||
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M4; saldi e partite di apertura in M12)
|
||||
> **Modulo di licenza:** CORE (piano dei conti, saldi e partite: ACCT/FIN) · **Livello richiesto:** amministratore · **Specifica:** SPEC §11.7, §12.12
|
||||
> **Stato:** completa per M4 · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (scrittura di giacenze iniziali in M6, piano dei conti in M7; saldi e partite di apertura in M7 e M9)
|
||||
> **Modulo di licenza:** CORE (piano dei conti: ACCT) · **Livello richiesto:** amministratore, oppure permesso di scrittura o di export dell'entità · **Specifica:** SPEC §11.7, §12.12 · **Decisione:** ADR 0031
|
||||
|
||||
## A cosa serve
|
||||
|
||||
La procedura guidata di **Import/Export** porta in Khaemhat i dati che arrivano da un altro gestionale o da un
|
||||
foglio di calcolo e li esporta in formati aperti. È lo strumento per l'**avviamento** di un'azienda: anagrafiche,
|
||||
articoli, listini, giacenze iniziali, piano dei conti, saldi iniziali e partite aperte.
|
||||
articoli, prezzi, giacenze iniziali e piano dei conti.
|
||||
|
||||
## Dove si trova
|
||||
|
||||
**Amministrazione → Import/Export** (titolo: *Import / export dati*). Ogni importazione si apre in una scheda
|
||||
propria (es. *Import clienti*).
|
||||
**Amministrazione → Import / export dati** (indirizzo `/amministrazione/import-export`). Il tasto **F1** apre questa
|
||||
pagina.
|
||||
|
||||
## Schermata
|
||||
|
||||

|
||||
|
||||
*Mockup 077 — a sinistra i quattro passi della procedura guidata (Origine, Mappatura colonne, Validazione,
|
||||
Importazione) e le opzioni; a destra l'**Anteprima e validazione** con l'esito riga per riga; in alto **Scarica report
|
||||
errori** e **Importa N righe** (anteprima ridotta)*
|
||||
Importazione), le opzioni e il riquadro **Esporta e modelli**; a destra la mappatura o l'**Anteprima e validazione**
|
||||
con l'esito riga per riga; in alto **Scarica report errori** e **Importa N righe***
|
||||
|
||||

|
||||
*Khaemhat 0.4.0 — il passo Mappatura colonne con un CSV di clienti: le dieci colonne si abbinano da sole, anche *P.IVA*, *Città* e *Prov*.*
|
||||
|
||||

|
||||
*Khaemhat 0.4.0 — l'anteprima dello stesso file: un comune dedotto dal CAP (avviso), un cliente nuovo e tre righe escluse (partita IVA mancante ed e-mail non valida, codice ripetuto, pagamento inesistente).*
|
||||
|
||||
## Formati
|
||||
|
||||
| Formato | Uso |
|
||||
| Formato | Lettura | Scrittura (export e modelli) |
|
||||
|---|---|---|
|
||||
| **CSV** (`.csv`, `.txt`) | separatore `;`, `,` o tabulazione (dedotto dalla riga di intestazione); UTF-8 con o senza BOM, altrimenti Windows-1252 | `;`, UTF-8 con BOM, numeri con la virgola, date `gg/mm/aaaa`, sì/no come `VERO`/`FALSO` |
|
||||
| **XLSX** | il primo foglio, intestazioni nella prima riga | un foglio con le intestazioni bloccate |
|
||||
| **JSON** | un elenco di oggetti con le colonne come chiavi; per il piano dei conti anche `khaemhat-coa.json` | lo stesso elenco (numeri e sì/no come valori JSON) |
|
||||
|
||||
La prima riga contiene sempre le **intestazioni**. Le righe vuote si saltano. Al massimo **50.000 righe** e **25 MB**
|
||||
per file.
|
||||
|
||||
**Valori accettati in tutte le colonne:**
|
||||
|
||||
- **numeri** all'italiana (`1.234,56`, `€ 12,5`, `22 %`) o con il punto decimale (`1234.56`, come li scrivono Excel e
|
||||
JSON);
|
||||
- **date** `gg/mm/aaaa` (anche `g/m/aa`, `gg-mm-aaaa`, `gg.mm.aaaa`), `aaaa-mm-gg`, `aaaammgg` o il numero di serie
|
||||
di una cella data di Excel;
|
||||
- **sì/no** come `sì`, `si`, `x`, `1`, `VERO`, `true` oppure `no`, `0`, `FALSO`, `false`;
|
||||
- le **parole di una scelta** (es. `tipo_soggetto`) senza badare a maiuscole, accenti, spazi e punteggiatura
|
||||
(`Extra UE` = `extra-ue`, `P.A.` = `pa`).
|
||||
|
||||
## Entità e colonne
|
||||
|
||||
Le intestazioni si abbinano da sole quando sono uguali ai nomi qui sotto o a un nome simile (es. `P.IVA`,
|
||||
`Partita IVA`, `piva` → `partita_iva`; `Città` → `comune`). Le colonne con **\*** servono per un record nuovo.
|
||||
|
||||
### Clienti e fornitori
|
||||
|
||||
`codice`, `ragione_sociale`, `nome`, `cognome`, `tipo_soggetto`, `partita_iva`, `codice_fiscale`, `rea`, `indirizzo`,
|
||||
`civico`, `cap`, `comune`, `provincia`, `nazione`, `telefono`, `email`, `pec`, `sito`, `codice_destinatario`,
|
||||
`categoria`; per i **clienti** anche `agente`, `pagamento`, `listino`, `sconto1`, `sconto2`, `fido`, `iban`, `note`;
|
||||
per i **fornitori** `pagamento`, `iban`, `note`.
|
||||
|
||||
| Colonna | Valori |
|
||||
|---|---|
|
||||
| **CSV** | testo con separatore `;` e codifica UTF-8 (formato più comune per gli scambi) |
|
||||
| **XLSX** | foglio Excel con le stesse colonne del CSV |
|
||||
| **JSON** | scambio completo fra installazioni Khaemhat (es. piano dei conti con voci di bilancio e causali) |
|
||||
| `tipo_soggetto` | `impresa`, `privato`, `pa`, `ue`, `extra-ue`, `forfettario` (vuoto: impresa; con solo cognome e nome: privato) |
|
||||
| `nazione` | codice ISO a due lettere (`IT`, `DE`...) |
|
||||
| `categoria`, `agente`, `pagamento`, `listino` | il **codice** della tabella (vedi [Tabelle azienda](Tabelle-azienda)) |
|
||||
| `iban` | aggiunge il conto se non c'è già (il primo diventa predefinito) |
|
||||
|
||||
## Entità importabili
|
||||
Ragione sociale (o cognome e nome per un privato), partita IVA e gli altri controlli sono quelli della scheda (vedi
|
||||
[Anagrafiche](Anagrafiche)).
|
||||
|
||||
| Entità | Note |
|
||||
### Articoli
|
||||
|
||||
`codice`, `descrizione`\*, `descrizione_estesa`, `tipo`, `categoria`, `um`, `iva_vendite`, `iva_acquisti`, `ean`,
|
||||
`nc8`, `marca`, `produttore`, `peso_netto`, `peso_lordo`, `a_magazzino`, `magazzino`, `scorta_minima`,
|
||||
`punto_riordino`, `lotto_riordino`, `prezzo`, `costo_standard`, `conto_ricavo`, `conto_costo`, `note`.
|
||||
|
||||
| Colonna | Valori |
|
||||
|---|---|
|
||||
| **Anagrafiche** (clienti, fornitori) | verifica partita IVA (VIES per i soggetti UE), comune da CAP |
|
||||
| **Articoli** | |
|
||||
| **Listini** | |
|
||||
| **Giacenze iniziali** | quantità di apertura per deposito |
|
||||
| **Piano dei conti** | tracciato descritto sotto; verifica della coerenza gerarchica |
|
||||
| **Saldi iniziali** | saldi di apertura dei conti |
|
||||
| **Partite di apertura** | crediti e debiti aperti verso clienti e fornitori, con scadenze |
|
||||
| `tipo` | `merce`, `servizio`, `spesa`, `descrittivo`, `cespite` (vuoto: merce) |
|
||||
| `categoria`, `um`, `iva_vendite`, `iva_acquisti`, `magazzino` | il **codice** della tabella (`PZ`, `22`, il codice del deposito) |
|
||||
| `a_magazzino` | sì/no; un articolo che non è merce non è mai a magazzino |
|
||||
| `prezzo` | il prezzo dell'articolo; i prezzi di listino si importano con l'entità *Prezzi* |
|
||||
|
||||
Le colonne disponibili per ogni entità corrispondono ai campi della relativa scheda (vedi [Anagrafiche](Anagrafiche),
|
||||
[Articoli e listini](Articoli-e-listini), [Magazzino](Magazzino), [Contabilità](Contabilita),
|
||||
[Scadenzario](Scadenzario)); i tracciati completi saranno pubblicati con i rispettivi moduli.
|
||||
Il codice generato usa la regola degli articoli, di solito `{categoria}-{seq:0000}`: in quel caso la categoria è
|
||||
obbligatoria. Unità alternative, codici alternativi, fornitori e sostitutivi restano quelli della scheda (vedi
|
||||
[Articoli e listini](Articoli-e-listini)).
|
||||
|
||||
### Prezzi di listino e netti cliente
|
||||
|
||||
`articolo`\*, `listino`, `cliente`, `prezzo`\*, `valido_dal`. Ogni riga ha **il listino oppure il cliente** (prezzo
|
||||
netto), non entrambi. Stesso articolo, listino o cliente e data: il prezzo si sostituisce; una data nuova aggiunge
|
||||
un prezzo che vale da quel giorno, come nella griglia dei listini. Le righe senza errori si scrivono tutte insieme.
|
||||
|
||||
### Giacenze iniziali (solo verifica fino a M6)
|
||||
|
||||
`articolo`\*, `deposito` (vuoto: il deposito dell'articolo), `quantita`\* (maggiore di zero), `costo_unitario`.
|
||||
L'articolo deve essere merce gestita a magazzino. Il controllo serve a preparare il file: la scrittura del movimento
|
||||
di apertura arriva con il [Magazzino](Magazzino).
|
||||
|
||||
### Piano dei conti (solo verifica fino a M7)
|
||||
|
||||
Vedi il tracciato più sotto.
|
||||
|
||||
## Come si importa
|
||||
|
||||
### 1. Origine
|
||||
|
||||
1. Scegli l'**Entità** (es. *Clienti*).
|
||||
2. Carica il file. Khaemhat riconosce numero di righe, codifica e separatore (es. *clienti.csv · 1.284 righe ·
|
||||
UTF-8 · separatore ;*).
|
||||
3. Imposta le opzioni:
|
||||
1. Scegli l'**Entità**.
|
||||
2. Imposta le opzioni:
|
||||
|
||||
| Opzione | Valori |
|
||||
|---|---|
|
||||
| **Se il codice esiste** | *Aggiorna* il record esistente oppure lo salta (valori esatti definiti in sviluppo) |
|
||||
| **Codici mancanti** | *Genera automatici* secondo le regole dei codici automatici (vedi [Tabelle azienda](Tabelle-azienda)) |
|
||||
| **Verifica P.IVA (VIES per UE)** | controlla le partite IVA |
|
||||
| **Compila comune da CAP** | completa comune e provincia dal CAP |
|
||||
| Opzione | Valori | Entità |
|
||||
|---|---|---|
|
||||
| **Se il codice esiste** | *Aggiorna* (le celle piene cambiano il record, le vuote lasciano ciò che c'è) oppure *Salta la riga* (avviso) | clienti, fornitori, articoli, prezzi |
|
||||
| **Codice mancante** | *Genera automatico* con le regole dei codici automatici (vedi [Tabelle azienda](Tabelle-azienda)) oppure *Errore sulla riga* | clienti, fornitori, articoli |
|
||||
| **Verifica P.IVA su VIES (UE)** | controlla su VIES le partite IVA dei soggetti UE durante l'import (più lento) | clienti, fornitori |
|
||||
| **Completa comune da CAP** | completa comune e provincia da un CAP con un solo comune, o il CAP da un comune con un solo CAP (avviso) | clienti, fornitori |
|
||||
|
||||
3. Scegli il **file**. Il passo mostra nome, righe e dimensione (es. *clienti_2026.csv · 1.284 righe · 37 KB*).
|
||||
|
||||
Un codice scritto nel file per un record nuovo deve essere ammesso dalla regola dei codici (**codice manuale**): per
|
||||
mantenere i codici del gestionale precedente lascia attiva quell'opzione nella regola. Un codice già presente in una
|
||||
riga precedente del file è un errore; il codice di un'anagrafica di altro tipo (un fornitore fra i clienti) anche.
|
||||
|
||||
### 2. Mappatura colonne
|
||||
|
||||
Khaemhat abbina le colonne del file ai campi dell'entità (es. *12 di 14 colonne abbinate*). Controlla gli
|
||||
abbinamenti proposti, correggi quelli sbagliati e indica le colonne da ignorare.
|
||||
Khaemhat abbina le colonne del file ai campi dell'entità (es. *14 di 16 colonne abbinate*) e mostra per ognuna il
|
||||
valore della prima riga. Correggi gli abbinamenti con l'elenco **Campo**; scegli *Ignora* per le colonne da
|
||||
tralasciare. Un campo va su una sola colonna. Un avviso elenca i campi obbligatori non abbinati. Premi **Verifica le
|
||||
righe**.
|
||||
|
||||
### 3. Validazione
|
||||
|
||||
Ogni riga viene controllata come se fosse inserita a mano. L'**Anteprima e validazione** mostra le prime righe con
|
||||
l'**Esito**:
|
||||
Ogni riga viene controllata come se fosse inserita a mano nella scheda. L'**Anteprima e validazione** mostra fino a
|
||||
500 righe con l'**Esito** e il motivo accanto; le celle con un problema sono evidenziate.
|
||||
|
||||
| Esito | Significato | Esempio |
|
||||
|---|---|---|
|
||||
| **OK** | riga importabile | |
|
||||
| **Avviso** | riga importabile con una correzione proposta | *CAP mancante: proposto 12100* |
|
||||
| **Errore** | riga non importabile | *P.IVA non valida* |
|
||||
| **Nuovo** / **Aggiorna** | riga importabile | |
|
||||
| **Avviso** | riga importabile con una correzione proposta o una nota | *Comune: dedotto dal CAP (Forlì)* |
|
||||
| **Errore** | riga esclusa | *Partita IVA non valida*, *Il codice XX non esiste* |
|
||||
|
||||
Il filtro **Tutte / Solo problemi** mostra solo le righe con avvisi o errori. **Scarica report errori** scarica
|
||||
l'elenco delle righe problematiche con il motivo: correggile nel file di origine e reimportale.
|
||||
Il filtro **Tutte / Solo problemi** mostra solo le righe con avvisi o errori. **Scarica report errori** scarica un CSV
|
||||
con riga, codice, colonna, esito e messaggio: correggi il file di origine e reimportalo. **Mappatura** torna al passo
|
||||
precedente.
|
||||
|
||||
### 4. Importazione
|
||||
|
||||
Il riepilogo indica quante righe verranno **create** e quante **aggiornate**. Premi **Importa N righe**: le righe con
|
||||
errori vengono escluse, le altre importate. L'esito finisce nel [Log](Log) e ogni record creato ha il suo storico.
|
||||
**Importa N righe** chiede conferma e scrive le righe senza errori, una alla volta come un salvataggio della scheda
|
||||
(i prezzi tutti insieme). Il riepilogo indica creati, aggiornati, saltati e righe con errori; ogni record ha il suo
|
||||
storico e l'esito finisce nel [Log](Log) (sezione *Sistema*). **Nuova importazione** ricomincia.
|
||||
|
||||
**Consiglio:** prova l'importazione su un'azienda clonata (vedi [Istanza e database](Istanza-e-database)) prima di
|
||||
farla sull'azienda reale, soprattutto per saldi e partite di apertura.
|
||||
farla sull'azienda reale.
|
||||
|
||||
## Tracciato del piano dei conti
|
||||
|
||||
In Italia non esiste uno standard per lo scambio del piano dei conti, perciò Khaemhat definisce il proprio
|
||||
tracciato. Il piano standard per PMI è già **precaricato** con le tabelle di base; l'importazione serve a chi vuole
|
||||
usare il piano del proprio commercialista o del gestionale precedente.
|
||||
tracciato. Il piano standard per PMI sarà **precaricato** con la contabilità (M7); l'importazione serve a chi vuole
|
||||
usare il piano del proprio commercialista o del gestionale precedente. Fino a M7 il file si **verifica** soltanto.
|
||||
|
||||
### CSV e XLSX
|
||||
|
||||
Separatore `;`, una riga per conto, con le colonne:
|
||||
Una riga per conto, con le colonne:
|
||||
|
||||
```
|
||||
codice;descrizione;livello;padre;natura;tipo;voce_cee;riclassifica;flag
|
||||
@@ -105,54 +171,78 @@ codice;descrizione;livello;padre;natura;tipo;voce_cee;riclassifica;flag
|
||||
|
||||
| Colonna | Contenuto |
|
||||
|---|---|
|
||||
| `codice` | codice gerarchico nella forma `MM.CC.SSS` (mastro, conto, sottoconto) |
|
||||
| `descrizione` | descrizione del conto |
|
||||
| `livello` | livello nella gerarchia (mastro, conto, sottoconto) |
|
||||
| `padre` | codice del conto padre (vuoto per i mastri) |
|
||||
| `natura` | natura del conto (es. patrimoniale/economico; valori ammessi definiti in sviluppo) |
|
||||
| `tipo` | tipo del conto (valori ammessi definiti in sviluppo) |
|
||||
| `codice`\* | da 1 a 3 parti separate da punto: mastro, conto, sottoconto (`01`, `01.10`, `01.10.001`) |
|
||||
| `descrizione`\* | descrizione del conto |
|
||||
| `livello` | 1, 2 o 3: il numero di parti del codice (se indicato deve corrispondere) |
|
||||
| `padre` | il codice senza l'ultima parte (se indicato deve corrispondere); deve essere nel file |
|
||||
| `natura` | `attivo`, `passivo`, `costo`, `ricavo`, `ordine`; obbligatoria sui mastri, ereditata dai sottoconti e uguale a quella del padre |
|
||||
| `tipo` | `generico` (vuoto), `clienti`, `fornitori`, `banca`, `cassa`, `iva`, `erario` |
|
||||
| `voce_cee` | voce dello schema di bilancio CEE (artt. 2424/2425 c.c.) |
|
||||
| `riclassifica` | voce del bilancio riclassificato |
|
||||
| `flag` | indicatori del conto (partitario clienti/fornitori, rilevante IVA, chiusura automatica, movimentabile, attivo; codifica definita in sviluppo) |
|
||||
| `flag` | lettere: `M` movimentabile, `I` rilevante IVA, `P` con partitario clienti/fornitori, `C` chiusura automatica, `X` disattivato |
|
||||
|
||||
Esempio di righe (valori indicativi):
|
||||
Esempio:
|
||||
|
||||
```
|
||||
codice;descrizione;livello;padre;natura;tipo;voce_cee;riclassifica;flag
|
||||
01;Immobilizzazioni;1;;…;…;;;
|
||||
01.01;Immobilizzazioni immateriali;2;01;…;…;…;…;
|
||||
01.01.001;Software;3;01.01;…;…;…;…;…
|
||||
01;Attivo;1;;attivo;;;;
|
||||
01.10;Crediti verso clienti;2;01;;;;;
|
||||
01.10.001;Clienti Italia;3;01.10;;clienti;CII1;;MP
|
||||
01.20;Disponibilità liquide;2;01;;;;;
|
||||
01.20.001;Banca;3;01.20;;banca;CIV1;;M
|
||||
```
|
||||
|
||||
Il file **XLSX** usa le stesse colonne, nella prima riga del primo foglio.
|
||||
|
||||
### JSON (`khaemhat-coa.json`)
|
||||
|
||||
Per l'export e l'import **completo** fra installazioni Khaemhat: contiene **conti**, **voci di bilancio**, **causali
|
||||
contabili** e **mappature**. È il formato da usare per copiare il piano dei conti da un'azienda all'altra.
|
||||
Per lo scambio **completo** fra installazioni Khaemhat:
|
||||
|
||||
### Controlli in importazione
|
||||
```json
|
||||
{
|
||||
"format": "khaemhat-coa",
|
||||
"version": 1,
|
||||
"accounts": [ { "codice": "01", "descrizione": "Attivo", "natura": "attivo" } ],
|
||||
"statementLines": [],
|
||||
"journalTemplates": [],
|
||||
"mappings": []
|
||||
}
|
||||
```
|
||||
|
||||
- **Coerenza gerarchica**: ogni conto deve avere un padre esistente e un livello coerente con il codice.
|
||||
- Gli altri controlli (ad esempio codici duplicati o voci CEE inesistenti) seguono le regole del piano dei conti e
|
||||
saranno precisati in sviluppo.
|
||||
`accounts` ha le stesse colonne del CSV. Voci di bilancio (`statementLines`), causali (`journalTemplates`) e
|
||||
mappature (`mappings`) si contano già nella mappatura e si importano con la contabilità (M7).
|
||||
|
||||
## Export
|
||||
### Controlli
|
||||
|
||||
I dati si esportano negli stessi formati:
|
||||
- codice di 1-3 parti, livello e padre coerenti con il codice, padre presente nel file;
|
||||
- natura indicata sui mastri e uguale a quella del padre;
|
||||
- **solo i conti senza sottoconti** sono movimentabili (`M` su un conto con sottoconti è un errore; un sottoconto
|
||||
senza `M` è un avviso);
|
||||
- lettere di `flag` sconosciute e codici ripetuti sono errori.
|
||||
|
||||
- dalla procedura guidata, per le entità sopra elencate (l'obiettivo è che un file esportato si possa reimportare
|
||||
con lo stesso tracciato; dettagli definiti in sviluppo);
|
||||
- dalle griglie e dai report (CSV/XLSX/PDF), dal pulsante **Genera file/esporta**;
|
||||
- il piano dei conti completo in `khaemhat-coa.json`.
|
||||
## Export e modelli
|
||||
|
||||
Gli export richiedono il flag utente **Può esportare dati** (vedi [Utenti e permessi](Utenti-e-permessi)).
|
||||
Il riquadro **Esporta e modelli** usa l'entità scelta in alto:
|
||||
|
||||
- **Formato**: CSV, XLSX o JSON;
|
||||
- **Scarica modello**: il file con le sole intestazioni (in JSON un oggetto con i valori vuoti; per il piano dei conti
|
||||
l'oggetto `khaemhat-coa`);
|
||||
- **Esporta**: tutti i record con le **stesse colonne dell'import**, così il file si corregge e si reimporta
|
||||
(nome `clienti-2026-11-12.csv`). I codici delle tabelle sono esportati come codici.
|
||||
|
||||
L'export richiede il flag utente **Può esportare dati** e il permesso di export dell'entità (per le anagrafiche
|
||||
*Esportare anagrafiche*) (vedi [Utenti e permessi](Utenti-e-permessi)). Giacenze e piano dei conti hanno per ora solo
|
||||
il modello. Le griglie esportano anche dal proprio menu (CSV/XLSX).
|
||||
|
||||
## Domande frequenti
|
||||
|
||||
- **Il file ha la virgola come separatore.** Usa il separatore `;` (standard per i CSV in italiano, dove la virgola è
|
||||
il separatore decimale) oppure salva in XLSX.
|
||||
- **Le lettere accentate appaiono sbagliate.** Salva il CSV in UTF-8.
|
||||
- **Il file ha la virgola come separatore.** Va bene: il separatore si deduce dalla riga di intestazione.
|
||||
- **Le lettere accentate appaiono sbagliate.** Khaemhat legge UTF-8 e, in alternativa, Windows-1252 (il CSV di Excel
|
||||
per l'Italia); con altre codifiche salva in UTF-8 o in XLSX.
|
||||
- **Il codice del vecchio gestionale viene rifiutato.** La regola dei codici di quell'archivio non ammette il codice
|
||||
manuale: abilitalo in *Preferenze azienda → Codici automatici* (`/tabelle/preferenze`), oppure scegli *Genera automatico* e togli la colonna.
|
||||
- **Ho importato con errori: devo rifare tutto?** No: correggi solo le righe del report e reimportale; con *Aggiorna*
|
||||
le righe già importate si aggiornano senza doppioni.
|
||||
- **Posso importare documenti (fatture, DDT) da un altro gestionale?** Non con questa procedura: le fatture
|
||||
elettroniche di acquisto si importano dall'XML SDI (vedi [Acquisti](Acquisti) e
|
||||
[Fatturazione elettronica](Fatturazione-elettronica)).
|
||||
@@ -160,4 +250,4 @@ Gli export richiedono il flag utente **Può esportare dati** (vedi [Utenti e per
|
||||
## Pagine correlate
|
||||
|
||||
[Dati di base e di esempio](Dati-di-base-e-esempio) · [Contabilità](Contabilita) · [Anagrafiche](Anagrafiche) ·
|
||||
[Articoli e listini](Articoli-e-listini) · [Scadenzario](Scadenzario) · [Tabelle azienda](Tabelle-azienda) · [Primi passi](Primi-passi)
|
||||
[Articoli e listini](Articoli-e-listini) · [Magazzino](Magazzino) · [Tabelle azienda](Tabelle-azienda) · [Primi passi](Primi-passi)
|
||||
@@ -189,6 +189,7 @@ obbligatoria, termina con un messaggio che indica quale.
|
||||
| `KHAEMHAT_SEED_DEMO` | no | `false` | dati di esempio, solo su database vuoto |
|
||||
| `KHAEMHAT_UPDATE_FEED` | no | `https://gitea.encke-hake.ts.net/api/v1/packages/BalboSoft?type=container&q=khaemhat` | API dei pacchetti Gitea per il controllo aggiornamenti |
|
||||
| `KHAEMHAT_UPDATE_TOKEN` | no | token Gitea in sola lettura | solo se il pacchetto non è pubblico |
|
||||
| `KHAEMHAT_HELP_URL` | no | `https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/` | wiki online aperta da **Apri nel wiki** nell'aiuto; l'aiuto (F1) usa la copia della wiki contenuta nell'immagine e funziona anche senza Internet |
|
||||
| `TZ` | no | `Europe/Rome` | fuso orario |
|
||||
| `PUID` / `PGID` | no | `1654` / `1654` (Unraid: `99` / `100`) | utente e gruppo proprietari dei file in `/data`; l'applicazione non gira mai come root |
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Interfaccia e scorciatoie
|
||||
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M3)
|
||||
> **Stato:** completa · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.3.0 (milestone M3)
|
||||
> **Modulo di licenza:** CORE · **Specifica:** SPEC §10.2, §10.4, §10.5, §10.7, §17 (aiuto in app)
|
||||
|
||||
Questa pagina descrive come è fatta la finestra di Khaemhat e come ci si muove: barra superiore, menu laterale,
|
||||
@@ -15,6 +15,9 @@ scorciatoia nel suggerimento che compare al passaggio del mouse.
|
||||

|
||||
*Mockup 013 — la finestra con il menu laterale compresso: barra superiore, sottomenu Anagrafiche a comparsa, schede aperte, radar dei clienti e barra di stato.*
|
||||
|
||||

|
||||
*Khaemhat 0.3.0 — la finestra con il menu espanso: barra superiore, menu, scheda Home con la dashboard predefinita e barra di stato.*
|
||||
|
||||
| Zona | Dove | Contenuto |
|
||||
|---|---|---|
|
||||
| Barra superiore | in alto, scura | marchio e versione, azienda, ricerca globale, nuovo, recenti, notifiche, tema, aiuto, utente |
|
||||
@@ -66,9 +69,15 @@ Si passa da uno stato all'altro con il pulsante **Comprimi menu** in fondo al me
|
||||
**ricordato per utente** (anche fra dispositivi diversi); sotto i 1100 px di larghezza della finestra il menu parte
|
||||
compresso. Lo stato iniziale si sceglie anche in [Preferenze utente](Preferenze-utente).
|
||||
|
||||
Le aree che arrivano con le prossime versioni sono già nel menu, se la licenza e i permessi le concedono: aprendole
|
||||
compare una pagina che dice con quale milestone arrivano e quali voci conterranno.
|
||||
|
||||

|
||||
*Mockup 007 — dashboard con il menu compresso a sole icone e accento Turchese (anteprima ridotta).*
|
||||
|
||||

|
||||
*Khaemhat 0.3.0 — lo stesso menu compresso a sole icone; la freccia in basso lo riapre.*
|
||||
|
||||
## Area a schede
|
||||
|
||||
Ogni maschera aperta (un radar, un documento, una scheda anagrafica, una procedura) diventa una **scheda** in alto.
|
||||
@@ -76,9 +85,23 @@ Le schede restano "vive": passando da una all'altra non si perde nulla di quanto
|
||||
|
||||
- Un **pallino arancione** accanto al titolo indica modifiche non salvate.
|
||||
- Chiudendo una scheda con modifiche non salvate Khaemhat chiede conferma.
|
||||
- Si possono tenere aperte al massimo **12 schede**; il comportamento all'apertura della tredicesima sarà definito in
|
||||
sviluppo.
|
||||
- `Ctrl+W` chiude la scheda attiva, `Ctrl+Tab` passa alla successiva; il pulsante `+` apre una nuova scheda.
|
||||
- Si possono tenere aperte al massimo **12 schede**. Aprendone una tredicesima si chiude da sola quella usata meno di
|
||||
recente fra quelle **senza modifiche**; se tutte hanno modifiche da salvare, Khaemhat lo dice e non apre la nuova.
|
||||
- Aprire una pagina già aperta porta alla sua scheda invece di crearne un'altra.
|
||||
- `Ctrl+W` (o `Alt+W`) chiude la scheda attiva, `Ctrl+Tab` (o `Alt+PagGiù`) passa alla successiva,
|
||||
`Ctrl+Maiusc+Tab` (o `Alt+PagSu`) alla precedente; il pulsante `+` apre la ricerca per aprire una nuova pagina.
|
||||
Molti browser tengono per sé `Ctrl+W` e `Ctrl+Tab`: le varianti con `Alt` funzionano sempre.
|
||||
- Il titolo della finestra del browser segue la scheda attiva.
|
||||
|
||||
## Su tablet e telefono
|
||||
|
||||
La finestra è pensata per lo schermo di un computer, ma resta usabile su tablet (dai 768 px) e su telefono. Sotto i
|
||||
1.100 px la barra superiore nasconde il nome dell'utente, sotto i 900 px il testo della ricerca; sul telefono il
|
||||
menu laterale resta a sole icone, la barra superiore mostra solo le icone (il nome dell'azienda resta letto dagli
|
||||
screen reader) e la barra di stato mostra solo connessione, cache e versione.
|
||||
|
||||

|
||||
*Khaemhat 0.3.0 — la Home su un telefono largo 390 px.*
|
||||
|
||||
## Barra di stato
|
||||
|
||||
@@ -91,6 +114,13 @@ e la **versione** del software con il commit (es. `v1.0.0 (a3f9c1e)`).
|
||||

|
||||
*Mockup 009 — ricerca "rossi": risultati raggruppati per clienti, articoli, documenti, contabilità e azioni (anteprima ridotta).*
|
||||
|
||||

|
||||
*Khaemhat 0.3.0 — la ricerca "cli": pagine del menu e pagine dell'aiuto. Clienti, articoli e documenti si aggiungono con i rispettivi moduli.*
|
||||
|
||||
> **In questa versione** la ricerca trova le **pagine** del menu, i **comandi** (tema, menu, profilo, sessioni,
|
||||
> scorciatoie) e le **pagine dell'aiuto** (titoli e sezioni, che si aprono al punto giusto). Clienti, articoli e
|
||||
> documenti si aggiungono con le milestone che li introducono: per ora `#` e `@` dicono con quali moduli arrivano.
|
||||
|
||||
Premi `Ctrl+K` (o fai clic sulla casella di ricerca) e digita. I risultati arrivano mentre scrivi, raggruppati per
|
||||
tipo: **clienti e fornitori**, **articoli**, **documenti**, **registrazioni e conti** contabili, **azioni** (ad
|
||||
esempio *Nuova fattura per Rossi Impianti*, *Registra incasso*, *Scheda cliente a 360°*).
|
||||
@@ -103,40 +133,58 @@ esempio *Nuova fattura per Rossi Impianti*, *Registra incasso*, *Scheda cliente
|
||||
| `@` | persone (contatti, utenti) | `@ verdi` |
|
||||
|
||||
Con le frecce `↑` `↓` ti sposti tra i risultati, con `Invio` apri quello evidenziato; il piede della finestra ricorda
|
||||
anche l'apertura in una nuova scheda (`Ctrl+Invio`) e i prefissi. `Esc` chiude.
|
||||
i prefissi. `Esc` chiude. Pagine e comandi compaiono subito; gli altri risultati arrivano un attimo dopo che hai
|
||||
smesso di scrivere, da almeno due caratteri.
|
||||
|
||||
## Notifiche
|
||||
|
||||

|
||||
*Mockup 010 — pannello laterale delle notifiche con filtri e azioni (anteprima ridotta).*
|
||||
|
||||

|
||||
*Khaemhat 0.3.0 — il pannello delle notifiche con i filtri Tutte e Non lette e il pulsante Segna tutte come lette.*
|
||||
|
||||
La campanella apre un pannello laterale con le notifiche in app. Le notifiche nascono da automazioni, attività
|
||||
programmate, SDI (scarti, notifiche), scadenze, magazzino (sottoscorta) e sicurezza (ad esempio un accesso da un
|
||||
dispositivo sconosciuto). Ogni voce ha icona, titolo, dettaglio e, se serve, un'etichetta d'urgenza (*Nuova*, *Da
|
||||
gestire*, *Verifica*); un clic apre il documento o la maschera collegata.
|
||||
|
||||
In alto i filtri **Tutte**, **Non lette**, **Errori**; in basso **Segna tutte come lette** e **Impostazioni notifiche**
|
||||
(che porta alla scheda *Notifiche* di [Il mio profilo](Preferenze-utente), dove si attiva anche il riepilogo via
|
||||
e-mail).
|
||||
In alto i filtri **Tutte** e **Non lette**, con il numero di voci; in basso **Segna tutte come lette**. Ogni voce ha
|
||||
il segno di spunta per segnarla come letta; il clic sul titolo la segna e apre la maschera collegata. Il numero
|
||||
sulla campanella si aggiorna da solo ogni minuto.
|
||||
|
||||
Chi legge una notifica rivolta a tutti la segna come letta **solo per sé**: per i colleghi resta da leggere. Gli
|
||||
account di istanza vedono le notifiche di sistema (backup, attività programmate, licenza), gli utenti aziendali
|
||||
quelle della propria azienda. Il pannello mostra le ultime 100 notifiche.
|
||||
|
||||
> **In questa versione** mancano il filtro *Errori* e *Impostazioni notifiche* (riepilogo via e-mail), che arrivano
|
||||
> con le automazioni.
|
||||
|
||||
## Aiuto in app (F1)
|
||||
|
||||

|
||||
*Mockup 011 — l'aiuto della maschera Fatture: indice delle pagine a sinistra, pagina wiki con stato e revisione a destra.*
|
||||
|
||||

|
||||
*Khaemhat 0.3.0 — l'aiuto di questa pagina: indice a sinistra, pagina della wiki a destra, Apri nel wiki e Segnala un problema in alto.*
|
||||
|
||||
`F1` o il pulsante `?` aprono, in una nuova scheda, **la pagina wiki della maschera** su cui stai lavorando (ogni
|
||||
maschera ha il proprio collegamento). La pagina mostra in testa lo stato (*bozza*, *completa*), la revisione e la data
|
||||
di aggiornamento; a sinistra c'è l'indice delle pagine. In alto a destra: **Apri nel wiki** (apre la wiki completa
|
||||
nel browser) e **Segnala un problema**.
|
||||
nel browser) e **Segnala un problema** (apre una nuova segnalazione nel repository della wiki).
|
||||
|
||||
L'indirizzo della wiki è configurabile; per le installazioni senza accesso a Internet Khaemhat serve una copia della
|
||||
wiki all'indirizzo `/help` della propria istanza.
|
||||
L'aiuto è una **copia della wiki contenuta nell'immagine Docker**, all'indirizzo `/aiuto` dell'istanza (`/help` porta
|
||||
lì): funziona anche senza Internet e corrisponde sempre alla versione installata, immagini comprese. La variabile
|
||||
`KHAEMHAT_HELP_URL` cambia solo la wiki aperta da *Apri nel wiki* (vedi [Installazione Docker](Installazione-Docker)).
|
||||
|
||||
## Toolbar a icone
|
||||
|
||||

|
||||
*Mockup 020 — fattura di vendita: toolbar a icone con il suggerimento "Salva Ctrl+S", azioni contestuali, intestazione documento e righe (anteprima ridotta).*
|
||||
|
||||

|
||||
*Khaemhat 0.3.0 — il documento di prova degli sviluppatori: toolbar a icone, intestazione a tre blocchi, schede interne e righe modificabili.*
|
||||
|
||||
Ogni maschera ha una toolbar su **una sola riga**, con i comandi standard **solo icona** (senza etichetta). Passando
|
||||
con il mouse compare il suggerimento con nome e scorciatoia (disattivabile in [Preferenze utente](Preferenze-utente)).
|
||||
|
||||
@@ -183,6 +231,11 @@ anagrafiche hanno la stessa struttura:
|
||||
(oppure revisioni o partite, secondo il documento) e **totali**.
|
||||
6. Gli errori di validazione compaiono accanto al campo e in un riepilogo. Un documento emesso è **in sola lettura**:
|
||||
campi e azioni non più ammesse sono disattivati.
|
||||
7. La scheda **Storico** elenca chi ha creato e modificato il record e quando, con i valori di prima (barrati) e
|
||||
quelli nuovi; serve il permesso di lettura del record.
|
||||
|
||||

|
||||
*Khaemhat 0.3.0 — la scheda Storico del documento di prova (modifiche di esempio).*
|
||||
|
||||
## Radar
|
||||
|
||||
@@ -239,13 +292,18 @@ azioni di riga. Gli sconti accettano la forma a cascata (`5+2`).
|
||||
|
||||
| Digiti | Ottieni |
|
||||
|---|---|
|
||||
| `T` | la data di oggi |
|
||||
| `F` | la fine del mese (il riferimento esatto, data del campo o mese corrente, sarà fissato in sviluppo) |
|
||||
| `+` / `-` | un giorno avanti / indietro |
|
||||
| `T` oppure `O` | la data di oggi |
|
||||
| `F` | la fine del mese della data già nel campo (del mese corrente se il campo è vuoto) |
|
||||
| `I` | l'inizio dello stesso mese |
|
||||
| `+` / `-` | un giorno avanti / indietro rispetto alla data nel campo (o a oggi) |
|
||||
| `+30` / `-7` | trenta giorni avanti, sette indietro |
|
||||
| `15` | il 15 del mese corrente |
|
||||
| `1503` oppure `15/3` | il 15 marzo dell'anno corrente |
|
||||
| `150326` oppure `15.3.26` | il 15 marzo 2026 |
|
||||
|
||||
**Numeri e importi** (formato italiano: virgola per i decimali, punto per le migliaia): si può scrivere un
|
||||
**calcolo** che inizia con `=`, ad esempio `=10*3` diventa `30`. Altre abbreviazioni eventuali saranno definite in
|
||||
sviluppo e documentate qui.
|
||||
**calcolo** che inizia con `=`, ad esempio `=10*3` diventa `30`: valgono le quattro operazioni, le parentesi e il
|
||||
segno meno davanti a un numero, sempre con la virgola per i decimali (`=(12,5+3)*2` diventa `31`).
|
||||
|
||||
## Tabella completa delle scorciatoie
|
||||
|
||||
@@ -254,9 +312,10 @@ sviluppo e documentate qui.
|
||||
| `Ctrl+K` | ricerca globale | ovunque |
|
||||
| `F1` | aiuto della maschera corrente | ovunque |
|
||||
| `Ctrl+B` | comprime / espande il menu laterale | ovunque |
|
||||
| `Ctrl+W` | chiude la scheda attiva | ovunque |
|
||||
| `Ctrl+Tab` | passa alla scheda successiva | ovunque |
|
||||
| `Ctrl+N` | nuovo record / documento | maschere e radar |
|
||||
| `Ctrl+W` o `Alt+W` | chiude la scheda attiva | ovunque |
|
||||
| `Ctrl+Tab` o `Alt+PagGiù` | passa alla scheda successiva | ovunque |
|
||||
| `Ctrl+Maiusc+Tab` o `Alt+PagSu` | passa alla scheda precedente | ovunque |
|
||||
| `Ctrl+N` o `Alt+N` | nuovo record / documento | maschere e radar |
|
||||
| `Ctrl+S` | salva | maschere |
|
||||
| `Esc` | annulla le modifiche / chiude la finestra aperta | maschere, finestre |
|
||||
| `Ctrl+Canc` | elimina il record (se ammesso) | maschere |
|
||||
@@ -271,11 +330,11 @@ sviluppo e documentate qui.
|
||||
| `Tab` | cella o filtro successivo | griglia righe, finestra F4 |
|
||||
| `Spazio` | seleziona la riga | radar |
|
||||
| `Ctrl+D` | quadra la registrazione | prima nota (vedi [Contabilità](Contabilita)) |
|
||||
| `T`, `F`, `+`, `-` | oggi, fine mese, giorno dopo/prima | campi data |
|
||||
| `T` (`O`), `F`, `I`, `+`, `-`, `+n` | oggi, fine mese, inizio mese, giorno dopo/prima, n giorni | campi data |
|
||||
| `=` | calcolo inline (`=10*3`) | campi numerici |
|
||||
|
||||
Le scorciatoie personali si potranno adattare nelle preferenze utente (§11.12 della specifica); l'interfaccia di
|
||||
personalizzazione sarà definita in sviluppo.
|
||||
L'elenco è anche in **Il mio profilo → Scorciatoie** ([Preferenze utente](Preferenze-utente)). Le varianti con `Alt`
|
||||
esistono perché i browser non passano alla pagina `Ctrl+W`, `Ctrl+Tab` e `Ctrl+N` (ADR 0020).
|
||||
|
||||
## Permessi e licenza
|
||||
|
||||
@@ -289,6 +348,7 @@ un permesso negato.
|
||||
amministratore.
|
||||
- **Ho chiuso una scheda per sbaglio.** Se c'erano modifiche non salvate Khaemhat ti ha chiesto conferma; il
|
||||
documento salvato si ritrova con **Recenti** o con `Ctrl+K`.
|
||||
- **`Ctrl+W` chiude il browser invece della scheda.** È il browser che tiene per sé la combinazione: usa `Alt+W`.
|
||||
- **Il menu si è compresso da solo.** Sotto i 1100 px di larghezza il menu parte compresso; allarga la finestra o
|
||||
premi `Ctrl+B`.
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Preferenze utente (Il mio profilo)
|
||||
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M3)
|
||||
> **Stato:** completa · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.3.0 (milestone M3)
|
||||
> **Modulo di licenza:** CORE · **Specifica:** SPEC §7.3, §10.6, §11.12 (preferenze), §12 (Il mio profilo)
|
||||
|
||||
**Il mio profilo** raccoglie tutto ciò che riguarda te come utente: aspetto dell'interfaccia (tema, colore di
|
||||
@@ -9,25 +9,32 @@ salvati e notifiche. Ogni utente può modificare il proprio profilo senza permes
|
||||
|
||||
## Dove si trova
|
||||
|
||||
Menu utente in alto a destra (iniziali e nome) → **Il mio profilo**. Il percorso mostrato nella maschera è
|
||||
*Utente → Preferenze*.
|
||||
Menu utente in alto a destra (iniziali e nome) → **Il mio profilo**, **Aspetto e colori** o **Sessioni attive**;
|
||||
oppure `Ctrl+K` e il comando corrispondente. L'indirizzo è `/profilo`, con `?scheda=aspetto`, `pagina-iniziale`,
|
||||
`sessioni` o `scorciatoie` per aprire direttamente una scheda.
|
||||
|
||||

|
||||
*Mockup 008 — scheda Aspetto con tema Scuro (notturno) e accento Ocra selezionati; a destra l'anteprima dal vivo.*
|
||||
|
||||

|
||||
*Khaemhat 0.3.0 — la scheda Aspetto con tema Automatico e accento Nilo, i valori di partenza. Ogni scelta si applica subito alla finestra.*
|
||||
|
||||
## Schede della maschera
|
||||
|
||||
| Scheda | Contenuto |
|
||||
|---|---|
|
||||
| **Aspetto** | tema, colore di accento, densità, dimensione testo, menu laterale, suggerimenti, animazioni |
|
||||
| **Dati personali** | nome, e-mail e altri dati del tuo utente |
|
||||
| **Password e 2FA** | cambio password, attivazione della verifica in due passaggi |
|
||||
| **Sessioni** | dispositivi collegati con il tuo utente (il numero accanto al titolo indica quante sono) |
|
||||
| **Pagina iniziale** | cosa aprire all'accesso, dashboard sì/no |
|
||||
| **Layout salvati** | filtri e disposizioni di colonne memorizzati nei radar e nelle griglie |
|
||||
| **Notifiche** | quali notifiche ricevere e il riepilogo via e-mail |
|
||||
| Scheda | Contenuto | Disponibile |
|
||||
|---|---|---|
|
||||
| **Aspetto** | tema, colore di accento, densità, dimensione testo, menu laterale, suggerimenti, animazioni | 0.3.0 |
|
||||
| **Pagina iniziale** | cosa aprire all'accesso, dashboard sì/no | 0.3.0 |
|
||||
| **Sessioni** | dispositivi collegati con il tuo utente, chiusura | 0.3.0 |
|
||||
| **Scorciatoie** | l'elenco delle scorciatoie da tastiera | 0.3.0 |
|
||||
| **Dati personali** | nome, e-mail e altri dati del tuo utente | 0.3.0 |
|
||||
| **Password e 2FA** | cambio password, attivazione della verifica in due passaggi | 0.3.0 |
|
||||
| **Layout salvati** | filtri e disposizioni di colonne memorizzati nei radar e nelle griglie | non ancora |
|
||||
| **Notifiche** | quali notifiche ricevere e il riepilogo via e-mail | non ancora |
|
||||
|
||||
In alto a destra: **Ripristina** (torna ai valori predefiniti) e **Salva**.
|
||||
In alto a destra: **Valori predefiniti**, **Annulla le modifiche** e **Salva**. Ogni scelta si vede **subito** sulla
|
||||
pagina; solo **Salva** la conserva. Finché non salvi, la scheda mostra il pallino delle modifiche; chiudendola senza
|
||||
salvare torna l'aspetto di prima.
|
||||
|
||||
## Aspetto
|
||||
|
||||
@@ -35,12 +42,13 @@ In alto a destra: **Ripristina** (torna ai valori predefiniti) e **Salva**.
|
||||
|
||||
| Tema | Descrizione |
|
||||
|---|---|
|
||||
| **Chiaro** | sfondo chiaro, barra superiore scura (predefinito) |
|
||||
| **Automatico** | segue l'impostazione chiaro/scuro del sistema operativo (predefinito) |
|
||||
| **Chiaro** | sfondo chiaro, barra superiore scura |
|
||||
| **Scuro (notturno)** | sfondi scuri e colori attenuati, per lavorare con poca luce |
|
||||
| **Automatico** | segue l'impostazione chiaro/scuro del sistema operativo |
|
||||
| **Alto contrasto** | contrasto massimo per chi ha esigenze visive (livello AAA) |
|
||||
|
||||
Prima dell'accesso (pagina di login) vale il tema del sistema operativo. Le **stampe e i PDF sono sempre in tema
|
||||
Prima dell'accesso (pagina di login) vale il tema del sistema operativo. Dopo l'accesso il tema scelto è già nella
|
||||
pagina che arriva dal server, senza lampeggi. Le **stampe e i PDF sono sempre in tema
|
||||
chiaro**, qualunque sia il tema scelto.
|
||||
|
||||
Il cambio tema rapido (sole/luna) nella barra superiore passa tra chiaro e scuro senza aprire il profilo.
|
||||
@@ -68,9 +76,9 @@ I valori esatti dei colori sono nella pagina [Design UI](Design-UI).
|
||||
| Impostazione | Valori |
|
||||
|---|---|
|
||||
| **Densità** | *Comoda* (righe da 30 px, predefinita) o *Compatta* (righe da 26 px, testo e spaziature più piccoli): con la compatta in una griglia stanno più righe |
|
||||
| **Dimensione testo** | *Normale* (13 px) e altre misure che saranno definite in sviluppo |
|
||||
| **Menu laterale** | *Espanso (ricorda l'ultimo stato)* o compresso all'avvio |
|
||||
| **Carattere numerico tabellare** | cifre di larghezza fissa negli importi, così le colonne restano allineate |
|
||||
| **Dimensione testo** | *100%* (13 px, predefinita), *110%*, *120%* |
|
||||
| **Menu laterale** | *Automatico* (compresso sotto i 1100 px, poi ricorda l'ultimo stato), *Espanso*, *Compresso* |
|
||||
| **Numeri tabellari** | cifre di larghezza fissa negli importi, così le colonne restano allineate (attivo) |
|
||||
|
||||
Interruttori:
|
||||
|
||||
@@ -78,8 +86,8 @@ Interruttori:
|
||||
- **Evidenzia riga sotto il cursore nelle griglie**.
|
||||
- **Animazioni ridotte** — riduce transizioni e movimenti.
|
||||
|
||||
Il riquadro **Anteprima** a destra mostra subito l'effetto delle scelte su una toolbar, alcuni campi, una griglia e
|
||||
i badge di stato (*Bozza*, *Confermato*, *Emessa*, *Attenzione*, *Scartata*).
|
||||
Al posto del riquadro **Anteprima** del mockup, l'anteprima è la pagina stessa: ogni scelta si applica subito a
|
||||
tutta l'interfaccia.
|
||||
|
||||
## Dati personali
|
||||
|
||||
@@ -99,34 +107,39 @@ non si cambiano da qui: li assegna un amministratore ([Utenti e permessi](Utenti
|
||||
|
||||
## Sessioni
|
||||
|
||||
Elenco delle sessioni aperte con il tuo utente: dispositivo, indirizzo IP, data di inizio e ultima attività. Puoi
|
||||
**chiudere** (revocare) una sessione che non riconosci. Un accesso da un **nuovo dispositivo** genera una notifica
|
||||
Elenco delle sessioni aperte con il tuo utente: dispositivo (browser e sistema), indirizzo IP, azienda, data di
|
||||
accesso e ultima attività; la sessione da cui stai lavorando è segnata come *Questa sessione*. Puoi **chiudere**
|
||||
(revocare) una sessione che non riconosci, o **chiuderle tutte tranne questa**: il dispositivo dovrà accedere di
|
||||
nuovo alla richiesta successiva. Un accesso da un **nuovo dispositivo** genera una notifica
|
||||
di sicurezza. Le sessioni scadono dopo un periodo di inattività (scadenza scorrevole) e contano nel numero di utenti
|
||||
contemporanei previsto dalla licenza.
|
||||
|
||||
## Pagina iniziale
|
||||
|
||||
- **All'accesso apri**: *Dashboard*, *ultima scheda aperta*, un *radar* (ad esempio Clienti), la *prima nota*,
|
||||
l'*agenda*…
|
||||
- **All'accesso apri**: *la pagina iniziale*, *le schede aperte l'ultima volta* (si riapre quella attiva), oppure
|
||||
*una pagina a scelta* fra quelle del menu che puoi aprire.
|
||||
- **Mostra la dashboard**: sì/no. Vedi [Dashboard](Dashboard).
|
||||
|
||||
## Layout salvati
|
||||
|
||||
Qui trovi i **filtri salvati** (stella nei radar) e le **disposizioni delle colonne** delle griglie che hai
|
||||
memorizzato, con la possibilità di eliminarli (le altre operazioni, come rinomina o scelta del predefinito, saranno
|
||||
definite in sviluppo). Il numero accanto al titolo della scheda indica quanti sono.
|
||||
La scheda raccoglierà i **filtri salvati** (stella nei radar) e le **disposizioni delle colonne** delle griglie che
|
||||
hai memorizzato, con la possibilità di eliminarli. **In questa versione** filtri e colonne si salvano e si eliminano
|
||||
direttamente dal radar e dalla griglia; la scheda nel profilo arriva con le prime maschere che li usano davvero
|
||||
(anagrafiche, M4).
|
||||
|
||||
## Notifiche
|
||||
|
||||
Scegli quali notifiche ricevere in app (documenti, SDI, scadenze, magazzino, sicurezza, attività programmate…) e se
|
||||
ricevere anche un **riepilogo via e-mail** (digest). L'elenco preciso delle categorie e quali di esse siano
|
||||
obbligatorie saranno definiti in sviluppo. Vedi anche
|
||||
La scheda permetterà di scegliere quali notifiche ricevere in app (documenti, SDI, scadenze, magazzino, sicurezza,
|
||||
attività programmate…) e se ricevere anche un **riepilogo via e-mail** (digest). **In questa versione** arrivano
|
||||
tutte le notifiche previste per il tuo ruolo e non c'è il riepilogo via e-mail: categorie e scelte arrivano con
|
||||
l'invio delle e-mail (M5). Vedi anche
|
||||
[Interfaccia e scorciatoie](Interfaccia-e-scorciatoie) (pannello notifiche).
|
||||
|
||||
## Dove sono salvate le preferenze
|
||||
|
||||
Le preferenze sono salvate **nel database dell'azienda** e valgono su ogni dispositivo da cui accedi. Le preferenze
|
||||
esistono su tre livelli:
|
||||
Le preferenze sono salvate **nel database**, non nel browser, e valgono su ogni dispositivo da cui accedi: per gli
|
||||
utenti aziendali nel database dell'azienda (tabella `user_settings`), per gli account di istanza (super utente,
|
||||
amministratori) nel database di sistema (`sys_user_settings`). Le preferenze esistono su tre livelli:
|
||||
|
||||
| Livello | Esempi | Chi le cambia |
|
||||
|---|---|---|
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Roadmap
|
||||
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Specifica:** SPEC §20
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-12 · **Specifica:** SPEC §20
|
||||
|
||||
Khaemhat si costruisce in **15 milestone**. Ogni milestone si chiude con un tag di versione, un'immagine Docker nel
|
||||
registro pacchetti di Gitea e la wiki delle funzioni consegnate portata da *bozza* a *completa*.
|
||||
@@ -10,6 +10,11 @@ Il lavoro di dettaglio è nelle issue di Gitea, raggruppate per
|
||||
[progetti](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/projects) *Khaemhat 1.0 — Sviluppo* e
|
||||
*Khaemhat 1.1+ — Fase 2*.
|
||||
|
||||
Finché il prodotto è in sviluppo le versioni restano **0.x**, anche dopo M13: la **1.0.0** sarà pubblicata solo
|
||||
quando verrà deciso esplicitamente.
|
||||
|
||||
**Completate:** M0 (0.0.1), M1 (0.1.0), M2 (0.2.0), M3 (0.3.0), M4 (0.4.0). **In corso:** M5.
|
||||
|
||||
| # | Milestone | Contenuto principale | Versione |
|
||||
|---|---|---|---|
|
||||
| M0 | Bootstrap | Soluzione e progetti, regole di build e allowlist, Dockerfile e compose con pagina "in costruzione", `/health`, Gitea Actions (`ci.yml`, `release.yml`, `wiki.yml`), script, ADR | 0.0.1 |
|
||||
@@ -25,8 +30,8 @@ Il lavoro di dettaglio è nelle issue di Gitea, raggruppate per
|
||||
| M10 | Cespiti, Intrastat, chiusura, bilancio | Registro cespiti, Intrastat, dichiarazioni d'intento, ratei e risconti, chiusura e apertura, bilancio CEE | 0.10.0 |
|
||||
| M11 | CRM | Lead, pipeline, opportunità, attività e agenda, campagne, ticket, scheda 360° | 0.11.0 |
|
||||
| M12 | Amministrazione, automazioni, API | Gestione database, backup e ripristino (anche S3 e WebDAV), attività programmate, impostazioni, stato sistema e aggiornamenti, API REST, MCP, webhook, regole e procedure | 0.12.0 |
|
||||
| M13 | Consolidamento e rilascio | Sicurezza, prestazioni, accessibilità, wiki completa, PWA, prova su Unraid | **1.0.0** |
|
||||
| M14 | Fase 2 | Servizi (contratti e interventi), canali e-commerce, EN 16931/Peppol, XBRL, regime del margine, ventilazione, IVA per cassa completa, SFTP | 1.1.0+ |
|
||||
| M13 | Consolidamento e rilascio | Sicurezza, prestazioni, accessibilità, wiki completa, PWA, prova su Unraid | 0.13.0 |
|
||||
| M14 | Fase 2 | Servizi (contratti e interventi), canali e-commerce, EN 16931/Peppol, XBRL, regime del margine, ventilazione, IVA per cassa completa, SFTP | 0.14.0+ |
|
||||
|
||||
## Stato attuale
|
||||
|
||||
|
||||
@@ -63,7 +63,7 @@ Il riquadro **Versione** riporta:
|
||||
| **Motore DB** | PostgreSQL 17 · minima 16 |
|
||||
| **Cache** | Redis (opzionale) o memoria |
|
||||
| **Fuso orario** | `Europe/Rome` |
|
||||
| **Pacchetto fiscale** | Italia · dati `IT 2026.2` |
|
||||
| **Pacchetto fiscale** | Italia · dati `IT 2026.3` |
|
||||
| **Istanza** | nome host e numero di aziende |
|
||||
|
||||
La stessa versione compare nella barra superiore (solo `major.minor`), nella barra di stato (completa) e
|
||||
|
||||
@@ -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:** completa · **Ultima revisione:** 2026-11-12 · **Versione software:** 0.4.0 (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,20 +10,50 @@ 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*, *Preferenze e codici automatici*, *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* è a `/tabelle/preferenze`.
|
||||
|
||||
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**.
|
||||

|
||||
*Khaemhat 0.4.0 — l'indice delle tabelle azienda per gruppi, con il sottomenu delle voci più usate.*
|
||||
|
||||
## 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*).
|
||||
fiscale** in uso (es. *IT 2026.3*).
|
||||
|
||||
| Scheda / gruppo | Campi |
|
||||
|---|---|
|
||||
@@ -49,6 +79,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 +92,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** | Sigla, regione, codice catastale (il codice del comune), codice ISTAT e CAP: servono per la compilazione da CAP e per il calcolo del codice fiscale. Province, comuni e CAP arrivano con i dati di base (elenco ISTAT, CAP da GeoNames); i pochi CAP mancanti si completano a mano o con l'Importa CSV, 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) |
|
||||
@@ -77,8 +111,8 @@ periodo (vedi [IVA](IVA)) e la chiusura dell'esercizio lo rende di sola lettura
|
||||
| **Depositi** | magazzini, anche mobili (es. furgone) |
|
||||
| **Categorie articolo** | su tre livelli |
|
||||
| **Categorie controparte** | classificazione di clienti e fornitori |
|
||||
| **Listini** | intestazioni dei listini (i prezzi sono in [Articoli e listini](Articoli-e-listini)) |
|
||||
| **Politiche di sconto** | regole di sconto riutilizzabili (struttura definita in sviluppo) |
|
||||
| **Listini** | intestazioni dei listini: valuta, IVA inclusa, validità, **Listino base** (uno solo, in partenza `BASE`), **Derivato da** con ricarico % e arrotondamento (i prezzi sono in [Articoli e listini](Articoli-e-listini)) |
|
||||
| **Politiche di sconto** | sconti in cascata con un codice, come formula (`10+5`), da richiamare nelle condizioni |
|
||||
| **Tipi documento** | catalogo dei documenti con numeratore, causale di magazzino, causale contabile, registro IVA, codice TD, modello di stampa |
|
||||
| **Centri di costo** | per l'analisi dei costi e dei ricavi |
|
||||
| **Commesse** | progetti o cantieri a cui imputare costi e ricavi |
|
||||
@@ -88,6 +122,9 @@ periodo (vedi [IVA](IVA)) e la chiusura dell'esercizio lo rende di sola lettura
|
||||

|
||||
*Mockup 076 — elenco dei codici IVA con aliquota, tipo, natura SDI, esigibilità, indetraibilità e conti, con il dettaglio del codice RC17 (anteprima ridotta).*
|
||||
|
||||

|
||||
*Khaemhat 0.4.0 — l'elenco dei codici IVA di base con il dettaglio del codice 22SP (scissione dei pagamenti).*
|
||||
|
||||
Ogni codice IVA ha: **codice**, **descrizione**, **aliquota**, **tipo** (IVA, esente, non imponibile, fuori campo,
|
||||
escluso, reverse charge), **natura SDI** per le operazioni senza imposta, **riferimento normativo** (stampato in
|
||||
fattura e riportato nell'XML), **esigibilità** (`I` immediata, `D` differita, `S` scissione dei pagamenti),
|
||||
@@ -112,19 +149,26 @@ 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
|
||||
|
||||

|
||||
*Mockup 074 — Preferenze azienda: maschere dei codici automatici per anagrafiche, articoli e cespiti, CRM e servizi, documenti e contabilità; elenco delle compilazioni automatiche (anteprima ridotta).*
|
||||
|
||||
La maschera **Preferenze azienda** ha le schede *Codici automatici*, *Compilazione automatica*, *Arrotondamenti e
|
||||
controlli*, *Default documenti*, *Modelli e-mail*, *Testi di stampa*.
|
||||

|
||||
*Khaemhat 0.4.0 — le maschere dei codici automatici con l'anteprima del prossimo codice; le maschere dei moduli non attivi restano pronte.*
|
||||
|
||||
La maschera **Preferenze azienda** (`/tabelle/preferenze`) ha le schede *Codici automatici* e *Compilazione
|
||||
automatica*; le schede *Arrotondamenti e controlli*, *Default documenti*, *Modelli e-mail* e *Testi di stampa*
|
||||
arrivano con i documenti e le e-mail. **Salva** registra le due schede insieme.
|
||||
|
||||
### Codici automatici
|
||||
|
||||
@@ -142,40 +186,58 @@ Per ogni archivio si imposta una **maschera**; sotto il campo compare l'anteprim
|
||||
| Contratti di servizio | `SVC-{seq:0000}` | `SVC-0001` |
|
||||
| Interventi | `MAN-{anno}-{seq:0000}` | `MAN-2026-0001` |
|
||||
|
||||
Segnaposto: `{seq:0000}` progressivo con il numero di cifre indicato, `{anno}` anno corrente, `{categoria}` codice
|
||||
della categoria. Il progressivo può essere **globale** o **per categoria / per anno**. Opzioni: *Consenti codice
|
||||
manuale* (l'utente può scrivere un codice diverso), *Blocca duplicati per EAN* (articoli). I progressivi sono
|
||||
assegnati in modo atomico: due salvataggi contemporanei non ottengono mai lo stesso codice.
|
||||
Segnaposto: `{seq:0000}` progressivo con tante cifre quanti sono gli zeri (`{seq}` senza zeri davanti), `{anno}`
|
||||
anno della registrazione, `{categoria}` codice della categoria (solo articoli). Il resto della maschera si scrive
|
||||
così com'è: lettere, cifre e `- _ / .`. Il progressivo è **globale**, riparte **ogni anno** se la maschera
|
||||
contiene `{anno}` e va **per categoria** se contiene `{categoria}`. Una maschera sbagliata (senza progressivo, con
|
||||
segnaposto sconosciuti o con codici più lunghi della tabella) viene segnalata sotto il campo e non si salva.
|
||||
|
||||
Opzioni: *Consenti codice manuale* per ogni riquadro (l'utente può scrivere un codice diverso; spento, il campo
|
||||
codice resta vuoto e il codice arriva al salvataggio), *Blocca duplicati per EAN* (articoli). Le maschere dei moduli
|
||||
non attivi (CRM, Servizi, Cespiti) si possono preparare: valgono quando il modulo viene attivato.
|
||||
|
||||
I progressivi sono assegnati **al salvataggio** dentro la stessa transazione: due salvataggi contemporanei non
|
||||
ottengono mai lo stesso codice, e un salvataggio non riuscito non consuma il numero. Se il codice successivo esiste
|
||||
già (perché scritto a mano), Khaemhat passa al numero dopo. **Cambiare la maschera non riscrive i codici già
|
||||
assegnati** e non azzera il progressivo: da `C{seq:000000}` a `CL{seq:0000}` dopo `C000123` il codice successivo è
|
||||
`CL0124`.
|
||||
|
||||
Il riquadro *Documenti e contabilità* rimanda ai [numeratori](#numeratori): fatture, protocollo e registrazioni non
|
||||
usano maschere ma numeratori per anno e sezionale.
|
||||
|
||||
### Compilazione automatica
|
||||
|
||||
| Opzione | Effetto |
|
||||
|---|---|
|
||||
| Comune, provincia e regione dal CAP | compila l'indirizzo partendo dal CAP |
|
||||
| Codice fiscale dai dati anagrafici | calcola il codice fiscale delle persone fisiche |
|
||||
| Verifica P.IVA UE (VIES) al salvataggio | interroga il servizio VIES e salva l'esito |
|
||||
| Banca e BIC dall'IBAN | ricava la banca dalla tabella ABI |
|
||||
| Cambi BCE giornalieri | scarica i cambi ogni giorno |
|
||||
| Descrizione articolo nelle righe | copia la descrizione dell'articolo nella riga del documento |
|
||||
| Ultimo prezzo praticato al cliente | lo mostra come riferimento |
|
||||
| Proponi ultimo documento simile | parte dal documento precedente dello stesso cliente |
|
||||
| Date consegna = data + lead time | calcola la consegna prevista |
|
||||
| Conti contabili da articolo, categoria, causale | propone conti di ricavo e costo |
|
||||
Ogni opzione si accende o spegne con un interruttore; spenta, i campi restano da scrivere a mano.
|
||||
|
||||
Oltre a queste, i documenti ricevono sempre destinazione, listino, pagamento e agente dal cliente e causale e
|
||||
deposito dal tipo documento.
|
||||
| Opzione | Effetto | Predefinita |
|
||||
|---|---|---|
|
||||
| Comune, provincia e regione dal CAP | scrivendo il CAP propone il comune (o i comuni) con provincia e regione; scrivendo il comune propone CAP e provincia | accesa |
|
||||
| Codice fiscale dai dati anagrafici | calcola il codice fiscale delle persone fisiche da cognome, nome, data, sesso e comune di nascita | accesa |
|
||||
| Verifica P.IVA UE (VIES) al salvataggio | interroga il servizio VIES e salva l'esito (*valida*, *non valida*, *servizio non disponibile*) | accesa |
|
||||
| Banca e BIC dall'IBAN | legge ABI e CAB dall'IBAN; banca e BIC vengono dall'elenco ABI o, finché l'elenco non è caricato, da un conto dell'azienda presso la stessa banca | accesa |
|
||||
| Cambi BCE giornalieri | l'attività di sistema scarica i cambi nei giorni lavorativi; spenta, l'azienda usa solo cambi manuali | accesa |
|
||||
| Descrizione articolo nelle righe | copia la descrizione dell'articolo nella riga del documento | accesa |
|
||||
| Ultimo prezzo praticato al cliente | lo mostra come riferimento | accesa |
|
||||
| Proponi ultimo documento simile | parte dal documento precedente dello stesso tipo e cliente | spenta |
|
||||
| Data di consegna = data + lead time | aggiunge il tempo di approvvigionamento e sposta la data al primo giorno lavorativo | accesa |
|
||||
| Conti contabili da articolo, categoria e causale | propone conti di ricavo e costo | accesa |
|
||||
|
||||
Le opzioni sulle righe e sui conti agiscono con i documenti e la contabilità (da M5). Oltre a queste, i documenti
|
||||
ricevono sempre destinazione, listino, pagamento e agente dal cliente e causale e deposito dal tipo documento.
|
||||
|
||||
### Altre preferenze aziendali
|
||||
|
||||
| Scheda | Contenuto |
|
||||
|---|---|
|
||||
| **Arrotondamenti e controlli** | arrotondamenti di prezzi e totali, controlli bloccanti o di avviso (fido, scaduto, date) |
|
||||
| **Default documenti** | sezionali, depositi, causali e condizioni proposti per tipo documento |
|
||||
| **Modelli e-mail** | testi per l'invio di documenti, solleciti, notifiche |
|
||||
| **Testi di stampa** | diciture e note in calce ai documenti |
|
||||
In 0.4.0 le preferenze azienda hanno le schede *Codici automatici* e *Compilazione automatica*. Arriveranno con i
|
||||
moduli che le usano:
|
||||
|
||||
La periodicità IVA e le numerazioni fanno parte delle preferenze aziendali e si impostano nel profilo e nei
|
||||
numeratori. Il dettaglio di ogni opzione sarà completato in sviluppo.
|
||||
| Scheda | Contenuto | Con |
|
||||
|---|---|---|
|
||||
| **Arrotondamenti e controlli** | arrotondamenti di prezzi e totali, controlli bloccanti o di avviso (fido, scaduto, date) | documenti (M5) |
|
||||
| **Default documenti** | sezionali, depositi, causali e condizioni proposti per tipo documento | documenti (M5) |
|
||||
| **Modelli e-mail** | testi per l'invio di documenti, solleciti, notifiche | e-mail (M5) |
|
||||
| **Testi di stampa** | diciture e note in calce ai documenti | stampe (M5) |
|
||||
|
||||
La periodicità IVA e le numerazioni si impostano nel profilo azienda e nei numeratori.
|
||||
|
||||
## Permessi e licenza
|
||||
|
||||
@@ -188,8 +250,9 @@ con i rispettivi moduli attivi. La conferma della liquidazione e la chiusura del
|
||||
modificare i codici predefiniti usati in documenti già emessi.
|
||||
- **Non riesco a inserire un documento con data di agosto.** Il periodo è bloccato o liquidato: chiedi a chi gestisce
|
||||
la contabilità.
|
||||
- **Posso cambiare la maschera dei codici clienti a metà anno?** I codici già assegnati non vengono riscritti: la
|
||||
nuova maschera vale per i codici successivi (il comportamento in caso di conflitti sarà definito in sviluppo).
|
||||
- **Posso cambiare la maschera dei codici clienti a metà anno?** Sì: i codici già assegnati non vengono riscritti,
|
||||
la nuova maschera vale per i codici successivi e continua lo stesso progressivo; un codice che esiste già viene
|
||||
saltato.
|
||||
|
||||
## Pagine correlate
|
||||
|
||||
|
||||
|
After Width: | Height: | Size: 122 KiB |
|
After Width: | Height: | Size: 119 KiB |
|
After Width: | Height: | Size: 84 KiB |
|
After Width: | Height: | Size: 119 KiB |
|
After Width: | Height: | Size: 115 KiB |
|
After Width: | Height: | Size: 150 KiB |
|
After Width: | Height: | Size: 134 KiB |
|
After Width: | Height: | Size: 159 KiB |
|
After Width: | Height: | Size: 93 KiB |
|
After Width: | Height: | Size: 89 KiB |
|
After Width: | Height: | Size: 127 KiB |
|
After Width: | Height: | Size: 115 KiB |
|
After Width: | Height: | Size: 215 KiB |
|
After Width: | Height: | Size: 89 KiB |
|
After Width: | Height: | Size: 74 KiB |
|
After Width: | Height: | Size: 54 KiB |
|
After Width: | Height: | Size: 98 KiB |
|
After Width: | Height: | Size: 101 KiB |
|
After Width: | Height: | Size: 140 KiB |
|
After Width: | Height: | Size: 99 KiB |
|
After Width: | Height: | Size: 93 KiB |
|
After Width: | Height: | Size: 119 KiB |
|
After Width: | Height: | Size: 117 KiB |
|
After Width: | Height: | Size: 111 KiB |
@@ -1,9 +1,17 @@
|
||||
#!/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), and with --demo the demo data to the
|
||||
# tables still empty (--scale N repeats the demo catalogues N times). Rows already there are never changed.
|
||||
# scripts/seed.sh --base [--company CODE]
|
||||
# scripts/seed.sh --demo [--scale N] [--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).
|
||||
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 "$@"
|
||||
@@ -0,0 +1,103 @@
|
||||
using System.Text.Json;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Data;
|
||||
|
||||
namespace Khaemhat.Application.Audit;
|
||||
|
||||
/// <summary>A changed field in the history of a record.</summary>
|
||||
/// <param name="Field">The field name.</param>
|
||||
/// <param name="Before">The old value as text; <see langword="null"/> when empty.</param>
|
||||
/// <param name="After">The new value as text; <see langword="null"/> when empty.</param>
|
||||
public sealed record AuditChange(string Field, string? Before, string? After);
|
||||
|
||||
/// <summary>A row of the history of a record (the <i>Storico</i> tab, <c>KhAuditList</c>).</summary>
|
||||
/// <param name="Id">The row.</param>
|
||||
/// <param name="At">When (UTC).</param>
|
||||
/// <param name="Action">What happened.</param>
|
||||
/// <param name="UserName">Who did it.</param>
|
||||
/// <param name="Changes">The changed fields.</param>
|
||||
public sealed record AuditItem(long Id, DateTime At, AuditAction Action, string? UserName, IReadOnlyList<AuditChange> Changes);
|
||||
|
||||
/// <summary>Reads the history written by <see cref="AuditTrail"/> for the interface (SPEC §7.4).</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="permissions">The permissions.</param>
|
||||
public sealed class AuditTrailService(IUnitOfWorkFactory factory, PermissionService permissions)
|
||||
{
|
||||
/// <summary>The most rows shown.</summary>
|
||||
public const int MaxItems = 200;
|
||||
|
||||
/// <summary>The history of a record, newest first.</summary>
|
||||
/// <param name="actor">Who asks.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="entity">The entity, as written by the audit trail (the type name, such as <c>Attachment</c>).</param>
|
||||
/// <param name="entityId">The record.</param>
|
||||
/// <param name="readPermission">The permission that lets the actor read the record.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>At most <see cref="MaxItems"/> rows.</returns>
|
||||
public async Task<IReadOnlyList<AuditItem>> HistoryAsync(
|
||||
Actor actor, string companyCode, string entity, string entityId, string readPermission, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = CompanyCodes.Normalize(companyCode);
|
||||
if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, company, StringComparison.Ordinal))
|
||||
{
|
||||
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A company user works only in its own company.");
|
||||
}
|
||||
|
||||
await permissions.DemandAsync(actor, readPermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var rows = await AuditTrail.HistoryAsync(unitOfWork, entity, entityId, cancellationToken).ConfigureAwait(false);
|
||||
return [.. rows.Take(MaxItems).Select(Item)];
|
||||
}
|
||||
|
||||
/// <summary>A row of the history, with the changes read from their JSON.</summary>
|
||||
/// <param name="entry">The row.</param>
|
||||
/// <returns>The item.</returns>
|
||||
public static AuditItem Item(AuditEntry entry)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entry);
|
||||
var action = Enum.TryParse<AuditAction>(entry.Action, out var parsed) ? parsed : AuditAction.Update;
|
||||
return new AuditItem(entry.Id, entry.At, action, entry.UserName, Changes(entry.Diff));
|
||||
}
|
||||
|
||||
private static List<AuditChange> Changes(string? diff)
|
||||
{
|
||||
var changes = new List<AuditChange>();
|
||||
if (string.IsNullOrWhiteSpace(diff))
|
||||
{
|
||||
return changes;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(diff);
|
||||
if (document.RootElement.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
return changes;
|
||||
}
|
||||
|
||||
foreach (var field in document.RootElement.EnumerateObject())
|
||||
{
|
||||
var values = field.Value.ValueKind == JsonValueKind.Array ? field.Value.EnumerateArray().ToList() : [];
|
||||
changes.Add(new AuditChange(field.Name, Text(values.ElementAtOrDefault(0)), Text(values.ElementAtOrDefault(1))));
|
||||
}
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// A row written by hand or damaged: show the action without the fields.
|
||||
}
|
||||
|
||||
return changes;
|
||||
}
|
||||
|
||||
private static string? Text(JsonElement value) => value.ValueKind switch
|
||||
{
|
||||
JsonValueKind.Undefined or JsonValueKind.Null => null,
|
||||
JsonValueKind.String => value.GetString() is { Length: > 0 } text ? text : null,
|
||||
JsonValueKind.True => "true",
|
||||
JsonValueKind.False => "false",
|
||||
JsonValueKind.Number => value.GetRawText(),
|
||||
_ => value.GetRawText(),
|
||||
};
|
||||
}
|
||||
@@ -65,6 +65,7 @@ public sealed class EnvironmentConfigurationReader
|
||||
SeedDemo = Get("KHAEMHAT_SEED_DEMO"),
|
||||
UpdateFeed = Get("KHAEMHAT_UPDATE_FEED"),
|
||||
UpdateToken = Get("KHAEMHAT_UPDATE_TOKEN"),
|
||||
HelpUrl = Get("KHAEMHAT_HELP_URL"),
|
||||
TimeZone = Get("TZ"),
|
||||
ReadErrors = errors,
|
||||
};
|
||||
|
||||
@@ -150,6 +150,12 @@ public sealed class KhaemhatOptions
|
||||
/// <summary><c>KHAEMHAT_UPDATE_TOKEN</c>: a read-only token for the feed.</summary>
|
||||
public string? UpdateToken { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// <c>KHAEMHAT_HELP_URL</c>: the online wiki opened by "Apri nel wiki" (default the project wiki). The help itself
|
||||
/// is the copy of the wiki shipped in the image, so it works offline.
|
||||
/// </summary>
|
||||
public string? HelpUrl { get; init; }
|
||||
|
||||
/// <summary><c>TZ</c>: the time zone of the container.</summary>
|
||||
public string? TimeZone { get; init; }
|
||||
|
||||
@@ -265,6 +271,11 @@ public sealed class KhaemhatOptions
|
||||
errors.Add("KHAEMHAT_PUBLIC_URL must be an absolute http or https address, for example https://gestionale.example.com.");
|
||||
}
|
||||
|
||||
if (HelpUrl is not null && !IsHttpUrl(HelpUrl))
|
||||
{
|
||||
errors.Add("KHAEMHAT_HELP_URL must be an absolute http or https address, for example https://gitea.example.com/owner/khaemhat/wiki/.");
|
||||
}
|
||||
|
||||
if (SmtpPort is not null && !(int.TryParse(SmtpPort, NumberStyles.None, CultureInfo.InvariantCulture, out var port) && port is > 0 and < 65536))
|
||||
{
|
||||
errors.Add("KHAEMHAT_SMTP_PORT must be a port number between 1 and 65535.");
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
using Khaemhat.Application.Security;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Khaemhat.Application.Dashboard;
|
||||
|
||||
/// <summary>The colour of a line in a dashboard list.</summary>
|
||||
public enum FeedTone
|
||||
{
|
||||
/// <summary>Nothing special.</summary>
|
||||
Neutral = 0,
|
||||
|
||||
/// <summary>Information.</summary>
|
||||
Info = 1,
|
||||
|
||||
/// <summary>Done, fine.</summary>
|
||||
Ok = 2,
|
||||
|
||||
/// <summary>Needs attention.</summary>
|
||||
Warning = 3,
|
||||
|
||||
/// <summary>Something went wrong.</summary>
|
||||
Error = 4,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A line of <em>Da fare oggi</em>, <em>Fatto oggi</em> or <em>Scadenze</em>. The texts are already in the user's
|
||||
/// language; <see cref="AreaKey"/> is the text key of the area label (Sistema, Vendite, Fiscale…).
|
||||
/// </summary>
|
||||
/// <param name="Id">A stable id, unique within the list.</param>
|
||||
/// <param name="Text">What it is.</param>
|
||||
/// <param name="AreaKey">The text key of the area.</param>
|
||||
/// <param name="Tone">The colour.</param>
|
||||
public sealed record FeedItem(string Id, string Text, string AreaKey, FeedTone Tone = FeedTone.Neutral)
|
||||
{
|
||||
/// <summary>A second line, if any.</summary>
|
||||
public string? Detail { get; init; }
|
||||
|
||||
/// <summary>When: the time for what was done, the date for a deadline.</summary>
|
||||
public DateTimeOffset? When { get; init; }
|
||||
|
||||
/// <summary>Where it opens, a local address.</summary>
|
||||
public string? Href { get; init; }
|
||||
|
||||
/// <summary>Higher first, for the things to do.</summary>
|
||||
public int Priority { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Who asks and when.</summary>
|
||||
/// <param name="Actor">The user.</param>
|
||||
/// <param name="Now">The local time now.</param>
|
||||
public sealed record FeedContext(Actor Actor, DateTimeOffset Now)
|
||||
{
|
||||
/// <summary>Today, local.</summary>
|
||||
public DateOnly Today => DateOnly.FromDateTime(Now.DateTime);
|
||||
|
||||
/// <summary>The start of today, local.</summary>
|
||||
public DateTimeOffset StartOfToday => new(Now.Date, Now.Offset);
|
||||
}
|
||||
|
||||
/// <summary>A source of things to do today (rejected SDI invoices, VAT settlements, procedures waiting… as the modules come).</summary>
|
||||
public interface ITodoSource
|
||||
{
|
||||
/// <summary>The things to do.</summary>
|
||||
/// <param name="context">Who and when.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The lines.</returns>
|
||||
Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>A source of things done today (documents issued, collections, backups, scheduled tasks…).</summary>
|
||||
public interface IDoneSource
|
||||
{
|
||||
/// <summary>The things done.</summary>
|
||||
/// <param name="context">Who and when.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The lines.</returns>
|
||||
Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>A source of deadlines (fiscal, sales, treasury, contracts…).</summary>
|
||||
public interface IDeadlineSource
|
||||
{
|
||||
/// <summary>The deadlines from today up to the horizon.</summary>
|
||||
/// <param name="context">Who and when.</param>
|
||||
/// <param name="until">The last day included.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The lines, with <see cref="FeedItem.When"/> set.</returns>
|
||||
Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, DateOnly until, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs every source of one kind and merges what they say. A source that fails is logged and left out: one broken
|
||||
/// module must not empty the whole dashboard.
|
||||
/// </summary>
|
||||
public abstract class FeedAggregator
|
||||
{
|
||||
/// <summary>The most lines a widget shows.</summary>
|
||||
public const int MaxItems = 50;
|
||||
|
||||
/// <summary>Runs the sources one after the other (they share the database connections of the scope).</summary>
|
||||
/// <param name="sources">The calls.</param>
|
||||
/// <param name="logger">Where failures go.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>All the lines.</returns>
|
||||
protected static async Task<List<FeedItem>> CollectAsync(
|
||||
IEnumerable<(string Name, Func<Task<IReadOnlyList<FeedItem>>> Call)> sources, ILogger logger, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sources);
|
||||
var items = new List<FeedItem>();
|
||||
foreach (var (name, call) in sources)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
try
|
||||
{
|
||||
items.AddRange(await call().ConfigureAwait(false));
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
logger.LogWarning(ex, "Dashboard source {Source} failed and was left out.", name);
|
||||
}
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What to do today, the most urgent first.</summary>
|
||||
/// <param name="sources">The sources.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
/// <param name="logger">The log.</param>
|
||||
public sealed class TodoAggregator(IEnumerable<ITodoSource> sources, TimeProvider clock, ILogger<TodoAggregator> logger) : FeedAggregator
|
||||
{
|
||||
/// <summary>The things to do.</summary>
|
||||
/// <param name="actor">The user.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>Higher priority first, then the oldest.</returns>
|
||||
public async Task<IReadOnlyList<FeedItem>> GetAsync(Actor actor, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var context = new FeedContext(actor, clock.GetLocalNow());
|
||||
var items = await CollectAsync(sources.Select(s => (s.GetType().Name, (Func<Task<IReadOnlyList<FeedItem>>>)(() => s.GetAsync(context, cancellationToken)))), logger, cancellationToken).ConfigureAwait(false);
|
||||
return [.. items.OrderByDescending(i => i.Priority).ThenBy(i => i.When ?? DateTimeOffset.MaxValue).Take(MaxItems)];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What was done today, the latest first.</summary>
|
||||
/// <param name="sources">The sources.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
/// <param name="logger">The log.</param>
|
||||
public sealed class DoneAggregator(IEnumerable<IDoneSource> sources, TimeProvider clock, ILogger<DoneAggregator> logger) : FeedAggregator
|
||||
{
|
||||
/// <summary>The things done today.</summary>
|
||||
/// <param name="actor">The user.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The latest first.</returns>
|
||||
public async Task<IReadOnlyList<FeedItem>> GetAsync(Actor actor, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var context = new FeedContext(actor, clock.GetLocalNow());
|
||||
var items = await CollectAsync(sources.Select(s => (s.GetType().Name, (Func<Task<IReadOnlyList<FeedItem>>>)(() => s.GetAsync(context, cancellationToken)))), logger, cancellationToken).ConfigureAwait(false);
|
||||
return [.. items.OrderByDescending(i => i.When ?? DateTimeOffset.MinValue).Take(MaxItems)];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The deadlines of the next days, the nearest first.</summary>
|
||||
/// <param name="sources">The sources.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
/// <param name="logger">The log.</param>
|
||||
public sealed class DeadlineAggregator(IEnumerable<IDeadlineSource> sources, TimeProvider clock, ILogger<DeadlineAggregator> logger) : FeedAggregator
|
||||
{
|
||||
/// <summary>How far the widget looks ahead.</summary>
|
||||
public const int HorizonDays = 30;
|
||||
|
||||
/// <summary>The deadlines from today to <see cref="HorizonDays"/> days ahead.</summary>
|
||||
/// <param name="actor">The user.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The nearest first.</returns>
|
||||
public async Task<IReadOnlyList<FeedItem>> GetAsync(Actor actor, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var context = new FeedContext(actor, clock.GetLocalNow());
|
||||
var until = context.Today.AddDays(HorizonDays);
|
||||
var items = await CollectAsync(sources.Select(s => (s.GetType().Name, (Func<Task<IReadOnlyList<FeedItem>>>)(() => s.GetAsync(context, until, cancellationToken)))), logger, cancellationToken).ConfigureAwait(false);
|
||||
return [.. items
|
||||
.Where(i => i.When is { } when && DateOnly.FromDateTime(when.DateTime) >= context.Today && DateOnly.FromDateTime(when.DateTime) <= until)
|
||||
.OrderBy(i => i.When)
|
||||
.Take(MaxItems)];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace Khaemhat.Application.Dashboard;
|
||||
|
||||
/// <summary>A widget on the dashboard: which one and how wide.</summary>
|
||||
/// <param name="Id">The widget id (<see cref="WidgetIds"/>).</param>
|
||||
/// <param name="Width">The width in columns of twelve: 3, 4, 6, 8 or 12.</param>
|
||||
public sealed record WidgetPlacement(string Id, int Width);
|
||||
|
||||
/// <summary>
|
||||
/// The widgets shown, in order, with their width (SPEC §10.3). A widget that is not in the list is switched off.
|
||||
/// Kept as JSON in <c>user_settings</c> (<c>dashboard.layout</c>) and, as the default of a role, in
|
||||
/// <c>company_settings</c>: <c>{"v":1,"widgets":[{"id":"todo","w":4}]}</c>.
|
||||
/// </summary>
|
||||
/// <param name="Widgets">The widgets in order.</param>
|
||||
public sealed record DashboardLayout(IReadOnlyList<WidgetPlacement> Widgets)
|
||||
{
|
||||
/// <summary>The most widgets a layout keeps.</summary>
|
||||
public const int MaxWidgets = 30;
|
||||
|
||||
private const int Version = 1;
|
||||
|
||||
/// <summary>Whether a widget is shown.</summary>
|
||||
/// <param name="id">The widget id.</param>
|
||||
/// <returns><see langword="true"/> when it is in the layout.</returns>
|
||||
public bool Contains(string id) => Widgets.Any(w => w.Id == id);
|
||||
|
||||
/// <summary>The width of a widget, or its default when not shown.</summary>
|
||||
/// <param name="id">The widget id.</param>
|
||||
/// <returns>The width.</returns>
|
||||
public int WidthOf(string id) =>
|
||||
Widgets.FirstOrDefault(w => w.Id == id)?.Width ?? WidgetCatalog.Find(id)?.DefaultWidth ?? 4;
|
||||
|
||||
/// <summary>Reads a layout saved as JSON.</summary>
|
||||
/// <param name="json">The JSON, or <see langword="null"/>.</param>
|
||||
/// <returns>The layout without unknown widgets, duplicates or invalid widths; <see langword="null"/> when there
|
||||
/// is none or it cannot be read.</returns>
|
||||
public static DashboardLayout? Parse(string? json)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(json))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (JsonNode.Parse(json) is not JsonObject root || root["widgets"] is not JsonArray array)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var widgets = new List<WidgetPlacement>();
|
||||
foreach (var node in array)
|
||||
{
|
||||
if (node is JsonObject item && item["id"]?.GetValueKind() == JsonValueKind.String)
|
||||
{
|
||||
var width = item["w"]?.GetValueKind() == JsonValueKind.Number ? item["w"]!.GetValue<int>() : 0;
|
||||
widgets.Add(new WidgetPlacement(item["id"]!.GetValue<string>(), width));
|
||||
}
|
||||
}
|
||||
|
||||
return new DashboardLayout(widgets).Normalize();
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or FormatException or InvalidOperationException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The layout as JSON.</summary>
|
||||
/// <returns>The JSON.</returns>
|
||||
public string ToJson()
|
||||
{
|
||||
var array = new JsonArray();
|
||||
foreach (var widget in Normalize().Widgets)
|
||||
{
|
||||
array.Add(new JsonObject { ["id"] = widget.Id, ["w"] = widget.Width });
|
||||
}
|
||||
|
||||
return new JsonObject { ["v"] = Version, ["widgets"] = array }.ToJsonString();
|
||||
}
|
||||
|
||||
/// <summary>Drops unknown widgets and repeated ones and snaps the widths to the allowed ones.</summary>
|
||||
/// <returns>The clean layout.</returns>
|
||||
public DashboardLayout Normalize()
|
||||
{
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||
var widgets = new List<WidgetPlacement>();
|
||||
foreach (var widget in Widgets)
|
||||
{
|
||||
if (WidgetCatalog.Find(widget.Id) is { } definition && seen.Add(widget.Id) && widgets.Count < MaxWidgets)
|
||||
{
|
||||
widgets.Add(new WidgetPlacement(definition.Id, widget.Width <= 0 ? definition.DefaultWidth : WidgetDefinition.Snap(widget.Width)));
|
||||
}
|
||||
}
|
||||
|
||||
return new DashboardLayout(widgets);
|
||||
}
|
||||
|
||||
/// <summary>Only the widgets that pass a test, such as those the user may see.</summary>
|
||||
/// <param name="keep">The test.</param>
|
||||
/// <returns>The layout.</returns>
|
||||
public DashboardLayout Where(Func<string, bool> keep)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(keep);
|
||||
return new DashboardLayout([.. Widgets.Where(w => keep(w.Id))]);
|
||||
}
|
||||
|
||||
/// <summary>Shows a widget at the end, or hides it.</summary>
|
||||
/// <param name="id">The widget id.</param>
|
||||
/// <param name="visible">Whether to show it.</param>
|
||||
/// <returns>The layout.</returns>
|
||||
public DashboardLayout Toggle(string id, bool visible)
|
||||
{
|
||||
if (visible == Contains(id) || WidgetCatalog.Find(id) is not { } definition)
|
||||
{
|
||||
return this;
|
||||
}
|
||||
|
||||
return visible
|
||||
? new DashboardLayout([.. Widgets, new WidgetPlacement(id, definition.DefaultWidth)])
|
||||
: new DashboardLayout([.. Widgets.Where(w => w.Id != id)]);
|
||||
}
|
||||
|
||||
/// <summary>Changes the width of a widget.</summary>
|
||||
/// <param name="id">The widget id.</param>
|
||||
/// <param name="width">The new width (snapped to the allowed ones).</param>
|
||||
/// <returns>The layout.</returns>
|
||||
public DashboardLayout Resize(string id, int width) =>
|
||||
new([.. Widgets.Select(w => w.Id == id ? w with { Width = WidgetDefinition.Snap(width) } : w)]);
|
||||
|
||||
/// <summary>Moves a widget by some places.</summary>
|
||||
/// <param name="id">The widget id.</param>
|
||||
/// <param name="offset">-1 before the previous one, +1 after the next one.</param>
|
||||
/// <returns>The layout.</returns>
|
||||
public DashboardLayout Move(string id, int offset)
|
||||
{
|
||||
var index = Widgets.ToList().FindIndex(w => w.Id == id);
|
||||
return index < 0 ? this : MoveTo(id, Math.Clamp(index + offset, 0, Widgets.Count - 1));
|
||||
}
|
||||
|
||||
/// <summary>Moves a widget to a position, as dropping it on another widget does.</summary>
|
||||
/// <param name="id">The widget id.</param>
|
||||
/// <param name="index">The new position.</param>
|
||||
/// <returns>The layout.</returns>
|
||||
public DashboardLayout MoveTo(string id, int index)
|
||||
{
|
||||
var list = Widgets.ToList();
|
||||
var from = list.FindIndex(w => w.Id == id);
|
||||
if (from < 0)
|
||||
{
|
||||
return this;
|
||||
}
|
||||
|
||||
var widget = list[from];
|
||||
list.RemoveAt(from);
|
||||
list.Insert(Math.Clamp(index, 0, list.Count), widget);
|
||||
return new DashboardLayout(list);
|
||||
}
|
||||
|
||||
/// <summary>Whether two layouts show the same widgets in the same order and widths.</summary>
|
||||
/// <param name="other">The other layout.</param>
|
||||
/// <returns><see langword="true"/> when they look the same.</returns>
|
||||
public bool SameAs(DashboardLayout? other) => other is not null && Widgets.SequenceEqual(other.Widgets);
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Khaemhat.Application.Instance;
|
||||
using Khaemhat.Application.Licensing;
|
||||
using Khaemhat.Application.Preferences;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Security;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Dashboard;
|
||||
|
||||
/// <summary>Where the layout shown comes from.</summary>
|
||||
public enum DashboardLayoutSource
|
||||
{
|
||||
/// <summary>The built-in layout of <see cref="WidgetCatalog.BuiltIn"/>.</summary>
|
||||
BuiltIn = 0,
|
||||
|
||||
/// <summary>The default of one of the user's roles.</summary>
|
||||
Role = 1,
|
||||
|
||||
/// <summary>The user's own layout.</summary>
|
||||
User = 2,
|
||||
}
|
||||
|
||||
/// <summary>The dashboard of a user: the layout and where it comes from.</summary>
|
||||
/// <param name="Layout">The widgets the user may see, in order.</param>
|
||||
/// <param name="Source">Where it comes from.</param>
|
||||
/// <param name="RoleCode">The role whose default is used, when <see cref="Source"/> is <see cref="DashboardLayoutSource.Role"/>.</param>
|
||||
public sealed record DashboardView(DashboardLayout Layout, DashboardLayoutSource Source, string? RoleCode = null);
|
||||
|
||||
/// <summary>A personal reminder of the dashboard.</summary>
|
||||
/// <param name="Text">What to remember.</param>
|
||||
/// <param name="Done">Whether it is ticked.</param>
|
||||
public sealed record PersonalNote(string Text, bool Done);
|
||||
|
||||
/// <summary>
|
||||
/// The dashboard of SPEC §10.3: which widgets a user may see, the layout to show (the user's own, else the default
|
||||
/// of one of their roles, else the built-in one), the personal reminders and the shortcuts. Everything belongs to the
|
||||
/// user in <c>user_settings</c>; the role defaults belong to the company in <c>company_settings</c>.
|
||||
/// </summary>
|
||||
/// <param name="settings">The user's settings.</param>
|
||||
/// <param name="company">The company's settings.</param>
|
||||
/// <param name="factory">Opens the company database, for the roles of a user.</param>
|
||||
/// <param name="permissions">The user's permissions.</param>
|
||||
/// <param name="licenses">The licensed modules.</param>
|
||||
public sealed class DashboardService(
|
||||
UserSettingsService settings,
|
||||
CompanySettingsService company,
|
||||
IUnitOfWorkFactory factory,
|
||||
PermissionService permissions,
|
||||
ILicenseGate licenses)
|
||||
{
|
||||
/// <summary>The key of the user's layout.</summary>
|
||||
public const string LayoutKey = "dashboard.layout";
|
||||
|
||||
/// <summary>The key of the personal reminders.</summary>
|
||||
public const string NotesKey = "dashboard.notes";
|
||||
|
||||
/// <summary>The key of the shortcuts.</summary>
|
||||
public const string ShortcutsKey = "dashboard.shortcuts";
|
||||
|
||||
/// <summary>The start of the keys of the role defaults in <c>company_settings</c>.</summary>
|
||||
public const string RolePrefix = "dashboard.layout.role.";
|
||||
|
||||
/// <summary>The most reminders kept.</summary>
|
||||
public const int MaxNotes = 20;
|
||||
|
||||
/// <summary>The longest reminder.</summary>
|
||||
public const int MaxNoteLength = 300;
|
||||
|
||||
/// <summary>The most shortcuts kept.</summary>
|
||||
public const int MaxShortcuts = 12;
|
||||
|
||||
/// <summary>The key of the default layout of a role.</summary>
|
||||
/// <param name="roleCode">The role code.</param>
|
||||
/// <returns>The key.</returns>
|
||||
public static string RoleKey(string roleCode) => RolePrefix + roleCode;
|
||||
|
||||
/// <summary>The widgets a user may see: licensed module, permission, administrators only.</summary>
|
||||
/// <param name="actor">The user.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The widgets in catalog order.</returns>
|
||||
public async Task<IReadOnlyList<WidgetDefinition>> AvailableAsync(Actor actor, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var granted = await permissions.GetAsync(actor, cancellationToken).ConfigureAwait(false);
|
||||
return [.. WidgetCatalog.All.Where(w =>
|
||||
licenses.IsModuleActive(w.Module)
|
||||
&& (!w.InstanceOnly || actor.IsInstanceAccount)
|
||||
&& (w.Permission is null || granted.Allows(w.Permission)))];
|
||||
}
|
||||
|
||||
/// <summary>The dashboard to show.</summary>
|
||||
/// <param name="actor">The user.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The layout, limited to the widgets the user may see, and where it comes from.</returns>
|
||||
public async Task<DashboardView> GetAsync(Actor actor, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var available = (await AvailableAsync(actor, cancellationToken).ConfigureAwait(false)).Select(w => w.Id).ToHashSet(StringComparer.Ordinal);
|
||||
if (DashboardLayout.Parse(await settings.GetAsync(actor, LayoutKey, cancellationToken).ConfigureAwait(false)) is { } own)
|
||||
{
|
||||
return new DashboardView(own.Where(available.Contains), DashboardLayoutSource.User);
|
||||
}
|
||||
|
||||
if (await RoleDefaultAsync(actor, cancellationToken).ConfigureAwait(false) is { } fromRole)
|
||||
{
|
||||
return new DashboardView(fromRole.Layout.Where(available.Contains), DashboardLayoutSource.Role, fromRole.RoleCode);
|
||||
}
|
||||
|
||||
return new DashboardView(WidgetCatalog.BuiltIn.Where(available.Contains), DashboardLayoutSource.BuiltIn);
|
||||
}
|
||||
|
||||
/// <summary>Saves the user's layout.</summary>
|
||||
/// <param name="actor">The user.</param>
|
||||
/// <param name="layout">The layout.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public Task SaveAsync(Actor actor, DashboardLayout layout, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(layout);
|
||||
return settings.SetAsync(actor, LayoutKey, layout.ToJson(), cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Forgets the user's layout: the role default or the built-in one comes back.</summary>
|
||||
/// <param name="actor">The user.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public Task ResetAsync(Actor actor, CancellationToken cancellationToken = default) =>
|
||||
settings.SetAsync(actor, LayoutKey, null, cancellationToken);
|
||||
|
||||
/// <summary>The roles of the company with their default layout, if they have one.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The roles in name order.</returns>
|
||||
public async Task<IReadOnlyList<(Role Role, DashboardLayout? Layout)>> RoleDefaultsAsync(string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(companyCode);
|
||||
var defaults = await company.GetAllAsync(companyCode, RolePrefix, cancellationToken).ConfigureAwait(false);
|
||||
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
|
||||
var roles = (await unitOfWork.Repository<Role, long>().ListAsync(Query.For<Role>(), cancellationToken).ConfigureAwait(false)).Items;
|
||||
return [.. roles.OrderBy(r => r.Name, StringComparer.CurrentCulture)
|
||||
.Select(r => (r, defaults.TryGetValue(RoleKey(r.Code), out var json) ? DashboardLayout.Parse(json) : null))];
|
||||
}
|
||||
|
||||
/// <summary>Sets or removes (<see langword="null"/>) the default layout of a role.</summary>
|
||||
/// <param name="actor">Who sets it: needs <c>company.settings.write</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="roleCode">The role.</param>
|
||||
/// <param name="layout">The layout, or <see langword="null"/>.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public Task SaveRoleDefaultAsync(Actor actor, string companyCode, string roleCode, DashboardLayout? layout, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(roleCode);
|
||||
return company.SetAsync(actor, companyCode, RoleKey(roleCode), layout?.ToJson(), cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>The personal reminders.</summary>
|
||||
/// <param name="actor">The user.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The reminders in order.</returns>
|
||||
public async Task<IReadOnlyList<PersonalNote>> GetNotesAsync(Actor actor, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var json = await settings.GetAsync(actor, NotesKey, cancellationToken).ConfigureAwait(false);
|
||||
var notes = new List<PersonalNote>();
|
||||
foreach (var node in ReadArray(json))
|
||||
{
|
||||
if (node is JsonObject item && item["t"]?.GetValueKind() == JsonValueKind.String)
|
||||
{
|
||||
notes.Add(new PersonalNote(item["t"]!.GetValue<string>(), item["d"]?.GetValueKind() == JsonValueKind.True));
|
||||
}
|
||||
}
|
||||
|
||||
return CleanNotes(notes);
|
||||
}
|
||||
|
||||
/// <summary>Saves the personal reminders (at most <see cref="MaxNotes"/>, each up to <see cref="MaxNoteLength"/> characters).</summary>
|
||||
/// <param name="actor">The user.</param>
|
||||
/// <param name="notes">The reminders.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public Task SaveNotesAsync(Actor actor, IReadOnlyList<PersonalNote> notes, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(notes);
|
||||
var array = new JsonArray();
|
||||
foreach (var note in CleanNotes(notes))
|
||||
{
|
||||
array.Add(new JsonObject { ["t"] = note.Text, ["d"] = note.Done });
|
||||
}
|
||||
|
||||
return settings.SetAsync(actor, NotesKey, array.Count == 0 ? null : array.ToJsonString(), cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>The addresses of the shortcut buttons.</summary>
|
||||
/// <param name="actor">The user.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The addresses in order; <see langword="null"/> when the user never chose them.</returns>
|
||||
public async Task<IReadOnlyList<string>?> GetShortcutsAsync(Actor actor, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var json = await settings.GetAsync(actor, ShortcutsKey, cancellationToken).ConfigureAwait(false);
|
||||
if (json is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return CleanShortcuts(ReadArray(json).Where(n => n?.GetValueKind() == JsonValueKind.String).Select(n => n!.GetValue<string>()));
|
||||
}
|
||||
|
||||
/// <summary>Saves the shortcut buttons (local addresses only, at most <see cref="MaxShortcuts"/>).</summary>
|
||||
/// <param name="actor">The user.</param>
|
||||
/// <param name="paths">The addresses.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public Task SaveShortcutsAsync(Actor actor, IReadOnlyList<string> paths, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(paths);
|
||||
var array = new JsonArray();
|
||||
foreach (var path in CleanShortcuts(paths))
|
||||
{
|
||||
array.Add(path);
|
||||
}
|
||||
|
||||
return settings.SetAsync(actor, ShortcutsKey, array.ToJsonString(), cancellationToken);
|
||||
}
|
||||
|
||||
private static List<PersonalNote> CleanNotes(IEnumerable<PersonalNote> notes) =>
|
||||
[
|
||||
.. notes.Select(n => n with { Text = (n.Text ?? string.Empty).Trim() })
|
||||
.Where(n => n.Text.Length > 0)
|
||||
.Select(n => n.Text.Length > MaxNoteLength ? n with { Text = n.Text[..MaxNoteLength] } : n)
|
||||
.Take(MaxNotes),
|
||||
];
|
||||
|
||||
private static List<string> CleanShortcuts(IEnumerable<string> paths) =>
|
||||
[.. paths.Where(UserPreferences.IsLocalPath).Distinct(StringComparer.OrdinalIgnoreCase).Take(MaxShortcuts)];
|
||||
|
||||
private static JsonArray ReadArray(string? json)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(json))
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return JsonNode.Parse(json) as JsonArray ?? [];
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// The default of the first of the user's roles (in role order) that has one. Instance accounts have no roles.
|
||||
private async Task<(DashboardLayout Layout, string RoleCode)?> RoleDefaultAsync(Actor actor, CancellationToken cancellationToken)
|
||||
{
|
||||
if (actor.CompanyCode is not { } companyCode || actor.CompanyUserId is not { } userId)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var defaults = await company.GetAllAsync(companyCode, RolePrefix, cancellationToken).ConfigureAwait(false);
|
||||
if (defaults.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
|
||||
var roleIds = (await unitOfWork.Repository<UserRole, long>().ListAsync(Query.For<UserRole>().Where(r => r.UserId == userId), cancellationToken).ConfigureAwait(false))
|
||||
.Items.Select(r => r.RoleId).ToHashSet();
|
||||
var roles = (await unitOfWork.Repository<Role, long>().ListAsync(Query.For<Role>(), cancellationToken).ConfigureAwait(false)).Items;
|
||||
foreach (var role in roles.Where(r => roleIds.Contains(r.Id)).OrderBy(r => r.Id))
|
||||
{
|
||||
if (defaults.TryGetValue(RoleKey(role.Code), out var json) && DashboardLayout.Parse(json) is { } layout)
|
||||
{
|
||||
return (layout, role.Code);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
using System.Globalization;
|
||||
using Khaemhat.Application.Licensing;
|
||||
using Khaemhat.Application.Localization;
|
||||
using Khaemhat.Application.Notifications;
|
||||
using Khaemhat.Application.Preferences;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Dashboard;
|
||||
|
||||
/// <summary>Text keys of the dashboard areas (the label at the side of a line).</summary>
|
||||
public static class FeedAreas
|
||||
{
|
||||
/// <summary>System and administration.</summary>
|
||||
public const string System = "Dashboard.Areas.System";
|
||||
|
||||
/// <summary>Messages for the user.</summary>
|
||||
public const string Notifications = "Dashboard.Areas.Notifications";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The licence on the dashboard of the administrators: the expiry among the deadlines, and renewing it among the
|
||||
/// things to do once it is near, in grace or expired.
|
||||
/// </summary>
|
||||
/// <param name="licenses">The licence in force.</param>
|
||||
/// <param name="texts">The texts.</param>
|
||||
public sealed class LicenseFeedSource(ILicenseGate licenses, ITexts texts) : ITodoSource, IDeadlineSource
|
||||
{
|
||||
/// <summary>Days before the expiry when renewing becomes a thing to do.</summary>
|
||||
public const int RenewDays = 7;
|
||||
|
||||
private const string Href = "/amministrazione/licenze";
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var license = licenses.Current;
|
||||
if (!context.Actor.IsInstanceAccount || license.IsTestMode)
|
||||
{
|
||||
return Task.FromResult<IReadOnlyList<FeedItem>>([]);
|
||||
}
|
||||
|
||||
var days = license.DaysLeft(context.Now.UtcDateTime);
|
||||
FeedItem? item = license.Status switch
|
||||
{
|
||||
LicenseStatus.Expired => new FeedItem("license", texts["Dashboard.Feed.LicenseExpired"], FeedAreas.System, FeedTone.Error) { Priority = 100, Href = Href },
|
||||
LicenseStatus.Grace => new FeedItem("license", texts["Dashboard.Feed.LicenseGrace"], FeedAreas.System, FeedTone.Error) { Priority = 90, Href = Href },
|
||||
_ when days is { } left && left <= RenewDays => new FeedItem("license", texts.Format("Dashboard.Feed.LicenseRenew", left), FeedAreas.System, FeedTone.Warning)
|
||||
{
|
||||
Priority = 50,
|
||||
Href = Href,
|
||||
},
|
||||
_ => null,
|
||||
};
|
||||
return Task.FromResult<IReadOnlyList<FeedItem>>(item is null ? [] : [item]);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, DateOnly until, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var license = licenses.Current;
|
||||
if (!context.Actor.IsInstanceAccount || license.IsTestMode || license.ExpiresAt is not { } expires || license.Status != LicenseStatus.Valid)
|
||||
{
|
||||
return Task.FromResult<IReadOnlyList<FeedItem>>([]);
|
||||
}
|
||||
|
||||
var when = new DateTimeOffset(DateTime.SpecifyKind(expires, DateTimeKind.Utc)).ToOffset(context.Now.Offset);
|
||||
if (DateOnly.FromDateTime(when.DateTime) > until)
|
||||
{
|
||||
return Task.FromResult<IReadOnlyList<FeedItem>>([]);
|
||||
}
|
||||
|
||||
var key = license.Kind == LicenseKind.Trial ? "Dashboard.Feed.TrialEnds" : "Dashboard.Feed.LicenseEnds";
|
||||
var near = license.DaysLeft(context.Now.UtcDateTime) <= RenewDays;
|
||||
return Task.FromResult<IReadOnlyList<FeedItem>>(
|
||||
[
|
||||
new FeedItem("license-expiry", texts[key], FeedAreas.System, near ? FeedTone.Warning : FeedTone.Info) { When = when, Href = Href },
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The unread warnings and errors addressed to the user, until they are read.</summary>
|
||||
/// <param name="notifications">The notifications.</param>
|
||||
public sealed class NotificationTodoSource(NotificationDispatcher notifications) : ITodoSource
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var unread = await notifications.InboxAsync(context.Actor, unreadOnly: true, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return [.. unread
|
||||
.Where(n => n.Severity >= NotificationSeverity.Warning)
|
||||
.Select(n => new FeedItem("notification-" + n.Id.ToString(CultureInfo.InvariantCulture), n.Title, FeedAreas.Notifications,
|
||||
n.Severity == NotificationSeverity.Warning ? FeedTone.Warning : FeedTone.Error)
|
||||
{
|
||||
Detail = n.Body,
|
||||
Href = UserPreferences.IsLocalPath(n.Link) ? n.Link : null,
|
||||
Priority = n.Severity == NotificationSeverity.Warning ? 60 : 80,
|
||||
When = new DateTimeOffset(DateTime.SpecifyKind(n.CreatedAt, DateTimeKind.Utc)).ToOffset(context.Now.Offset),
|
||||
})];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The scheduled tasks of today for the administrators: those that ran fine among the things done (one line per task),
|
||||
/// those that failed among the things to do.
|
||||
/// </summary>
|
||||
/// <param name="factory">Opens the system database.</param>
|
||||
/// <param name="texts">The texts.</param>
|
||||
public sealed class JobRunFeedSource(IUnitOfWorkFactory factory, ITexts texts) : IDoneSource, ITodoSource
|
||||
{
|
||||
private const string Href = "/amministrazione/attivita";
|
||||
|
||||
/// <inheritdoc />
|
||||
async Task<IReadOnlyList<FeedItem>> IDoneSource.GetAsync(FeedContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
if (!context.Actor.IsInstanceAccount)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var (runs, names) = await TodayAsync(context, cancellationToken).ConfigureAwait(false);
|
||||
return [.. runs
|
||||
.Where(r => r.Outcome == JobOutcome.Succeeded)
|
||||
.GroupBy(r => r.TaskCode, StringComparer.Ordinal)
|
||||
.Select(g =>
|
||||
{
|
||||
var last = g.MaxBy(r => r.FinishedAt ?? r.StartedAt)!;
|
||||
var when = Local(last.FinishedAt ?? last.StartedAt, context);
|
||||
// The widget shows the time of the last run at the side: the detail says how many.
|
||||
var detail = g.Count() == 1 ? texts["Dashboard.Feed.JobRanOnce"] : texts.Format("Dashboard.Feed.JobRanTimes", g.Count());
|
||||
return new FeedItem("job-" + g.Key, names.GetValueOrDefault(g.Key, g.Key), FeedAreas.System, FeedTone.Ok) { Detail = detail, When = when, Href = Href };
|
||||
})];
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
async Task<IReadOnlyList<FeedItem>> ITodoSource.GetAsync(FeedContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
if (!context.Actor.IsInstanceAccount)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var (runs, names) = await TodayAsync(context, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// A task that failed and has not succeeded since is still a thing to do.
|
||||
return [.. runs
|
||||
.GroupBy(r => r.TaskCode, StringComparer.Ordinal)
|
||||
.Select(g => g.MaxBy(r => r.StartedAt)!)
|
||||
.Where(r => r.Outcome == JobOutcome.Failed)
|
||||
.Select(r => new FeedItem("job-failed-" + r.TaskCode, texts.Format("Dashboard.Feed.JobFailed", names.GetValueOrDefault(r.TaskCode, r.TaskCode)), FeedAreas.System, FeedTone.Error)
|
||||
{
|
||||
Detail = r.Message,
|
||||
When = Local(r.StartedAt, context),
|
||||
Href = Href,
|
||||
Priority = 70,
|
||||
})];
|
||||
}
|
||||
|
||||
private static DateTimeOffset Local(DateTime utc, FeedContext context) =>
|
||||
new DateTimeOffset(DateTime.SpecifyKind(utc, DateTimeKind.Utc)).ToOffset(context.Now.Offset);
|
||||
|
||||
private async Task<(IReadOnlyList<JobRun> Runs, IReadOnlyDictionary<string, string> Names)> TodayAsync(FeedContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
var since = context.StartOfToday.UtcDateTime;
|
||||
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
|
||||
var runs = (await unitOfWork.Repository<JobRun, long>().ListAsync(Query.For<JobRun>().Where(r => r.StartedAt >= since), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var tasks = (await unitOfWork.Repository<ScheduledTask, long>().ListAsync(Query.For<ScheduledTask>(), cancellationToken).ConfigureAwait(false)).Items;
|
||||
return (runs, tasks.ToDictionary(t => t.Code, t => t.Name, StringComparer.Ordinal));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
using Khaemhat.Application.Instance;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Companies;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Dashboard;
|
||||
|
||||
/// <summary>What the <em>Stato del sistema</em> widget shows besides version, cache and licence.</summary>
|
||||
/// <param name="Engine">The database engine.</param>
|
||||
/// <param name="Companies">The companies that are not disabled.</param>
|
||||
/// <param name="FailedCompanies">Those that failed to open at start-up.</param>
|
||||
/// <param name="JobsSucceeded">Scheduled task runs of today that succeeded.</param>
|
||||
/// <param name="JobsFailed">Those that failed.</param>
|
||||
public sealed record SystemStatus(DbEngine Engine, int Companies, int FailedCompanies, int JobsSucceeded, int JobsFailed);
|
||||
|
||||
/// <summary>Reads the state of the instance for the administrators' widget.</summary>
|
||||
/// <param name="factory">Opens the system database.</param>
|
||||
/// <param name="system">The system database.</param>
|
||||
/// <param name="companies">The companies.</param>
|
||||
/// <param name="bootstrap">What happened at start-up.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
public sealed class SystemStatusService(IUnitOfWorkFactory factory, DatabaseTarget system, ICompanyRegistry companies, BootstrapState bootstrap, TimeProvider clock)
|
||||
{
|
||||
/// <summary>The state now.</summary>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The state.</returns>
|
||||
public async Task<SystemStatus> GetAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var all = await companies.ListAsync(cancellationToken).ConfigureAwait(false);
|
||||
var now = clock.GetLocalNow();
|
||||
var since = new DateTimeOffset(now.Date, now.Offset).UtcDateTime;
|
||||
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
|
||||
var runs = (await unitOfWork.Repository<JobRun, long>().ListAsync(Query.For<JobRun>().Where(r => r.StartedAt >= since), cancellationToken).ConfigureAwait(false)).Items;
|
||||
return new SystemStatus(
|
||||
system.Engine,
|
||||
all.Count(c => c.Status != CompanyStatus.Disabled),
|
||||
bootstrap.FailedCompanies.Count,
|
||||
runs.Count(r => r.Outcome == JobOutcome.Succeeded),
|
||||
runs.Count(r => r.Outcome == JobOutcome.Failed));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
using Khaemhat.Application.Modules;
|
||||
|
||||
namespace Khaemhat.Application.Dashboard;
|
||||
|
||||
/// <summary>
|
||||
/// A widget of the dashboard (SPEC §10.3, mockup 004): what it is, how wide it starts and who may see it. The
|
||||
/// <see cref="Milestone"/> of a widget whose data comes from a later module says where its data will come from; until
|
||||
/// then the widget shows that instead of invented numbers.
|
||||
/// </summary>
|
||||
/// <param name="Id">The id, kept in the layouts.</param>
|
||||
/// <param name="TitleKey">The text key of the title.</param>
|
||||
/// <param name="Icon">The icon.</param>
|
||||
/// <param name="DefaultWidth">The starting width in columns of twelve.</param>
|
||||
/// <param name="Module">The licensed module it needs.</param>
|
||||
/// <param name="Permission">The permission it needs, if any.</param>
|
||||
/// <param name="InstanceOnly">Only for administrators of the instance.</param>
|
||||
/// <param name="Milestone">The milestone that brings its data, if still to come.</param>
|
||||
public sealed record WidgetDefinition(
|
||||
string Id,
|
||||
string TitleKey,
|
||||
string Icon,
|
||||
int DefaultWidth,
|
||||
string Module,
|
||||
string? Permission = null,
|
||||
bool InstanceOnly = false,
|
||||
string? Milestone = null)
|
||||
{
|
||||
/// <summary>The widths a widget can take, in columns of twelve.</summary>
|
||||
public static readonly IReadOnlyList<int> Widths = [3, 4, 6, 8, 12];
|
||||
|
||||
/// <summary>The text key of the description shown in the customize panel.</summary>
|
||||
public string DescriptionKey => TitleKey[..TitleKey.LastIndexOf('.')] + ".Description";
|
||||
|
||||
/// <summary>The nearest allowed width.</summary>
|
||||
/// <param name="width">Any number.</param>
|
||||
/// <returns>One of <see cref="Widths"/>.</returns>
|
||||
public static int Snap(int width) => Widths.OrderBy(w => Math.Abs(w - width)).ThenByDescending(w => w).First();
|
||||
|
||||
/// <summary>The next width up or down, staying at the ends.</summary>
|
||||
/// <param name="width">The current width.</param>
|
||||
/// <param name="step">+1 wider, -1 narrower.</param>
|
||||
/// <returns>The width.</returns>
|
||||
public static int Step(int width, int step)
|
||||
{
|
||||
var index = Math.Clamp(Widths.ToList().IndexOf(Snap(width)) + Math.Sign(step), 0, Widths.Count - 1);
|
||||
return Widths[index];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The ids of the widgets.</summary>
|
||||
public static class WidgetIds
|
||||
{
|
||||
/// <summary>Indicators chosen by the user.</summary>
|
||||
public const string Kpi = "kpi";
|
||||
|
||||
/// <summary>What to do today.</summary>
|
||||
public const string Todo = "todo";
|
||||
|
||||
/// <summary>What was done today.</summary>
|
||||
public const string Done = "done";
|
||||
|
||||
/// <summary>Deadlines of the next 30 days.</summary>
|
||||
public const string Deadlines = "deadlines";
|
||||
|
||||
/// <summary>Orders and delivery notes still to fulfil.</summary>
|
||||
public const string ToFulfil = "to-fulfil";
|
||||
|
||||
/// <summary>Revenue of the last 12 months.</summary>
|
||||
public const string Revenue = "revenue";
|
||||
|
||||
/// <summary>CRM activities.</summary>
|
||||
public const string CrmActivities = "crm-activities";
|
||||
|
||||
/// <summary>Personal reminders.</summary>
|
||||
public const string Notes = "notes";
|
||||
|
||||
/// <summary>Shortcut buttons.</summary>
|
||||
public const string Shortcuts = "shortcuts";
|
||||
|
||||
/// <summary>Items under the minimum stock.</summary>
|
||||
public const string Understock = "understock";
|
||||
|
||||
/// <summary>The CRM pipeline.</summary>
|
||||
public const string Pipeline = "pipeline";
|
||||
|
||||
/// <summary>The last documents.</summary>
|
||||
public const string RecentDocuments = "recent-documents";
|
||||
|
||||
/// <summary>State of the system (administrators).</summary>
|
||||
public const string SystemStatus = "system";
|
||||
}
|
||||
|
||||
/// <summary>Every widget, in the order of the customize panel (SPEC §10.3).</summary>
|
||||
public static class WidgetCatalog
|
||||
{
|
||||
/// <summary>The widgets.</summary>
|
||||
public static IReadOnlyList<WidgetDefinition> All { get; } =
|
||||
[
|
||||
new(WidgetIds.Kpi, "Dashboard.Widgets.Kpi.Title", "chart", 12, ModuleCodes.Core, "sales.invoice.read", Milestone: "M5"),
|
||||
new(WidgetIds.Todo, "Dashboard.Widgets.Todo.Title", "check-circle", 4, ModuleCodes.Core),
|
||||
new(WidgetIds.Done, "Dashboard.Widgets.Done.Title", "check", 4, ModuleCodes.Core),
|
||||
new(WidgetIds.Deadlines, "Dashboard.Widgets.Deadlines.Title", "calendar", 4, ModuleCodes.Core),
|
||||
new(WidgetIds.ToFulfil, "Dashboard.Widgets.ToFulfil.Title", "truck", 8, ModuleCodes.Core, "sales.order.read", Milestone: "M5"),
|
||||
new(WidgetIds.Revenue, "Dashboard.Widgets.Revenue.Title", "chart", 4, ModuleCodes.Core, "sales.invoice.read", Milestone: "M5"),
|
||||
new(WidgetIds.CrmActivities, "Dashboard.Widgets.CrmActivities.Title", "target", 6, ModuleCodes.Crm, "crm.lead.read", Milestone: "M11"),
|
||||
new(WidgetIds.Notes, "Dashboard.Widgets.Notes.Title", "edit", 4, ModuleCodes.Core),
|
||||
new(WidgetIds.Shortcuts, "Dashboard.Widgets.Shortcuts.Title", "zap", 4, ModuleCodes.Core),
|
||||
new(WidgetIds.Understock, "Dashboard.Widgets.Understock.Title", "box", 6, ModuleCodes.Core, "inventory.stock.read", Milestone: "M6"),
|
||||
new(WidgetIds.Pipeline, "Dashboard.Widgets.Pipeline.Title", "target", 6, ModuleCodes.Crm, "crm.lead.read", Milestone: "M11"),
|
||||
new(WidgetIds.RecentDocuments, "Dashboard.Widgets.RecentDocuments.Title", "file", 6, ModuleCodes.Core, "sales.invoice.read", Milestone: "M5"),
|
||||
new(WidgetIds.SystemStatus, "Dashboard.Widgets.System.Title", "shield", 4, ModuleCodes.Core, InstanceOnly: true),
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// The layout of whoever never customized it and has no default from a role: the widgets that already have data.
|
||||
/// Those that wait for a later module stay in the panel, ready to be switched on.
|
||||
/// </summary>
|
||||
public static DashboardLayout BuiltIn { get; } = new(
|
||||
[
|
||||
new(WidgetIds.Todo, 4),
|
||||
new(WidgetIds.Done, 4),
|
||||
new(WidgetIds.Deadlines, 4),
|
||||
new(WidgetIds.Shortcuts, 4),
|
||||
new(WidgetIds.Notes, 4),
|
||||
new(WidgetIds.SystemStatus, 4),
|
||||
]);
|
||||
|
||||
/// <summary>Finds a widget.</summary>
|
||||
/// <param name="id">The id.</param>
|
||||
/// <returns>The widget, or <see langword="null"/>.</returns>
|
||||
public static WidgetDefinition? Find(string? id) => All.FirstOrDefault(w => string.Equals(w.Id, id, StringComparison.Ordinal));
|
||||
}
|
||||
@@ -0,0 +1,732 @@
|
||||
using System.Data.Common;
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
using Khaemhat.Application.Audit;
|
||||
using Khaemhat.Application.Instance;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Files;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Khaemhat.Infrastructure.Files;
|
||||
|
||||
namespace Khaemhat.Application.Files;
|
||||
|
||||
/// <summary>An attachment as the interface shows it.</summary>
|
||||
/// <param name="Id">The identifier.</param>
|
||||
/// <param name="Entity">The entity of the owning record.</param>
|
||||
/// <param name="EntityId">The owning record.</param>
|
||||
/// <param name="Kind">Uploaded, generated, e-invoice or notification.</param>
|
||||
/// <param name="Name">The name.</param>
|
||||
/// <param name="FileName">The download name, with the version suffix from v2 (<c>fattura_v2.pdf</c>).</param>
|
||||
/// <param name="Mime">The media type.</param>
|
||||
/// <param name="Size">The size in bytes.</param>
|
||||
/// <param name="Sha256">The SHA-256 of the content.</param>
|
||||
/// <param name="Version">The version, from 1.</param>
|
||||
/// <param name="GeneratedBy">The generator code (generated files).</param>
|
||||
/// <param name="Locked">Whether it is locked (cannot be deleted).</param>
|
||||
/// <param name="IsLatest">Whether it is the latest version of its series.</param>
|
||||
/// <param name="CreatedAt">When it was uploaded or generated (UTC).</param>
|
||||
/// <param name="CreatedBy">Who uploaded or generated it.</param>
|
||||
/// <param name="DeletedAt">When it was moved to the trash; <see langword="null"/> if in use.</param>
|
||||
public sealed record AttachmentView(
|
||||
long Id, string Entity, long EntityId, AttachmentKind Kind, string Name, string FileName, string Mime, long Size, string Sha256,
|
||||
int Version, string? GeneratedBy, bool Locked, bool IsLatest, DateTime CreatedAt, string? CreatedBy, DateTime? DeletedAt)
|
||||
{
|
||||
/// <summary>How the interface can preview the file.</summary>
|
||||
public AttachmentPreview Preview => MediaTypes.PreviewOf(Mime);
|
||||
|
||||
/// <summary>The version label, <c>v1</c>, <c>v2</c>...</summary>
|
||||
public string VersionLabel => "v" + Version.ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
/// <summary>The view of a row.</summary>
|
||||
/// <param name="row">The row.</param>
|
||||
/// <param name="isLatest">Whether it is the latest of its series.</param>
|
||||
/// <returns>The view.</returns>
|
||||
public static AttachmentView From(Attachment row, bool isLatest)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(row);
|
||||
return new AttachmentView(
|
||||
row.Id, row.Entity, row.EntityId, row.Kind, row.Name, MediaTypes.VersionedFileName(row.Name, row.Version), row.Mime, row.Size, row.Sha256,
|
||||
row.Version, row.GeneratedBy, row.Locked, isLatest, row.CreatedAt, row.UserName ?? row.CreatedBy, row.DeletedAt);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>An open attachment: its description and its content. Dispose it to close the file.</summary>
|
||||
/// <param name="attachment">The attachment.</param>
|
||||
/// <param name="content">The content, a read-only seekable stream.</param>
|
||||
public sealed class AttachmentContent(AttachmentView attachment, Stream content) : IAsyncDisposable, IDisposable
|
||||
{
|
||||
/// <summary>The attachment.</summary>
|
||||
public AttachmentView Attachment { get; } = attachment;
|
||||
|
||||
/// <summary>The content.</summary>
|
||||
public Stream Content { get; } = content;
|
||||
|
||||
/// <inheritdoc />
|
||||
public ValueTask DisposeAsync() => Content.DisposeAsync();
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose() => Content.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>A file to attach that is not uploaded by a user: an e-invoice, a notification, a file from a procedure.</summary>
|
||||
/// <param name="Kind">The kind.</param>
|
||||
/// <param name="FileName">The file name.</param>
|
||||
/// <param name="Mime">The media type; from the extension when <see langword="null"/>.</param>
|
||||
/// <param name="GeneratedBy">The procedure that produced it: the versions count per this code when set, per name otherwise.</param>
|
||||
/// <param name="Locked">Whether it is locked from the start (for example the XML sent to the SDI).</param>
|
||||
public sealed record AttachmentFile(AttachmentKind Kind, string FileName, string? Mime = null, string? GeneratedBy = null, bool Locked = false);
|
||||
|
||||
/// <summary>
|
||||
/// The attachments of the company records (SPEC §9.4; wiki <i>Allegati e file</i>): upload, generated files with
|
||||
/// versions, list, download, ZIP of all, lock, trash and restore. An attachment belongs to exactly one record
|
||||
/// (<c>entity</c> + <c>entity_id</c>); its bytes are in the <see cref="IFileStore"/>, its row in <c>attachments</c>,
|
||||
/// and every change writes the history (<see cref="AuditTrail"/>).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Permissions: reading needs <c>attachments.read</c>, uploading, generating and locking <c>attachments.write</c>,
|
||||
/// deleting and restoring <c>attachments.delete</c>. The permission on the owning record is checked by the caller (the
|
||||
/// document service or page), which knows it. A company user works only in its own company. Deleting moves to the
|
||||
/// company trash; <see cref="PurgeTrashAsync"/> removes rows and files 30 days later.
|
||||
/// </remarks>
|
||||
public sealed partial class AttachmentService
|
||||
{
|
||||
/// <summary>Permission to see and download attachments.</summary>
|
||||
public const string ReadPermission = "attachments.read";
|
||||
|
||||
/// <summary>Permission to upload and generate attachments.</summary>
|
||||
public const string WritePermission = "attachments.write";
|
||||
|
||||
/// <summary>Permission to delete and restore attachments.</summary>
|
||||
public const string DeletePermission = "attachments.delete";
|
||||
|
||||
/// <summary>The instance setting with the largest upload in MB (default 25).</summary>
|
||||
public const string MaxUploadSetting = "files.max-upload-mb";
|
||||
|
||||
/// <summary>The instance setting with the space each company may use in MB (default: no quota).</summary>
|
||||
public const string CompanyQuotaSetting = "files.company-quota-mb";
|
||||
|
||||
/// <summary>Error: no such attachment (or not in this company).</summary>
|
||||
public const string NotFoundError = "attachments.not_found";
|
||||
|
||||
/// <summary>Error: the attachment is locked.</summary>
|
||||
public const string LockedError = "attachments.locked";
|
||||
|
||||
/// <summary>Error: the file is larger than the limit.</summary>
|
||||
public const string TooLargeError = "attachments.file_too_large";
|
||||
|
||||
/// <summary>Error: the company has no space left.</summary>
|
||||
public const string QuotaError = "attachments.quota_exceeded";
|
||||
|
||||
/// <summary>Error: the scanner rejected the file.</summary>
|
||||
public const string RejectedError = "attachments.file_rejected";
|
||||
|
||||
/// <summary>Error: the entity or record is not valid.</summary>
|
||||
public const string InvalidOwnerError = "attachments.owner_invalid";
|
||||
|
||||
/// <summary>Error: the file is empty.</summary>
|
||||
public const string EmptyError = "attachments.file_empty";
|
||||
|
||||
/// <summary>How long attachments stay in the trash.</summary>
|
||||
public static readonly TimeSpan TrashRetention = TimeSpan.FromDays(30);
|
||||
|
||||
private const int MaxVersionAttempts = 3;
|
||||
private const long Megabyte = 1024 * 1024;
|
||||
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly IFileStore _store;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly AuditTrail _audit;
|
||||
private readonly SystemSettingsStore _settings;
|
||||
private readonly FileStoreOptions _options;
|
||||
private readonly TimeProvider _clock;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="factory">Opens the company databases.</param>
|
||||
/// <param name="store">The file store.</param>
|
||||
/// <param name="permissions">Checks permissions.</param>
|
||||
/// <param name="audit">Writes the history.</param>
|
||||
/// <param name="settings">Reads the limits set by the administrators.</param>
|
||||
/// <param name="options">The default limits.</param>
|
||||
/// <param name="clock">The clock (trash dates).</param>
|
||||
public AttachmentService(
|
||||
IUnitOfWorkFactory factory, IFileStore store, PermissionService permissions, AuditTrail audit, SystemSettingsStore settings, FileStoreOptions options, TimeProvider clock)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(store);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(audit);
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
_factory = factory;
|
||||
_store = store;
|
||||
_permissions = permissions;
|
||||
_audit = audit;
|
||||
_settings = settings;
|
||||
_options = options;
|
||||
_clock = clock;
|
||||
}
|
||||
|
||||
/// <summary>The limits in force: the instance settings, else the store defaults (25 MB, no quota).</summary>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The limits for uploads.</returns>
|
||||
public async Task<FileLimits> GetLimitsAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var max = await ReadMegabytesAsync(MaxUploadSetting, cancellationToken).ConfigureAwait(false) ?? _options.MaxFileBytes;
|
||||
var quota = await ReadMegabytesAsync(CompanyQuotaSetting, cancellationToken).ConfigureAwait(false) ?? _options.CompanyQuotaBytes;
|
||||
return new FileLimits(max, quota);
|
||||
}
|
||||
|
||||
/// <summary>Uploads a file to a record (streaming; the size limit and the quota apply).</summary>
|
||||
/// <param name="actor">Who uploads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="entity">The entity of the record, for example <c>sales.invoice</c>.</param>
|
||||
/// <param name="entityId">The record.</param>
|
||||
/// <param name="fileName">The file name as received.</param>
|
||||
/// <param name="declaredMime">The type declared by the client (used only when the extension is unknown).</param>
|
||||
/// <param name="content">The content.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The new attachment; a file with the same name as an existing one becomes its next version.</returns>
|
||||
/// <exception cref="AccessDeniedException">The actor may not upload.</exception>
|
||||
/// <exception cref="ValidationFailedException">The file is empty, too large, over quota or rejected.</exception>
|
||||
public async Task<AttachmentView> UploadAsync(
|
||||
Actor actor, string companyCode, string entity, long entityId, string fileName, string? declaredMime, Stream content, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(content);
|
||||
var company = await DemandAsync(actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
|
||||
CheckOwner(entity, entityId);
|
||||
var limits = await GetLimitsAsync(cancellationToken).ConfigureAwait(false);
|
||||
var stored = await StoreAsync(company, limits, (target, ct) => content.CopyToAsync(target, ct), cancellationToken).ConfigureAwait(false);
|
||||
var name = MediaTypes.CleanFileName(fileName);
|
||||
return await RecordAsync(actor, company, entity, entityId, new AttachmentFile(AttachmentKind.Uploaded, name, MediaTypes.Resolve(name, declaredMime)), stored, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a file produced by Khaemhat, written by <paramref name="write"/> straight into the store. Each call adds
|
||||
/// the next version of the series of <see cref="AttachmentFile.GeneratedBy"/> (or of the name): this is "Rigenera".
|
||||
/// </summary>
|
||||
/// <param name="actor">Who generates.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="entity">The entity of the record.</param>
|
||||
/// <param name="entityId">The record.</param>
|
||||
/// <param name="file">Kind, name, type, generator, lock.</param>
|
||||
/// <param name="write">Writes the content to the stream it receives (write-only, not seekable).</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The new attachment.</returns>
|
||||
/// <exception cref="AccessDeniedException">The actor may not add attachments.</exception>
|
||||
/// <exception cref="ValidationFailedException">The company has no space left, or the file is empty.</exception>
|
||||
public async Task<AttachmentView> AddAsync(
|
||||
Actor actor, string companyCode, string entity, long entityId, AttachmentFile file, Func<Stream, CancellationToken, Task> write, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(file);
|
||||
ArgumentNullException.ThrowIfNull(write);
|
||||
var company = await DemandAsync(actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
|
||||
CheckOwner(entity, entityId);
|
||||
if (file.GeneratedBy is { } generator && (generator.Length is 0 or > 100))
|
||||
{
|
||||
throw new ValidationFailedException([InvalidOwnerError]);
|
||||
}
|
||||
|
||||
// Files made by Khaemhat are bounded by their generator: only the quota applies.
|
||||
var limits = await GetLimitsAsync(cancellationToken).ConfigureAwait(false);
|
||||
var stored = await StoreAsync(company, new FileLimits(0, limits.QuotaBytes), write, cancellationToken).ConfigureAwait(false);
|
||||
var name = MediaTypes.CleanFileName(file.FileName);
|
||||
var normalized = file with { FileName = name, Mime = MediaTypes.Resolve(name, file.Mime) };
|
||||
return await RecordAsync(actor, company, entity, entityId, normalized, stored, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The attachments of a record, newest first (trash excluded).</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="entity">The entity.</param>
|
||||
/// <param name="entityId">The record.</param>
|
||||
/// <param name="includeOlderVersions">Whether to list the earlier versions too (marked not <see cref="AttachmentView.IsLatest"/>).</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The attachments.</returns>
|
||||
public async Task<IReadOnlyList<AttachmentView>> ListAsync(
|
||||
Actor actor, string companyCode, string entity, long entityId, bool includeOlderVersions = false, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
return Views(await ListRowsAsync(company, entity, entityId, cancellationToken).ConfigureAwait(false), includeOlderVersions);
|
||||
}
|
||||
|
||||
/// <summary>How many attachments a record has (latest versions only): the number on the toolbar icon.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="entity">The entity.</param>
|
||||
/// <param name="entityId">The record.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The count.</returns>
|
||||
public async Task<int> CountAsync(Actor actor, string companyCode, string entity, long entityId, CancellationToken cancellationToken = default) =>
|
||||
(await ListAsync(actor, companyCode, entity, entityId, false, cancellationToken).ConfigureAwait(false)).Count;
|
||||
|
||||
/// <summary>One attachment, in use or in the trash.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="attachmentId">The attachment.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The attachment, or <see langword="null"/>.</returns>
|
||||
public async Task<AttachmentView?> GetAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
return (await LoadAsync(company, attachmentId, cancellationToken).ConfigureAwait(false))?.View;
|
||||
}
|
||||
|
||||
/// <summary>Opens an attachment for download or preview.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="attachmentId">The attachment.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The attachment and its content; dispose it.</returns>
|
||||
/// <exception cref="KeyNotFoundException">No such attachment in use, or its file is missing.</exception>
|
||||
public async Task<AttachmentContent> OpenAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
var loaded = await LoadAsync(company, attachmentId, cancellationToken).ConfigureAwait(false);
|
||||
if (loaded is not { } found || found.Row.DeletedAt is not null)
|
||||
{
|
||||
throw new KeyNotFoundException(NotFoundError);
|
||||
}
|
||||
|
||||
var (row, view) = found;
|
||||
|
||||
try
|
||||
{
|
||||
return new AttachmentContent(view, _store.OpenRead(company, row.StorageKey));
|
||||
}
|
||||
catch (FileStoreException ex) when (ex.Code == FileStoreException.NotFound)
|
||||
{
|
||||
throw new KeyNotFoundException(NotFoundError, ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes a ZIP with the latest version of every attachment of a record ("Scarica tutto"), streaming: the output
|
||||
/// can be the HTTP response.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who downloads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="entity">The entity.</param>
|
||||
/// <param name="entityId">The record.</param>
|
||||
/// <param name="output">The stream that receives the ZIP; it is left open.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>How many files were written.</returns>
|
||||
public async Task<int> WriteZipAsync(Actor actor, string companyCode, string entity, long entityId, Stream output, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(output);
|
||||
var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
var rows = await ListRowsAsync(company, entity, entityId, cancellationToken).ConfigureAwait(false);
|
||||
var keys = rows.ToDictionary(r => r.Id, r => r.StorageKey);
|
||||
await using var zip = await ZipStreamWriter.CreateAsync(output, leaveOpen: true, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var attachment in Views(rows, includeOlderVersions: false))
|
||||
{
|
||||
var key = keys[attachment.Id];
|
||||
if (!_store.Exists(company, key))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var content = _store.OpenRead(company, key);
|
||||
await using (content.ConfigureAwait(false))
|
||||
{
|
||||
var level = attachment.Mime is "image/jpeg" or "image/png" or MediaTypes.Zip or MediaTypes.Xlsx
|
||||
? System.IO.Compression.CompressionLevel.NoCompression
|
||||
: System.IO.Compression.CompressionLevel.Optimal;
|
||||
await zip.AddAsync(attachment.FileName, content, new DateTimeOffset(DateTime.SpecifyKind(attachment.CreatedAt, DateTimeKind.Utc)), level, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
return zip.Count;
|
||||
}
|
||||
|
||||
/// <summary>Locks an attachment: from now on it cannot be deleted (for example the XML sent to the SDI). Locks are permanent.</summary>
|
||||
/// <param name="actor">Who locks.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="attachmentId">The attachment.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public Task LockAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default) =>
|
||||
ChangeAsync(
|
||||
actor, companyCode, attachmentId, WritePermission,
|
||||
row =>
|
||||
{
|
||||
if (row.Locked)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
row.Locked = true;
|
||||
return true;
|
||||
},
|
||||
cancellationToken);
|
||||
|
||||
/// <summary>Moves one attachment to the company trash (restorable for 30 days).</summary>
|
||||
/// <param name="actor">Who deletes.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="attachmentId">The attachment.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
/// <exception cref="ValidationFailedException">The attachment is locked (<see cref="LockedError"/>).</exception>
|
||||
public Task DeleteAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var now = _clock.GetUtcNow().UtcDateTime;
|
||||
return ChangeAsync(
|
||||
actor, companyCode, attachmentId, DeletePermission,
|
||||
row =>
|
||||
{
|
||||
if (row.Locked)
|
||||
{
|
||||
throw new ValidationFailedException([LockedError]);
|
||||
}
|
||||
|
||||
if (row.DeletedAt is not null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
row.DeletedAt = now;
|
||||
return true;
|
||||
},
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Takes an attachment back from the trash.</summary>
|
||||
/// <param name="actor">Who restores.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="attachmentId">The attachment.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public Task RestoreAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default) =>
|
||||
ChangeAsync(
|
||||
actor, companyCode, attachmentId, DeletePermission,
|
||||
row =>
|
||||
{
|
||||
if (row.DeletedAt is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
row.DeletedAt = null;
|
||||
return true;
|
||||
},
|
||||
cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Moves every attachment of a record to the trash: call it in the deletion of the record (the caller has checked
|
||||
/// that the record may be deleted). Refused when an attachment is locked: a record with a sent e-invoice cannot go.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who deletes the record.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="entity">The entity.</param>
|
||||
/// <param name="entityId">The record.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>How many attachments were moved.</returns>
|
||||
/// <exception cref="ValidationFailedException">An attachment is locked (<see cref="LockedError"/>).</exception>
|
||||
public Task<int> TrashForEntityAsync(Actor actor, string companyCode, string entity, long entityId, CancellationToken cancellationToken = default) =>
|
||||
ChangeEntityAsync(actor, companyCode, entity, entityId, toTrash: true, cancellationToken);
|
||||
|
||||
/// <summary>Takes back from the trash every attachment of a record (the record was restored).</summary>
|
||||
/// <param name="actor">Who restores.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="entity">The entity.</param>
|
||||
/// <param name="entityId">The record.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>How many attachments were restored.</returns>
|
||||
public Task<int> RestoreForEntityAsync(Actor actor, string companyCode, string entity, long entityId, CancellationToken cancellationToken = default) =>
|
||||
ChangeEntityAsync(actor, companyCode, entity, entityId, toTrash: false, cancellationToken);
|
||||
|
||||
/// <summary>The company trash, most recently deleted first.</summary>
|
||||
/// <param name="actor">Who looks (needs <c>attachments.delete</c>).</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The attachments in the trash.</returns>
|
||||
public async Task<IReadOnlyList<AttachmentView>> ListTrashAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await DemandAsync(actor, companyCode, DeletePermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var rows = (await unitOfWork.Repository<Attachment, long>().ListAsync(
|
||||
Query.For<Attachment>().Where(a => a.DeletedAt != null).OrderByDescending(a => a.DeletedAt).Take(1000), cancellationToken).ConfigureAwait(false)).Items;
|
||||
return rows.Select(r => AttachmentView.From(r, isLatest: false)).ToList();
|
||||
}
|
||||
|
||||
/// <summary>The space the company uses in the file store, with the quota in force.</summary>
|
||||
/// <param name="actor">Who looks.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The usage.</returns>
|
||||
public async Task<FileUsage> GetUsageAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
var limits = await GetLimitsAsync(cancellationToken).ConfigureAwait(false);
|
||||
return await _store.GetUsageAsync(company, limits.QuotaBytes, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes for good the attachments in the trash for more than 30 days, rows and files, and the partial files of
|
||||
/// interrupted uploads. Run by the scheduled job <see cref="AttachmentTrashPurgeJob"/>.
|
||||
/// </summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>How many attachments were removed.</returns>
|
||||
public async Task<int> PurgeTrashAsync(string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = CompanyCodes.Normalize(companyCode);
|
||||
var limit = _clock.GetUtcNow().UtcDateTime - TrashRetention;
|
||||
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var repository = unitOfWork.Repository<Attachment, long>();
|
||||
var rows = (await repository.ListAsync(Query.For<Attachment>().Where(a => a.DeletedAt != null && a.DeletedAt < limit), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var removed = 0;
|
||||
foreach (var row in rows)
|
||||
{
|
||||
await unitOfWork.InTransactionAsync(
|
||||
async ct =>
|
||||
{
|
||||
await repository.DeleteAsync(row.Id, ct).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(unitOfWork, AuditAction.Delete, row.Id, row, null, Actor.System.UserName, ct).ConfigureAwait(false);
|
||||
},
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// The row is gone: the file follows (a file left behind by a crash here is only wasted space).
|
||||
if (!await StorageKeyInUseAsync(repository, row.StorageKey, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
_store.Delete(company, row.StorageKey);
|
||||
}
|
||||
|
||||
removed++;
|
||||
}
|
||||
|
||||
_store.DeleteAbandonedParts(company, TimeSpan.FromDays(1));
|
||||
return removed;
|
||||
}
|
||||
|
||||
private static List<AttachmentView> Views(IReadOnlyList<Attachment> rows, bool includeOlderVersions)
|
||||
{
|
||||
var latest = rows.GroupBy(r => r.VersionKey, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.Max(r => r.Version), StringComparer.Ordinal);
|
||||
return rows
|
||||
.Select(r => AttachmentView.From(r, r.Version == latest[r.VersionKey]))
|
||||
.Where(v => includeOlderVersions || v.IsLatest)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
private static void CheckOwner(string entity, long entityId)
|
||||
{
|
||||
if (entity is null || entity.Length > 100 || !EntityPattern().IsMatch(entity) || entityId <= 0)
|
||||
{
|
||||
throw new ValidationFailedException([InvalidOwnerError]);
|
||||
}
|
||||
}
|
||||
|
||||
private static string VersionKeyOf(AttachmentFile file) =>
|
||||
file.GeneratedBy is { } generator ? "gen:" + generator : "name:" + file.FileName.ToLowerInvariant();
|
||||
|
||||
private static async Task<bool> IsLatestAsync(IUnitOfWork unitOfWork, Attachment row, CancellationToken cancellationToken)
|
||||
{
|
||||
var (entity, id, key, version) = (row.Entity, row.EntityId, row.VersionKey, row.Version);
|
||||
return await unitOfWork.Repository<Attachment, long>().CountAsync(
|
||||
Query.For<Attachment>().Where(a => a.Entity == entity && a.EntityId == id && a.VersionKey == key && a.Version > version),
|
||||
cancellationToken).ConfigureAwait(false) == 0;
|
||||
}
|
||||
|
||||
private static async Task<bool> StorageKeyInUseAsync(IRepository<Attachment, long> repository, string key, CancellationToken cancellationToken) =>
|
||||
await repository.CountAsync(Query.For<Attachment>().Where(a => a.StorageKey == key), cancellationToken).ConfigureAwait(false) > 0;
|
||||
|
||||
[GeneratedRegex("^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_-]*)*$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex EntityPattern();
|
||||
|
||||
private async Task<string> DemandAsync(Actor actor, string companyCode, string permission, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = CompanyCodes.Normalize(companyCode);
|
||||
if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, company, StringComparison.Ordinal))
|
||||
{
|
||||
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A company user works only in its own company.");
|
||||
}
|
||||
|
||||
await _permissions.DemandAsync(actor, permission, cancellationToken).ConfigureAwait(false);
|
||||
return company;
|
||||
}
|
||||
|
||||
private async Task<long?> ReadMegabytesAsync(string key, CancellationToken cancellationToken)
|
||||
{
|
||||
var value = await _settings.GetAsync(key, cancellationToken).ConfigureAwait(false);
|
||||
return long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var megabytes) && megabytes >= 0 ? megabytes * Megabyte : null;
|
||||
}
|
||||
|
||||
private async Task<StoredFile> StoreAsync(string company, FileLimits limits, Func<Stream, CancellationToken, Task> write, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var writer = await _store.CreateAsync(company, limits, cancellationToken).ConfigureAwait(false);
|
||||
await write(writer.Content, cancellationToken).ConfigureAwait(false);
|
||||
if (writer.Content.Length == 0)
|
||||
{
|
||||
throw new ValidationFailedException([EmptyError]);
|
||||
}
|
||||
|
||||
return await writer.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (FileStoreException ex)
|
||||
{
|
||||
var code = ex.Code switch
|
||||
{
|
||||
FileStoreException.TooLarge => TooLargeError,
|
||||
FileStoreException.QuotaExceeded => QuotaError,
|
||||
_ => RejectedError,
|
||||
};
|
||||
throw new ValidationFailedException(code, ex);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<AttachmentView> RecordAsync(
|
||||
Actor actor, string company, string entity, long entityId, AttachmentFile file, StoredFile stored, CancellationToken cancellationToken)
|
||||
{
|
||||
var key = VersionKeyOf(file);
|
||||
try
|
||||
{
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await InsertAsync(actor, company, entity, entityId, file, key, stored, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (DbException) when (attempt < MaxVersionAttempts)
|
||||
{
|
||||
// Two versions of the same series at once: the unique index refused one; take the next number.
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
_store.Delete(company, stored.Key);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<AttachmentView> InsertAsync(
|
||||
Actor actor, string company, string entity, long entityId, AttachmentFile file, string key, StoredFile stored, CancellationToken cancellationToken)
|
||||
{
|
||||
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var repository = unitOfWork.Repository<Attachment, long>();
|
||||
Attachment? row = null;
|
||||
await unitOfWork.InTransactionAsync(
|
||||
async ct =>
|
||||
{
|
||||
var last = await repository.FindAsync(
|
||||
Query.For<Attachment>().Where(a => a.Entity == entity && a.EntityId == entityId && a.VersionKey == key).OrderByDescending(a => a.Version).Take(1),
|
||||
ct).ConfigureAwait(false);
|
||||
row = new Attachment
|
||||
{
|
||||
Entity = entity,
|
||||
EntityId = entityId,
|
||||
Kind = file.Kind,
|
||||
Name = file.FileName,
|
||||
Mime = file.Mime ?? MediaTypes.OctetStream,
|
||||
Size = stored.Size,
|
||||
Sha256 = stored.Sha256,
|
||||
Version = (last?.Version ?? 0) + 1,
|
||||
VersionKey = key,
|
||||
GeneratedBy = file.GeneratedBy,
|
||||
StorageKey = stored.Key,
|
||||
UserName = actor.UserName.Length > 100 ? actor.UserName[..100] : actor.UserName,
|
||||
Locked = file.Locked,
|
||||
};
|
||||
await repository.InsertAsync(row, ct).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(unitOfWork, AuditAction.Insert, row.Id, null, row, actor.UserName, ct).ConfigureAwait(false);
|
||||
},
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
return AttachmentView.From(row!, isLatest: true);
|
||||
}
|
||||
|
||||
private async Task ChangeAsync(Actor actor, string companyCode, long attachmentId, string permission, Func<Attachment, bool> change, CancellationToken cancellationToken)
|
||||
{
|
||||
var company = await DemandAsync(actor, companyCode, permission, cancellationToken).ConfigureAwait(false);
|
||||
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var repository = unitOfWork.Repository<Attachment, long>();
|
||||
await unitOfWork.InTransactionAsync(
|
||||
async ct =>
|
||||
{
|
||||
var row = await repository.GetAsync(attachmentId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFoundError);
|
||||
var before = Copy(row);
|
||||
if (change(row))
|
||||
{
|
||||
await repository.UpdateAsync(row, ct).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(unitOfWork, AuditAction.Update, row.Id, before, row, actor.UserName, ct).ConfigureAwait(false);
|
||||
}
|
||||
},
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<int> ChangeEntityAsync(Actor actor, string companyCode, string entity, long entityId, bool toTrash, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var company = CompanyCodes.Normalize(companyCode);
|
||||
if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, company, StringComparison.Ordinal))
|
||||
{
|
||||
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A company user works only in its own company.");
|
||||
}
|
||||
|
||||
CheckOwner(entity, entityId);
|
||||
var now = _clock.GetUtcNow().UtcDateTime;
|
||||
var changed = 0;
|
||||
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var repository = unitOfWork.Repository<Attachment, long>();
|
||||
await unitOfWork.InTransactionAsync(
|
||||
async ct =>
|
||||
{
|
||||
var query = toTrash
|
||||
? Query.For<Attachment>().Where(a => a.Entity == entity && a.EntityId == entityId && a.DeletedAt == null)
|
||||
: Query.For<Attachment>().Where(a => a.Entity == entity && a.EntityId == entityId && a.DeletedAt != null);
|
||||
var rows = (await repository.ListAsync(query, ct).ConfigureAwait(false)).Items;
|
||||
if (toTrash && rows.Any(r => r.Locked))
|
||||
{
|
||||
throw new ValidationFailedException([LockedError]);
|
||||
}
|
||||
|
||||
foreach (var row in rows)
|
||||
{
|
||||
var before = Copy(row);
|
||||
row.DeletedAt = toTrash ? now : null;
|
||||
await repository.UpdateAsync(row, ct).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(unitOfWork, AuditAction.Update, row.Id, before, row, actor.UserName, ct).ConfigureAwait(false);
|
||||
changed++;
|
||||
}
|
||||
},
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
return changed;
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<Attachment>> ListRowsAsync(string company, string entity, long entityId, CancellationToken cancellationToken)
|
||||
{
|
||||
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return (await unitOfWork.Repository<Attachment, long>().ListAsync(
|
||||
Query.For<Attachment>().Where(a => a.Entity == entity && a.EntityId == entityId && a.DeletedAt == null).OrderByDescending(a => a.Id),
|
||||
cancellationToken).ConfigureAwait(false)).Items;
|
||||
}
|
||||
|
||||
private async Task<(Attachment Row, AttachmentView View)?> LoadAsync(string company, long attachmentId, CancellationToken cancellationToken)
|
||||
{
|
||||
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var row = await unitOfWork.Repository<Attachment, long>().GetAsync(attachmentId, cancellationToken).ConfigureAwait(false);
|
||||
return row is null ? null : (row, AttachmentView.From(row, await IsLatestAsync(unitOfWork, row, cancellationToken).ConfigureAwait(false)));
|
||||
}
|
||||
|
||||
private static Attachment Copy(Attachment row) => new()
|
||||
{
|
||||
Id = row.Id,
|
||||
Entity = row.Entity,
|
||||
EntityId = row.EntityId,
|
||||
Kind = row.Kind,
|
||||
Name = row.Name,
|
||||
Mime = row.Mime,
|
||||
Size = row.Size,
|
||||
Sha256 = row.Sha256,
|
||||
Version = row.Version,
|
||||
VersionKey = row.VersionKey,
|
||||
GeneratedBy = row.GeneratedBy,
|
||||
StorageKey = row.StorageKey,
|
||||
UserName = row.UserName,
|
||||
Locked = row.Locked,
|
||||
DeletedAt = row.DeletedAt,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System.Globalization;
|
||||
using Khaemhat.Application.Jobs;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Data.Companies;
|
||||
|
||||
namespace Khaemhat.Application.Files;
|
||||
|
||||
/// <summary>
|
||||
/// Empties the company trash of attachments (SPEC §9.4): every night, in every company that is not disabled, removes
|
||||
/// rows and files deleted more than 30 days ago and the partial files of interrupted uploads.
|
||||
/// </summary>
|
||||
/// <param name="attachments">The attachments.</param>
|
||||
/// <param name="companies">The companies.</param>
|
||||
public sealed class AttachmentTrashPurgeJob(AttachmentService attachments, ICompanyRegistry companies) : IScheduledJob
|
||||
{
|
||||
/// <summary>The job type.</summary>
|
||||
public const string JobType = "system.attachments-trash";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Type => JobType;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<string?> RunAsync(JobContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
var removed = 0;
|
||||
foreach (var company in await companies.ListAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (company.Status is not CompanyStatus.Disabled)
|
||||
{
|
||||
removed += await attachments.PurgeTrashAsync(company.Code, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
return string.Create(CultureInfo.InvariantCulture, $"{removed} allegati eliminati dal cestino.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
using System.Globalization;
|
||||
using Khaemhat.Infrastructure.Files;
|
||||
|
||||
namespace Khaemhat.Application.Files;
|
||||
|
||||
/// <summary>
|
||||
/// The <i>documento di prova</i> of issue #34: a clearly fictitious document (entity <see cref="Entity"/>) used to try
|
||||
/// attachments, generation, versions and print preview before the real documents exist (M5). Every value is invented.
|
||||
/// </summary>
|
||||
public static class DemoDocument
|
||||
{
|
||||
/// <summary>The entity of the test document.</summary>
|
||||
public const string Entity = "demo.document";
|
||||
|
||||
/// <summary>The title printed on the test document.</summary>
|
||||
public const string Title = "Documento di prova";
|
||||
|
||||
/// <summary>The fictitious lines: code, description, quantity, unit price.</summary>
|
||||
public static IReadOnlyList<(string Code, string Description, decimal Quantity, decimal UnitPrice)> Lines { get; } =
|
||||
[
|
||||
("PROVA-001", "Articolo di prova – vite inventata", 10m, 1.25m),
|
||||
("PROVA-002", "Servizio fittizio di consulenza (non reale)", 2m, 480m),
|
||||
("PROVA-003", "Materiale d'esempio: cavo €uro-test 3×1,5", 25.5m, 3.9m),
|
||||
("PROVA-004", "Riga con accenti: perché, città, più, così", 1m, 1234.56m),
|
||||
("PROVA-005", "Sconto finto", 1m, -50m),
|
||||
];
|
||||
|
||||
/// <summary>The headers of the line table.</summary>
|
||||
public static IReadOnlyList<string> Headers { get; } = ["Codice", "Descrizione", "Quantità", "Prezzo unitario", "Importo"];
|
||||
|
||||
/// <summary>The amount of a line.</summary>
|
||||
/// <param name="line">The line.</param>
|
||||
/// <returns>Quantity times unit price, rounded to cents.</returns>
|
||||
public static decimal Amount((string Code, string Description, decimal Quantity, decimal UnitPrice) line) =>
|
||||
Math.Round(line.Quantity * line.UnitPrice, 2, MidpointRounding.AwayFromZero);
|
||||
|
||||
/// <summary>The total of the lines.</summary>
|
||||
public static decimal Total => Lines.Sum(Amount);
|
||||
|
||||
/// <summary>An amount in euro as Italians write it: <c>€ 1.234,56</c>.</summary>
|
||||
/// <param name="value">The amount.</param>
|
||||
/// <param name="culture">The culture (it-IT).</param>
|
||||
/// <returns>The text.</returns>
|
||||
public static string Euro(decimal value, CultureInfo culture) =>
|
||||
(value < 0 ? "-€ " : "€ ") + Math.Abs(value).ToString("N2", culture);
|
||||
|
||||
/// <summary>The file name stem for a record.</summary>
|
||||
/// <param name="context">The record.</param>
|
||||
/// <returns>For example <c>documento-di-prova-7</c>.</returns>
|
||||
public static string Stem(FileGenerationContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
return "documento-di-prova-" + context.EntityId.ToString(CultureInfo.InvariantCulture);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The test PDF of the test document: title, a paragraph and the table of lines with amounts aligned right.</summary>
|
||||
public sealed class DemoPdfGenerator : IFileGenerator
|
||||
{
|
||||
/// <summary>The generator code.</summary>
|
||||
public const string GeneratorCode = "demo.test-pdf";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Code => GeneratorCode;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string TitleKey => "files.generators.demo_pdf";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string MediaType => PdfWriter.MediaType;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Extension => ".pdf";
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool Supports(string entity) => entity == DemoDocument.Entity;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string FileName(FileGenerationContext context) => DemoDocument.Stem(context) + Extension;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task GenerateAsync(FileGenerationContext context, Stream output, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var culture = context.Culture;
|
||||
var accent = PdfColor.FromHex("#1F5F8B");
|
||||
var muted = PdfColor.Gray(110);
|
||||
var info = new PdfDocumentInfo
|
||||
{
|
||||
Title = DemoDocument.Title + " n. " + context.EntityId.ToString(CultureInfo.InvariantCulture),
|
||||
Author = context.CompanyCode,
|
||||
Subject = "Documento fittizio per provare la generazione dei file",
|
||||
CreationDate = new DateTimeOffset(DateTime.SpecifyKind(context.Now, DateTimeKind.Utc)),
|
||||
};
|
||||
|
||||
await using var pdf = new PdfWriter(output, info, leaveOpen: true);
|
||||
var page = await pdf.AddPageAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
const double left = 50;
|
||||
var right = page.Width - 50;
|
||||
var y = page.Height - 70;
|
||||
|
||||
page.DrawText(DemoDocument.Title, left, y, PdfFont.HelveticaBold, 20, accent);
|
||||
page.DrawTextRight("n. " + context.EntityId.ToString(CultureInfo.InvariantCulture) + " del " + context.Now.ToString("d", culture), right, y, PdfFont.Helvetica, 10, muted);
|
||||
y -= 12;
|
||||
page.DrawLine(left, y, right, y, 1, accent);
|
||||
y -= 22;
|
||||
y = page.DrawParagraph(
|
||||
"Questo è un documento di prova generato da Khaemhat: azienda " + context.CompanyCode + ", generato da " + context.Actor.UserName
|
||||
+ ". Righe, prezzi e importi sono inventati e servono solo a provare stampa, allegati e versioni (v1, v2…).",
|
||||
left, y, right - left, PdfFont.Helvetica, 10, 13);
|
||||
y -= 16;
|
||||
|
||||
// Table: code, description, quantity, unit price, amount (the last three aligned right).
|
||||
double[] edges = [left, left + 75, right - 205, right - 135, right - 65, right];
|
||||
page.DrawRectangle(left, y - 6, right - left, 18, fill: PdfColor.Gray(235));
|
||||
for (var i = 0; i < DemoDocument.Headers.Count; i++)
|
||||
{
|
||||
if (i < 2)
|
||||
{
|
||||
page.DrawText(DemoDocument.Headers[i], edges[i] + 4, y, PdfFont.HelveticaBold, 9);
|
||||
}
|
||||
else
|
||||
{
|
||||
page.DrawTextRight(DemoDocument.Headers[i], edges[i + 1] - 4, y, PdfFont.HelveticaBold, 9);
|
||||
}
|
||||
}
|
||||
|
||||
y -= 20;
|
||||
foreach (var line in DemoDocument.Lines)
|
||||
{
|
||||
page.DrawText(line.Code, edges[0] + 4, y, PdfFont.Courier, 9);
|
||||
page.DrawText(PdfTextLayout.Fit(line.Description, PdfFont.Helvetica, 9, edges[2] - edges[1] - 8), edges[1] + 4, y, PdfFont.Helvetica, 9);
|
||||
page.DrawTextRight(line.Quantity.ToString("#,##0.##", culture), edges[3] - 4, y, PdfFont.Helvetica, 9);
|
||||
page.DrawTextRight(DemoDocument.Euro(line.UnitPrice, culture), edges[4] - 4, y, PdfFont.Helvetica, 9);
|
||||
page.DrawTextRight(DemoDocument.Euro(DemoDocument.Amount(line), culture), edges[5] - 4, y, PdfFont.Helvetica, 9);
|
||||
y -= 6;
|
||||
page.DrawLine(left, y, right, y, 0.25, PdfColor.Gray(200));
|
||||
y -= 12;
|
||||
}
|
||||
|
||||
y -= 4;
|
||||
page.DrawText("Totale", edges[3] + 4, y, PdfFont.HelveticaBold, 11);
|
||||
page.DrawTextRight(DemoDocument.Euro(DemoDocument.Total, culture), right - 4, y, PdfFont.HelveticaBold, 11, accent);
|
||||
|
||||
page.DrawText("Documento fittizio – nessun valore fiscale", left, 40, PdfFont.HelveticaOblique, 8, muted);
|
||||
page.DrawTextRight("Pagina 1", right, 40, PdfFont.Helvetica, 8, muted);
|
||||
await pdf.CloseAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The lines of the test document as CSV (Italian Excel: <c>;</c>, decimal comma, BOM).</summary>
|
||||
public sealed class DemoCsvGenerator : IFileGenerator
|
||||
{
|
||||
/// <summary>The generator code.</summary>
|
||||
public const string GeneratorCode = "demo.test-csv";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Code => GeneratorCode;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string TitleKey => "files.generators.demo_csv";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string MediaType => MediaTypes.Csv;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Extension => ".csv";
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool Supports(string entity) => entity == DemoDocument.Entity;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string FileName(FileGenerationContext context) => DemoDocument.Stem(context) + "-righe" + Extension;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task GenerateAsync(FileGenerationContext context, Stream output, CancellationToken cancellationToken)
|
||||
{
|
||||
await using var csv = new CsvWriter(output, CsvOptions.Italian, leaveOpen: true);
|
||||
await csv.WriteRowAsync(DemoDocument.Headers, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var line in DemoDocument.Lines)
|
||||
{
|
||||
await csv.WriteRowAsync([line.Code, line.Description, line.Quantity, line.UnitPrice, DemoDocument.Amount(line)], cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await csv.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The lines of the test document as an XLSX sheet with bold header and euro amounts.</summary>
|
||||
public sealed class DemoXlsxGenerator : IFileGenerator
|
||||
{
|
||||
/// <summary>The generator code.</summary>
|
||||
public const string GeneratorCode = "demo.test-xlsx";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Code => GeneratorCode;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string TitleKey => "files.generators.demo_xlsx";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string MediaType => XlsxWriter.MediaType;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Extension => ".xlsx";
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool Supports(string entity) => entity == DemoDocument.Entity;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string FileName(FileGenerationContext context) => DemoDocument.Stem(context) + "-righe" + Extension;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task GenerateAsync(FileGenerationContext context, Stream output, CancellationToken cancellationToken)
|
||||
{
|
||||
var xlsx = await XlsxWriter.CreateAsync(output, leaveOpen: true, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
await using (xlsx.ConfigureAwait(false))
|
||||
{
|
||||
await xlsx.StartSheetAsync(
|
||||
"Righe",
|
||||
[
|
||||
new XlsxColumn(DemoDocument.Headers[0], 14),
|
||||
new XlsxColumn(DemoDocument.Headers[1], 48),
|
||||
new XlsxColumn(DemoDocument.Headers[2], 12, XlsxFormat.TwoDecimals),
|
||||
new XlsxColumn(DemoDocument.Headers[3], 16, XlsxFormat.Euro),
|
||||
new XlsxColumn(DemoDocument.Headers[4], 16, XlsxFormat.Euro),
|
||||
],
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
foreach (var line in DemoDocument.Lines)
|
||||
{
|
||||
await xlsx.WriteRowAsync([line.Code, line.Description, line.Quantity, line.UnitPrice, DemoDocument.Amount(line)], cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await xlsx.WriteRowAsync([null, "Totale", null, null, DemoDocument.Total], cancellationToken).ConfigureAwait(false);
|
||||
await xlsx.CompleteAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
using System.Globalization;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Files;
|
||||
using Khaemhat.Data;
|
||||
|
||||
namespace Khaemhat.Application.Files;
|
||||
|
||||
/// <summary>What a generator receives besides the output stream.</summary>
|
||||
/// <param name="Actor">Who asked for the file (the generator reads data on its behalf).</param>
|
||||
/// <param name="CompanyCode">The company.</param>
|
||||
/// <param name="Entity">The entity of the record, for example <c>sales.invoice</c>.</param>
|
||||
/// <param name="EntityId">The record.</param>
|
||||
/// <param name="Culture">The culture of numbers, dates and texts (it-IT).</param>
|
||||
/// <param name="Now">When the file is generated (UTC).</param>
|
||||
public sealed record FileGenerationContext(Actor Actor, string CompanyCode, string Entity, long EntityId, CultureInfo Culture, DateTime Now);
|
||||
|
||||
/// <summary>
|
||||
/// An output of the <i>Genera file</i> section (SPEC §9.4): print PDF, XML FatturaPA, rows in XLSX/CSV, courtesy ZIP...
|
||||
/// Modules register theirs as <see cref="IFileGenerator"/> singletons; <see cref="FileGenerationService"/> runs them.
|
||||
/// </summary>
|
||||
public interface IFileGenerator
|
||||
{
|
||||
/// <summary>The unique code, also written in <c>attachments.generated_by</c> (versions count per code), for example <c>sales.invoice.pdf</c>.</summary>
|
||||
string Code { get; }
|
||||
|
||||
/// <summary>The text key of the label shown in the interface (Italian text in the Web resources).</summary>
|
||||
string TitleKey { get; }
|
||||
|
||||
/// <summary>The media type of the output.</summary>
|
||||
string MediaType { get; }
|
||||
|
||||
/// <summary>The extension of the output, with the dot (<c>.pdf</c>).</summary>
|
||||
string Extension { get; }
|
||||
|
||||
/// <summary>Whether the generator applies to records of an entity.</summary>
|
||||
/// <param name="entity">The entity.</param>
|
||||
/// <returns><see langword="true"/> if it does.</returns>
|
||||
bool Supports(string entity);
|
||||
|
||||
/// <summary>The file name for a record, with extension (for example <c>Fattura-2026-15.pdf</c>).</summary>
|
||||
/// <param name="context">The record.</param>
|
||||
/// <returns>The file name.</returns>
|
||||
string FileName(FileGenerationContext context);
|
||||
|
||||
/// <summary>Writes the file. The stream is write-only and not seekable; write with asynchronous calls.</summary>
|
||||
/// <param name="context">The record.</param>
|
||||
/// <param name="output">The stream that receives the file; do not close it.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
Task GenerateAsync(FileGenerationContext context, Stream output, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>The registered generators, by code.</summary>
|
||||
public sealed class FileGeneratorRegistry
|
||||
{
|
||||
private readonly Dictionary<string, IFileGenerator> _byCode;
|
||||
|
||||
/// <summary>Creates the registry.</summary>
|
||||
/// <param name="generators">The generators (codes must be unique).</param>
|
||||
public FileGeneratorRegistry(IEnumerable<IFileGenerator> generators)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(generators);
|
||||
_byCode = new Dictionary<string, IFileGenerator>(StringComparer.Ordinal);
|
||||
foreach (var generator in generators)
|
||||
{
|
||||
if (!_byCode.TryAdd(generator.Code, generator))
|
||||
{
|
||||
throw new InvalidOperationException($"Two file generators have code {generator.Code}.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Every generator, by code.</summary>
|
||||
public IReadOnlyCollection<IFileGenerator> All => _byCode.Values;
|
||||
|
||||
/// <summary>The generator with a code.</summary>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <returns>The generator, or <see langword="null"/>.</returns>
|
||||
public IFileGenerator? Find(string code) => _byCode.GetValueOrDefault(code);
|
||||
|
||||
/// <summary>The generators that apply to an entity, by code.</summary>
|
||||
/// <param name="entity">The entity.</param>
|
||||
/// <returns>The generators.</returns>
|
||||
public IReadOnlyList<IFileGenerator> For(string entity) =>
|
||||
_byCode.Values.Where(g => g.Supports(entity)).OrderBy(g => g.Code, StringComparer.Ordinal).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs the generators (SPEC §9.4): <see cref="GenerateAsync"/> writes the file straight into the file store and
|
||||
/// records it as a generated attachment of the record, with the next version (<c>v1</c>, <c>v2</c>... "Rigenera");
|
||||
/// <see cref="WriteAsync"/> writes it to any stream without keeping it (print preview, direct download).
|
||||
/// </summary>
|
||||
/// <param name="registry">The generators.</param>
|
||||
/// <param name="attachments">Records the generated files.</param>
|
||||
/// <param name="permissions">Checks permissions for <see cref="WriteAsync"/>.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
public sealed class FileGenerationService(FileGeneratorRegistry registry, AttachmentService attachments, PermissionService permissions, TimeProvider clock)
|
||||
{
|
||||
/// <summary>Error: no generator with that code applies to the record.</summary>
|
||||
public const string UnknownGeneratorError = "attachments.generator_unknown";
|
||||
|
||||
private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT");
|
||||
|
||||
/// <summary>The generators that apply to an entity (the <i>Genera file</i> list).</summary>
|
||||
/// <param name="entity">The entity.</param>
|
||||
/// <returns>The generators.</returns>
|
||||
public IReadOnlyList<IFileGenerator> AvailableFor(string entity) => registry.For(entity);
|
||||
|
||||
/// <summary>Generates a file and attaches it to the record as the next version of the generator's series.</summary>
|
||||
/// <param name="actor">Who generates (needs <c>attachments.write</c>).</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="entity">The entity.</param>
|
||||
/// <param name="entityId">The record.</param>
|
||||
/// <param name="generatorCode">The generator.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The new attachment.</returns>
|
||||
/// <exception cref="ValidationFailedException">No such generator for the entity (<see cref="UnknownGeneratorError"/>).</exception>
|
||||
public Task<AttachmentView> GenerateAsync(
|
||||
Actor actor, string companyCode, string entity, long entityId, string generatorCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var generator = Resolve(entity, generatorCode);
|
||||
var context = Context(actor, companyCode, entity, entityId);
|
||||
var file = new AttachmentFile(AttachmentKind.Generated, generator.FileName(context), generator.MediaType, generator.Code);
|
||||
return attachments.AddAsync(actor, companyCode, entity, entityId, file, (output, ct) => generator.GenerateAsync(context, output, ct), cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Generates a file into a stream without attaching it (print preview, report download).</summary>
|
||||
/// <param name="actor">Who asks (needs <c>attachments.read</c>).</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="entity">The entity.</param>
|
||||
/// <param name="entityId">The record.</param>
|
||||
/// <param name="generatorCode">The generator.</param>
|
||||
/// <param name="output">The stream; left open.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The file name and media type of what was written.</returns>
|
||||
public async Task<(string FileName, string MediaType)> WriteAsync(
|
||||
Actor actor, string companyCode, string entity, long entityId, string generatorCode, Stream output, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
ArgumentNullException.ThrowIfNull(output);
|
||||
var generator = Resolve(entity, generatorCode);
|
||||
if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, CompanyCodes.Normalize(companyCode), StringComparison.Ordinal))
|
||||
{
|
||||
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A company user works only in its own company.");
|
||||
}
|
||||
|
||||
await permissions.DemandAsync(actor, AttachmentService.ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
var context = Context(actor, companyCode, entity, entityId);
|
||||
await generator.GenerateAsync(context, output, cancellationToken).ConfigureAwait(false);
|
||||
return (MediaTypes.CleanFileName(generator.FileName(context)), generator.MediaType);
|
||||
}
|
||||
|
||||
private IFileGenerator Resolve(string entity, string generatorCode)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entity);
|
||||
ArgumentNullException.ThrowIfNull(generatorCode);
|
||||
return registry.Find(generatorCode) is { } generator && generator.Supports(entity)
|
||||
? generator
|
||||
: throw new ValidationFailedException([UnknownGeneratorError]);
|
||||
}
|
||||
|
||||
private FileGenerationContext Context(Actor actor, string companyCode, string entity, long entityId) =>
|
||||
new(actor, CompanyCodes.Normalize(companyCode), entity, entityId, Italian, clock.GetUtcNow().UtcDateTime);
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
using System.Globalization;
|
||||
using System.IO.Compression;
|
||||
using System.Text;
|
||||
using System.Xml;
|
||||
|
||||
namespace Khaemhat.Application.Files;
|
||||
|
||||
/// <summary>What the preview of a text or table file shows (mockup 024: XML, CSV, XLSX).</summary>
|
||||
/// <param name="Kind">The kind of preview.</param>
|
||||
/// <param name="Text">The text (XML, plain text), possibly cut.</param>
|
||||
/// <param name="Rows">The cells (CSV, XLSX), possibly cut.</param>
|
||||
/// <param name="Truncated">Whether the file goes on after what is shown.</param>
|
||||
public sealed record FilePreview(AttachmentPreview Kind, string? Text, IReadOnlyList<IReadOnlyList<string>>? Rows, bool Truncated)
|
||||
{
|
||||
/// <summary>The most characters of text shown.</summary>
|
||||
public const int MaxChars = 200_000;
|
||||
|
||||
/// <summary>The most rows of a table shown.</summary>
|
||||
public const int MaxRows = 200;
|
||||
|
||||
/// <summary>The most columns of a table shown.</summary>
|
||||
public const int MaxColumns = 40;
|
||||
|
||||
/// <summary>Reads the preview of a file; PDF and images are shown by the browser and give no text.</summary>
|
||||
/// <param name="kind">The kind, from the media type.</param>
|
||||
/// <param name="content">The content, readable.</param>
|
||||
/// <param name="culture">The culture for numbers of spreadsheets.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The preview; with neither text nor rows when the file cannot be read.</returns>
|
||||
public static async Task<FilePreview> ReadAsync(AttachmentPreview kind, Stream content, CultureInfo culture, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(content);
|
||||
ArgumentNullException.ThrowIfNull(culture);
|
||||
try
|
||||
{
|
||||
return kind switch
|
||||
{
|
||||
AttachmentPreview.Xml or AttachmentPreview.Text => await TextAsync(kind, content, cancellationToken).ConfigureAwait(false),
|
||||
AttachmentPreview.Csv => await CsvAsync(content, cancellationToken).ConfigureAwait(false),
|
||||
AttachmentPreview.Xlsx => await XlsxAsync(content, culture, cancellationToken).ConfigureAwait(false),
|
||||
_ => new FilePreview(kind, null, null, false),
|
||||
};
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidDataException or XmlException or IOException)
|
||||
{
|
||||
return new FilePreview(kind, null, null, false);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<(string Text, bool Truncated)> ReadTextAsync(Stream content, CancellationToken cancellationToken)
|
||||
{
|
||||
using var reader = new StreamReader(content, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, leaveOpen: true);
|
||||
var buffer = new char[MaxChars + 1];
|
||||
var read = 0;
|
||||
while (read < buffer.Length)
|
||||
{
|
||||
var n = await reader.ReadAsync(buffer.AsMemory(read), cancellationToken).ConfigureAwait(false);
|
||||
if (n == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
read += n;
|
||||
}
|
||||
|
||||
return read > MaxChars ? (new string(buffer, 0, MaxChars), true) : (new string(buffer, 0, read), false);
|
||||
}
|
||||
|
||||
private static async Task<FilePreview> TextAsync(AttachmentPreview kind, Stream content, CancellationToken cancellationToken)
|
||||
{
|
||||
var (text, truncated) = await ReadTextAsync(content, cancellationToken).ConfigureAwait(false);
|
||||
return new FilePreview(kind, text, null, truncated);
|
||||
}
|
||||
|
||||
private static async Task<FilePreview> CsvAsync(Stream content, CancellationToken cancellationToken)
|
||||
{
|
||||
var (text, truncated) = await ReadTextAsync(content, cancellationToken).ConfigureAwait(false);
|
||||
var rows = Csv(text, out var more);
|
||||
return new FilePreview(AttachmentPreview.Csv, null, rows, truncated || more);
|
||||
}
|
||||
|
||||
/// <summary>Splits CSV text into cells: separator <c>;</c> or <c>,</c> (the more frequent in the first line), quotes as RFC 4180.</summary>
|
||||
/// <param name="text">The text.</param>
|
||||
/// <param name="truncated">Whether there were more rows than <see cref="MaxRows"/>.</param>
|
||||
/// <returns>The rows.</returns>
|
||||
public static List<IReadOnlyList<string>> Csv(string text, out bool truncated)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(text);
|
||||
var firstLine = text.AsSpan(0, Math.Max(0, text.IndexOf('\n') is var nl and >= 0 ? nl : text.Length));
|
||||
var separator = firstLine.Count(';') >= firstLine.Count(',') ? ';' : ',';
|
||||
var rows = new List<IReadOnlyList<string>>();
|
||||
var row = new List<string>();
|
||||
var cell = new StringBuilder();
|
||||
var quoted = false;
|
||||
truncated = false;
|
||||
for (var i = 0; i < text.Length; i++)
|
||||
{
|
||||
var c = text[i];
|
||||
if (quoted)
|
||||
{
|
||||
if (c == '"' && i + 1 < text.Length && text[i + 1] == '"')
|
||||
{
|
||||
cell.Append('"');
|
||||
i++;
|
||||
}
|
||||
else if (c == '"')
|
||||
{
|
||||
quoted = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
cell.Append(c);
|
||||
}
|
||||
}
|
||||
else if (c == '"' && cell.Length == 0)
|
||||
{
|
||||
quoted = true;
|
||||
}
|
||||
else if (c == separator)
|
||||
{
|
||||
AddCell();
|
||||
}
|
||||
else if (c == '\n')
|
||||
{
|
||||
if (!EndRow())
|
||||
{
|
||||
truncated = true;
|
||||
return rows;
|
||||
}
|
||||
}
|
||||
else if (c != '\r' && c != '')
|
||||
{
|
||||
cell.Append(c);
|
||||
}
|
||||
}
|
||||
|
||||
if (cell.Length > 0 || row.Count > 0)
|
||||
{
|
||||
EndRow();
|
||||
}
|
||||
|
||||
return rows;
|
||||
|
||||
void AddCell()
|
||||
{
|
||||
if (row.Count < MaxColumns)
|
||||
{
|
||||
row.Add(cell.ToString());
|
||||
}
|
||||
|
||||
cell.Clear();
|
||||
}
|
||||
|
||||
bool EndRow()
|
||||
{
|
||||
AddCell();
|
||||
if (rows.Count == MaxRows)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
rows.Add([.. row]);
|
||||
row.Clear();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<FilePreview> XlsxAsync(Stream content, CultureInfo culture, CancellationToken cancellationToken)
|
||||
{
|
||||
// ZipArchive needs a seekable stream; attachments are files, generated content is copied first.
|
||||
var source = content;
|
||||
MemoryStream? copy = null;
|
||||
if (!content.CanSeek)
|
||||
{
|
||||
copy = new MemoryStream();
|
||||
await content.CopyToAsync(copy, cancellationToken).ConfigureAwait(false);
|
||||
copy.Position = 0;
|
||||
source = copy;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var zip = new ZipArchive(source, ZipArchiveMode.Read, leaveOpen: true);
|
||||
var shared = zip.GetEntry("xl/sharedStrings.xml") is { } strings ? SharedStrings(strings) : [];
|
||||
var sheet = zip.GetEntry("xl/worksheets/sheet1.xml")
|
||||
?? zip.Entries.Where(e => e.FullName.StartsWith("xl/worksheets/", StringComparison.Ordinal) && e.FullName.EndsWith(".xml", StringComparison.Ordinal))
|
||||
.OrderBy(e => e.FullName, StringComparer.Ordinal).FirstOrDefault();
|
||||
if (sheet is null)
|
||||
{
|
||||
return new FilePreview(AttachmentPreview.Xlsx, null, null, false);
|
||||
}
|
||||
|
||||
var rows = Sheet(sheet, shared, culture, out var truncated);
|
||||
return new FilePreview(AttachmentPreview.Xlsx, null, rows, truncated);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (copy is not null)
|
||||
{
|
||||
await copy.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static XmlReader Reader(ZipArchiveEntry entry) =>
|
||||
XmlReader.Create(entry.Open(), new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null, IgnoreWhitespace = false, CloseInput = true });
|
||||
|
||||
private static List<string> SharedStrings(ZipArchiveEntry entry)
|
||||
{
|
||||
var strings = new List<string>();
|
||||
using var reader = Reader(entry);
|
||||
StringBuilder? current = null;
|
||||
while (reader.Read())
|
||||
{
|
||||
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "si")
|
||||
{
|
||||
current = new StringBuilder();
|
||||
if (reader.IsEmptyElement)
|
||||
{
|
||||
strings.Add(string.Empty);
|
||||
current = null;
|
||||
}
|
||||
}
|
||||
else if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "t" && current is not null)
|
||||
{
|
||||
current.Append(reader.ReadElementContentAsString());
|
||||
}
|
||||
else if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "si" && current is not null)
|
||||
{
|
||||
strings.Add(current.ToString());
|
||||
current = null;
|
||||
}
|
||||
}
|
||||
|
||||
return strings;
|
||||
}
|
||||
|
||||
private static List<IReadOnlyList<string>> Sheet(ZipArchiveEntry entry, List<string> shared, CultureInfo culture, out bool truncated)
|
||||
{
|
||||
var rows = new List<IReadOnlyList<string>>();
|
||||
truncated = false;
|
||||
using var reader = Reader(entry);
|
||||
List<string>? row = null;
|
||||
while (reader.Read())
|
||||
{
|
||||
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "row")
|
||||
{
|
||||
if (rows.Count == MaxRows)
|
||||
{
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
|
||||
// Empty rows in between keep their place.
|
||||
if (int.TryParse(reader.GetAttribute("r"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var number))
|
||||
{
|
||||
while (rows.Count < Math.Min(number - 1, MaxRows))
|
||||
{
|
||||
rows.Add([]);
|
||||
}
|
||||
}
|
||||
|
||||
row = [];
|
||||
if (reader.IsEmptyElement)
|
||||
{
|
||||
rows.Add(row);
|
||||
row = null;
|
||||
}
|
||||
}
|
||||
else if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "c" && row is not null)
|
||||
{
|
||||
var column = Column(reader.GetAttribute("r")) ?? row.Count;
|
||||
var type = reader.GetAttribute("t");
|
||||
var value = reader.IsEmptyElement ? string.Empty : Cell(reader, type, shared, culture);
|
||||
if (column < MaxColumns)
|
||||
{
|
||||
while (row.Count < column)
|
||||
{
|
||||
row.Add(string.Empty);
|
||||
}
|
||||
|
||||
row.Add(value);
|
||||
}
|
||||
}
|
||||
else if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "row" && row is not null)
|
||||
{
|
||||
rows.Add(row);
|
||||
row = null;
|
||||
}
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
// Reads the content of a <c> element, leaving the reader on its end.
|
||||
private static string Cell(XmlReader reader, string? type, List<string> shared, CultureInfo culture)
|
||||
{
|
||||
var depth = reader.Depth;
|
||||
var text = new StringBuilder();
|
||||
string? value = null;
|
||||
while (reader.Read() && !(reader.NodeType == XmlNodeType.EndElement && reader.Depth == depth))
|
||||
{
|
||||
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "v")
|
||||
{
|
||||
value = reader.ReadElementContentAsString();
|
||||
if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == depth)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
else if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "t")
|
||||
{
|
||||
text.Append(reader.ReadElementContentAsString());
|
||||
if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == depth)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return type switch
|
||||
{
|
||||
"s" => int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var index) && index >= 0 && index < shared.Count ? shared[index] : string.Empty,
|
||||
"inlineStr" => text.ToString(),
|
||||
"b" or "str" or "e" => value ?? string.Empty,
|
||||
_ => decimal.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var number) ? number.ToString("G", culture) : value ?? string.Empty,
|
||||
};
|
||||
}
|
||||
|
||||
// "BC12" -> 54 (zero-based column).
|
||||
private static int? Column(string? reference)
|
||||
{
|
||||
if (string.IsNullOrEmpty(reference))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var column = 0;
|
||||
var letters = 0;
|
||||
foreach (var c in reference)
|
||||
{
|
||||
if (c is >= 'A' and <= 'Z')
|
||||
{
|
||||
column = (column * 26) + (c - 'A' + 1);
|
||||
letters++;
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return letters is 0 or > 3 ? null : column - 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
using System.Text;
|
||||
|
||||
namespace Khaemhat.Application.Files;
|
||||
|
||||
/// <summary>How the interface can show a file in the preview (SPEC §9.4: PDF, images, XML, CSV/XLSX).</summary>
|
||||
public enum AttachmentPreview
|
||||
{
|
||||
/// <summary>No preview: the file can only be downloaded.</summary>
|
||||
None = 0,
|
||||
|
||||
/// <summary>The integrated PDF viewer.</summary>
|
||||
Pdf = 1,
|
||||
|
||||
/// <summary>An image, at full size with zoom.</summary>
|
||||
Image = 2,
|
||||
|
||||
/// <summary>XML, formatted and indented.</summary>
|
||||
Xml = 3,
|
||||
|
||||
/// <summary>CSV, as a grid.</summary>
|
||||
Csv = 4,
|
||||
|
||||
/// <summary>XLSX, as a grid.</summary>
|
||||
Xlsx = 5,
|
||||
|
||||
/// <summary>Plain text.</summary>
|
||||
Text = 6,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Media types and file names of attachments. The media type is taken from the extension when it is known (the type
|
||||
/// declared by a browser is not trusted), and file names are cleaned so they are safe on every file system and in a
|
||||
/// ZIP.
|
||||
/// </summary>
|
||||
public static class MediaTypes
|
||||
{
|
||||
/// <summary>The type of unknown content.</summary>
|
||||
public const string OctetStream = "application/octet-stream";
|
||||
|
||||
/// <summary>PDF.</summary>
|
||||
public const string Pdf = "application/pdf";
|
||||
|
||||
/// <summary>CSV.</summary>
|
||||
public const string Csv = "text/csv";
|
||||
|
||||
/// <summary>XLSX.</summary>
|
||||
public const string Xlsx = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
|
||||
|
||||
/// <summary>ZIP.</summary>
|
||||
public const string Zip = "application/zip";
|
||||
|
||||
/// <summary>XML.</summary>
|
||||
public const string Xml = "application/xml";
|
||||
|
||||
/// <summary>The longest file name kept.</summary>
|
||||
public const int MaxFileNameLength = 255;
|
||||
|
||||
private static readonly Dictionary<string, string> ByExtension = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
[".pdf"] = Pdf,
|
||||
[".xml"] = Xml,
|
||||
[".p7m"] = "application/pkcs7-mime",
|
||||
[".csv"] = Csv,
|
||||
[".txt"] = "text/plain",
|
||||
[".json"] = "application/json",
|
||||
[".xlsx"] = Xlsx,
|
||||
[".xls"] = "application/vnd.ms-excel",
|
||||
[".ods"] = "application/vnd.oasis.opendocument.spreadsheet",
|
||||
[".docx"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
[".doc"] = "application/msword",
|
||||
[".odt"] = "application/vnd.oasis.opendocument.text",
|
||||
[".zip"] = Zip,
|
||||
[".jpg"] = "image/jpeg",
|
||||
[".jpeg"] = "image/jpeg",
|
||||
[".png"] = "image/png",
|
||||
[".gif"] = "image/gif",
|
||||
[".webp"] = "image/webp",
|
||||
[".tif"] = "image/tiff",
|
||||
[".tiff"] = "image/tiff",
|
||||
[".eml"] = "message/rfc822",
|
||||
};
|
||||
|
||||
/// <summary>The media type of a file: from its extension when known, else the declared type when well formed.</summary>
|
||||
/// <param name="fileName">The file name.</param>
|
||||
/// <param name="declared">The type declared by the client, if any.</param>
|
||||
/// <returns>The media type.</returns>
|
||||
public static string Resolve(string fileName, string? declared = null)
|
||||
{
|
||||
if (ByExtension.TryGetValue(Path.GetExtension(fileName ?? string.Empty), out var known))
|
||||
{
|
||||
return known;
|
||||
}
|
||||
|
||||
return IsWellFormed(declared) ? declared!.Trim().ToLowerInvariant() : OctetStream;
|
||||
}
|
||||
|
||||
/// <summary>How a file can be previewed.</summary>
|
||||
/// <param name="mime">The media type.</param>
|
||||
/// <returns>The preview.</returns>
|
||||
public static AttachmentPreview PreviewOf(string? mime) => mime switch
|
||||
{
|
||||
Pdf => AttachmentPreview.Pdf,
|
||||
"image/jpeg" or "image/png" or "image/gif" or "image/webp" => AttachmentPreview.Image,
|
||||
Xml or "text/xml" => AttachmentPreview.Xml,
|
||||
Csv => AttachmentPreview.Csv,
|
||||
Xlsx => AttachmentPreview.Xlsx,
|
||||
"text/plain" or "application/json" => AttachmentPreview.Text,
|
||||
_ => AttachmentPreview.None,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Cleans a file name: no folders, no control characters or characters Windows refuses, at most 255 characters
|
||||
/// keeping the extension; <c>file</c> when nothing is left.
|
||||
/// </summary>
|
||||
/// <param name="fileName">The name as received.</param>
|
||||
/// <returns>The clean name.</returns>
|
||||
public static string CleanFileName(string? fileName)
|
||||
{
|
||||
var name = (fileName ?? string.Empty).Replace('\\', '/');
|
||||
name = name[(name.LastIndexOf('/') + 1)..];
|
||||
var builder = new StringBuilder(name.Length);
|
||||
foreach (var c in name)
|
||||
{
|
||||
builder.Append(char.IsControl(c) || c is ':' or '*' or '?' or '"' or '<' or '>' or '|' ? '_' : c);
|
||||
}
|
||||
|
||||
var clean = builder.ToString().Trim().TrimEnd('.').Trim();
|
||||
if (clean.Length > MaxFileNameLength)
|
||||
{
|
||||
var extension = Path.GetExtension(clean);
|
||||
extension = extension.Length > 20 ? string.Empty : extension;
|
||||
clean = clean[..(MaxFileNameLength - extension.Length)] + extension;
|
||||
}
|
||||
|
||||
return clean.Length == 0 || clean is "." or ".." ? "file" : clean;
|
||||
}
|
||||
|
||||
/// <summary>The download name of a version: <c>name.pdf</c> for v1, <c>name_v2.pdf</c> after.</summary>
|
||||
/// <param name="name">The attachment name.</param>
|
||||
/// <param name="version">The version.</param>
|
||||
/// <returns>The file name.</returns>
|
||||
public static string VersionedFileName(string name, int version)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(name);
|
||||
if (version <= 1)
|
||||
{
|
||||
return name;
|
||||
}
|
||||
|
||||
var extension = Path.GetExtension(name);
|
||||
return name[..^extension.Length] + "_v" + version.ToString(System.Globalization.CultureInfo.InvariantCulture) + extension;
|
||||
}
|
||||
|
||||
private static bool IsWellFormed(string? mime) =>
|
||||
mime is { Length: > 2 and <= 150 } && mime.Count(c => c == '/') == 1
|
||||
&& mime.Trim().All(c => char.IsAsciiLetterOrDigit(c) || c is '/' or '.' or '+' or '-');
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
using Khaemhat.Application.Modules;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Accounting;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.ImportExport;
|
||||
|
||||
/// <summary>An account of the chart read from a file.</summary>
|
||||
/// <param name="Code">The code, parts separated by points (<c>01.02.003</c>).</param>
|
||||
/// <param name="Description">The description.</param>
|
||||
/// <param name="Level">The level, 1 to 3: the number of parts of the code.</param>
|
||||
/// <param name="ParentCode">The code without its last part.</param>
|
||||
/// <param name="Nature">The nature.</param>
|
||||
/// <param name="Type">The use.</param>
|
||||
/// <param name="Postable">Postings go on it (only leaves).</param>
|
||||
/// <param name="VatRelevant">Relevant for VAT.</param>
|
||||
/// <param name="SubLedger">With a sub-ledger of customers or suppliers.</param>
|
||||
/// <param name="ClosesAutomatically">Closed by the year end.</param>
|
||||
/// <param name="Disabled">Not used any more.</param>
|
||||
public sealed record ImportedAccount(
|
||||
string Code, string Description, int Level, string? ParentCode, AccountNature Nature, AccountType Type, bool Postable, bool VatRelevant, bool SubLedger,
|
||||
bool ClosesAutomatically, bool Disabled);
|
||||
|
||||
/// <summary>
|
||||
/// The checks of a chart of accounts from a file (SPEC §12.12, ADR 0031): codes of one to three parts separated by
|
||||
/// points, each account under the account whose code is its own without the last part, with the same nature; only
|
||||
/// leaves are postable. Pure, so that M7 writes what this checks.
|
||||
/// </summary>
|
||||
public static class ChartOfAccountsImportValidator
|
||||
{
|
||||
/// <summary>The words of <c>natura</c>, in the order of <see cref="AccountNature"/>.</summary>
|
||||
public static readonly IReadOnlyList<string> NatureWords = ["attivo", "passivo", "costo", "ricavo", "ordine"];
|
||||
|
||||
/// <summary>The words of <c>tipo</c>, in the order of <see cref="AccountType"/>.</summary>
|
||||
public static readonly IReadOnlyList<string> TypeWords = ["generico", "clienti", "fornitori", "banca", "cassa", "iva", "erario"];
|
||||
|
||||
/// <summary>The flag letters: postable, VAT relevant, sub-ledger, automatic closing, disabled.</summary>
|
||||
public const string FlagLetters = "MIPCX";
|
||||
|
||||
/// <summary>The deepest level.</summary>
|
||||
public const int MaxLevel = 3;
|
||||
|
||||
/// <summary>The columns of the chart.</summary>
|
||||
public static IReadOnlyList<ImportField> Fields { get; } =
|
||||
[
|
||||
new("codice", ImportFieldKind.Code, Required: true, Aliases: ["conto", "codice_conto", "cod_conto"]),
|
||||
new("descrizione", Required: true, Aliases: ["descr", "denominazione"]),
|
||||
new("livello", ImportFieldKind.Number, Aliases: ["liv"]),
|
||||
new("padre", ImportFieldKind.Code, Aliases: ["conto_padre", "mastro"]),
|
||||
new("natura", ImportFieldKind.Choice, Aliases: ["sezione"], Choices: NatureWords),
|
||||
new("tipo", ImportFieldKind.Choice, Aliases: ["tipo_conto"], Choices: TypeWords),
|
||||
new("voce_cee", Aliases: ["cee", "voce_bilancio"]),
|
||||
new("riclassifica", Aliases: ["riclassificazione"]),
|
||||
new("flag", Aliases: ["flags", "attributi"]),
|
||||
];
|
||||
|
||||
/// <summary>Checks the rows of a chart.</summary>
|
||||
/// <param name="rows">The rows.</param>
|
||||
/// <returns>A result per row, and the accounts without errors.</returns>
|
||||
public static (IReadOnlyList<ImportRowResult> Results, IReadOnlyList<ImportedAccount> Accounts) Check(IReadOnlyList<ImportRow> rows)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(rows);
|
||||
|
||||
// First pass: every code with its nature as written, to check parents wherever they are in the file.
|
||||
var natures = new Dictionary<string, AccountNature?>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var row in rows)
|
||||
{
|
||||
if (row["codice"] is { } code)
|
||||
{
|
||||
natures.TryAdd(code, Choice(row["natura"], NatureWords) is { } n ? (AccountNature)n : null);
|
||||
}
|
||||
}
|
||||
|
||||
var parents = natures.Keys.Select(ParentOf).Where(p => p is not null).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var results = new List<ImportRowResult>(rows.Count);
|
||||
var accounts = new List<ImportedAccount>();
|
||||
foreach (var row in rows)
|
||||
{
|
||||
var messages = new List<ImportMessage>();
|
||||
var cells = new CellReader(row, messages);
|
||||
var code = row["codice"];
|
||||
messages.AddRange(Fields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required)));
|
||||
if (code is null)
|
||||
{
|
||||
results.Add(new(row.Line, row["descrizione"] ?? string.Empty, ImportAction.Skip, messages));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!seen.Add(code))
|
||||
{
|
||||
results.Add(new(row.Line, code, ImportAction.Skip, [new("codice", ImportErrors.CodeRepeated, Value: code)]));
|
||||
continue;
|
||||
}
|
||||
|
||||
var parts = code.Split('.');
|
||||
var level = parts.Length;
|
||||
if (level > MaxLevel || parts.Any(p => p.Length == 0 || !p.All(char.IsAsciiLetterOrDigit)))
|
||||
{
|
||||
messages.Add(new("codice", ImportErrors.AccountLevel, Value: code));
|
||||
}
|
||||
else if (cells.Number("livello") is { } written && written != level)
|
||||
{
|
||||
messages.Add(new("livello", ImportErrors.AccountLevel, Value: level.ToString(System.Globalization.CultureInfo.InvariantCulture)));
|
||||
}
|
||||
|
||||
var parent = ParentOf(code);
|
||||
if (row["padre"] is { } named && !string.Equals(named, parent, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
messages.Add(new("padre", ImportErrors.AccountParent, Value: parent ?? string.Empty));
|
||||
}
|
||||
else if (parent is not null && !natures.ContainsKey(parent))
|
||||
{
|
||||
messages.Add(new("padre", ImportErrors.AccountParent, Value: parent));
|
||||
}
|
||||
|
||||
var nature = NatureOf(code, natures);
|
||||
if (nature is null)
|
||||
{
|
||||
messages.Add(new("natura", cells.Has("natura") ? ImportErrors.Choice : ImportErrors.Required, Value: cells.Has("natura") ? string.Join(", ", NatureWords) : null));
|
||||
}
|
||||
else if (parent is not null && natures.ContainsKey(parent) && NatureOf(parent, natures) is { } parentNature && parentNature != nature)
|
||||
{
|
||||
messages.Add(new("natura", ImportErrors.AccountNature, Value: NatureWords[(int)parentNature]));
|
||||
}
|
||||
|
||||
var type = cells.Choice(Fields[5]) is { } t ? (AccountType)t : AccountType.Generic;
|
||||
var flags = (row["flag"] ?? string.Empty).ToUpperInvariant().Where(c => !char.IsWhiteSpace(c) && c is not ',' and not ';').ToList();
|
||||
if (flags.FirstOrDefault(c => !FlagLetters.Contains(c, StringComparison.Ordinal)) is var bad && bad != default)
|
||||
{
|
||||
messages.Add(new("flag", ImportErrors.AccountFlag, Value: bad.ToString()));
|
||||
}
|
||||
|
||||
var postable = flags.Contains('M');
|
||||
var leaf = !parents.Contains(code);
|
||||
if (postable && !leaf)
|
||||
{
|
||||
messages.Add(new("flag", ImportErrors.AccountPostable));
|
||||
}
|
||||
else if (!postable && leaf && level > 1)
|
||||
{
|
||||
messages.Add(new("flag", ImportErrors.AccountLeaf, IsWarning: true));
|
||||
}
|
||||
|
||||
if (messages.All(m => m.IsWarning) && nature is { } valid)
|
||||
{
|
||||
accounts.Add(new(code, row["descrizione"] ?? string.Empty, level, parent, valid, type, postable, flags.Contains('I'), flags.Contains('P'), flags.Contains('C'),
|
||||
flags.Contains('X')));
|
||||
}
|
||||
|
||||
results.Add(new(row.Line, code, messages.Any(m => !m.IsWarning) ? ImportAction.Skip : ImportAction.Create, messages));
|
||||
}
|
||||
|
||||
return (results, accounts);
|
||||
}
|
||||
|
||||
/// <summary>The code without its last part, or <see langword="null"/> for a first level account.</summary>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <returns>The parent code.</returns>
|
||||
public static string? ParentOf(string code)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(code);
|
||||
var point = code.LastIndexOf('.');
|
||||
return point <= 0 ? null : code[..point];
|
||||
}
|
||||
|
||||
// The nature written on the account, else the one of the nearest ancestor that has one.
|
||||
private static AccountNature? NatureOf(string code, Dictionary<string, AccountNature?> natures)
|
||||
{
|
||||
for (var current = code; current is not null; current = ParentOf(current))
|
||||
{
|
||||
if (natures.TryGetValue(current, out var nature) && nature is not null)
|
||||
{
|
||||
return nature;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static int? Choice(string? text, IReadOnlyList<string> words) => text is null ? null : ImportValues.Choice(text, words) is var i and >= 0 ? i : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The chart of accounts (<c>piano-dei-conti</c>): CSV, XLSX or <c>khaemhat-coa.json</c>. Until the ledger exists (M7)
|
||||
/// the file is only checked; M7 writes the accounts this check accepts.
|
||||
/// </summary>
|
||||
/// <param name="permissions">Checks the permission.</param>
|
||||
public sealed class ChartOfAccountsImportTarget(PermissionService permissions) : IImportTarget
|
||||
{
|
||||
/// <summary>The permission to change the chart of accounts.</summary>
|
||||
public const string WritePermission = "ledger.account.write";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Key => "piano-dei-conti";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ModuleCode => ModuleCodes.Accounting;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Permission => WritePermission;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ExportPermission => "ledger.account.read";
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanApply => false;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanExport => false;
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<ImportField> Fields => ChartOfAccountsImportValidator.Fields;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
|
||||
return ChartOfAccountsImportValidator.Check(rows).Results;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
|
||||
throw new InvalidOperationException(ImportErrors.CheckOnly);
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken) =>
|
||||
Task.FromResult<IReadOnlyList<IReadOnlyList<object?>>>([]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The opening stock (<c>giacenze-iniziali</c>): item, warehouse, quantity and unit cost. Until the stock entries exist
|
||||
/// (M6) the file is only checked; M6 writes the opening entry from the rows this check accepts.
|
||||
/// </summary>
|
||||
/// <param name="factory">Opens the company databases.</param>
|
||||
/// <param name="permissions">Checks the permission.</param>
|
||||
public sealed class OpeningStockImportTarget(IUnitOfWorkFactory factory, PermissionService permissions) : IImportTarget
|
||||
{
|
||||
private static readonly ImportField[] StockFields =
|
||||
[
|
||||
new("articolo", ImportFieldKind.Code, Required: true, Aliases: ["codice_articolo", "codice", "cod_articolo", "sku"]),
|
||||
new("deposito", ImportFieldKind.Code, Aliases: ["magazzino", "codice_magazzino"]),
|
||||
new("quantita", ImportFieldKind.Number, Required: true, Aliases: ["qta", "qty", "giacenza", "esistenza"]),
|
||||
new("costo_unitario", ImportFieldKind.Number, Aliases: ["costo", "valore_unitario", "prezzo_acquisto"]),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Key => "giacenze-iniziali";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ModuleCode => ModuleCodes.Core;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Permission => "inventory.entry.write";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ExportPermission => "inventory.stock.read";
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanApply => false;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanExport => false;
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<ImportField> Fields => StockFields;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
ArgumentNullException.ThrowIfNull(rows);
|
||||
var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var items = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>(), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var codes = new CodeIndex(items.Select(i => (i.Code, i.Id)));
|
||||
var byId = items.ToDictionary(i => i.Id);
|
||||
var warehouses = await CodeIndex.LoadAsync<Warehouse>(uow, cancellationToken).ConfigureAwait(false);
|
||||
var seen = new HashSet<(long, long)>();
|
||||
var results = new List<ImportRowResult>(rows.Count);
|
||||
foreach (var row in rows)
|
||||
{
|
||||
var messages = new List<ImportMessage>();
|
||||
var cells = new CellReader(row, messages);
|
||||
messages.AddRange(StockFields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required)));
|
||||
var item = cells.Code("articolo", codes) is { } id ? byId[id] : null;
|
||||
var warehouse = cells.Code("deposito", warehouses) ?? (cells.Has("deposito") ? null : item?.WarehouseId);
|
||||
if (item is not null && (item.Kind != ItemKind.Goods || !item.Stocked))
|
||||
{
|
||||
messages.Add(new("articolo", ImportErrors.NotStocked, Value: item.Code));
|
||||
}
|
||||
|
||||
if (item is not null && warehouse is null && !cells.Has("deposito"))
|
||||
{
|
||||
messages.Add(new("deposito", ImportErrors.Required));
|
||||
}
|
||||
|
||||
if (cells.Number("quantita") is <= 0)
|
||||
{
|
||||
messages.Add(new("quantita", ImportErrors.Positive));
|
||||
}
|
||||
|
||||
if (cells.Number("costo_unitario") is < 0)
|
||||
{
|
||||
messages.Add(new("costo_unitario", Items.ItemService.NotNegative));
|
||||
}
|
||||
|
||||
var label = row["articolo"] ?? string.Empty;
|
||||
if (item is not null && warehouse is { } w && !seen.Add((item.Id, w)))
|
||||
{
|
||||
messages.Add(new("articolo", ImportErrors.CodeRepeated, Value: label));
|
||||
}
|
||||
|
||||
results.Add(new(row.Line, label, messages.Any(m => !m.IsWarning) ? ImportAction.Skip : ImportAction.Create, messages));
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
|
||||
throw new InvalidOperationException(ImportErrors.CheckOnly);
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken) =>
|
||||
Task.FromResult<IReadOnlyList<IReadOnlyList<object?>>>([]);
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Khaemhat.Infrastructure.Files;
|
||||
|
||||
namespace Khaemhat.Application.ImportExport;
|
||||
|
||||
/// <summary>A file the import cannot use; <see cref="Code"/> is one of the <c>import.file.*</c> codes.</summary>
|
||||
public sealed class ImportFileException : Exception
|
||||
{
|
||||
/// <summary>Creates the exception.</summary>
|
||||
public ImportFileException()
|
||||
{
|
||||
Code = ImportErrors.FileUnreadable;
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="message">What went wrong.</param>
|
||||
public ImportFileException(string message)
|
||||
: base(message)
|
||||
{
|
||||
Code = ImportErrors.FileUnreadable;
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="message">What went wrong.</param>
|
||||
/// <param name="innerException">The cause.</param>
|
||||
public ImportFileException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
Code = ImportErrors.FileUnreadable;
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception with a code.</summary>
|
||||
/// <param name="code">The text code.</param>
|
||||
/// <param name="message">What went wrong.</param>
|
||||
/// <param name="innerException">The cause.</param>
|
||||
public ImportFileException(string code, string message, Exception? innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
Code = code;
|
||||
}
|
||||
|
||||
/// <summary>The text code.</summary>
|
||||
public string Code { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the files of the guided import (SPEC §12.12): CSV (UTF-8 with or without byte order mark, else Windows-1252;
|
||||
/// separator <c>;</c>, <c>,</c> or tab guessed from the header), XLSX (first sheet) and JSON (an array of objects, or the
|
||||
/// object of <c>khaemhat-coa.json</c> with its <c>accounts</c>). The first row holds the headers.
|
||||
/// </summary>
|
||||
public static class ImportFileReader
|
||||
{
|
||||
/// <summary>The most data rows an import takes.</summary>
|
||||
public const int MaxRows = 50_000;
|
||||
|
||||
/// <summary>The format name written in <c>khaemhat-coa.json</c>.</summary>
|
||||
public const string ChartFormat = "khaemhat-coa";
|
||||
|
||||
private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
|
||||
|
||||
/// <summary>The format of a file from its name.</summary>
|
||||
/// <param name="fileName">The name.</param>
|
||||
/// <returns>The format, or <see langword="null"/> when not supported.</returns>
|
||||
public static TransferFormat? FormatOf(string? fileName) => Path.GetExtension(fileName ?? string.Empty).ToUpperInvariant() switch
|
||||
{
|
||||
".CSV" or ".TXT" => TransferFormat.Csv,
|
||||
".XLSX" => TransferFormat.Xlsx,
|
||||
".JSON" => TransferFormat.Json,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary>Reads a file.</summary>
|
||||
/// <param name="fileName">The name, which gives the format.</param>
|
||||
/// <param name="content">The content.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The file with headers and rows.</returns>
|
||||
/// <exception cref="ImportFileException">The format is not supported, or the file is empty, damaged or too large.</exception>
|
||||
public static async Task<ImportFile> ReadAsync(string fileName, Stream content, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(fileName);
|
||||
ArgumentNullException.ThrowIfNull(content);
|
||||
var format = FormatOf(fileName) ?? throw new ImportFileException(ImportErrors.FileFormat, "Not CSV, XLSX or JSON: " + fileName, null);
|
||||
using var buffer = new MemoryStream();
|
||||
await content.CopyToAsync(buffer, cancellationToken).ConfigureAwait(false);
|
||||
buffer.Position = 0;
|
||||
return format switch
|
||||
{
|
||||
TransferFormat.Xlsx => await ReadXlsxAsync(fileName, buffer, cancellationToken).ConfigureAwait(false),
|
||||
TransferFormat.Json => ReadJson(fileName, buffer.ToArray()),
|
||||
_ => ReadCsv(fileName, buffer.ToArray()),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Reads CSV bytes.</summary>
|
||||
/// <param name="fileName">The name.</param>
|
||||
/// <param name="bytes">The content.</param>
|
||||
/// <returns>The file.</returns>
|
||||
/// <exception cref="ImportFileException">Empty or too large.</exception>
|
||||
public static ImportFile ReadCsv(string fileName, byte[] bytes)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(bytes);
|
||||
string text;
|
||||
string encoding;
|
||||
var start = bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF ? 3 : 0;
|
||||
try
|
||||
{
|
||||
text = StrictUtf8.GetString(bytes, start, bytes.Length - start);
|
||||
encoding = "UTF-8";
|
||||
}
|
||||
catch (DecoderFallbackException)
|
||||
{
|
||||
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
|
||||
text = Encoding.GetEncoding(1252).GetString(bytes);
|
||||
encoding = "Windows-1252";
|
||||
}
|
||||
|
||||
var separator = Guess(text);
|
||||
var lines = CsvReader.Parse(text, separator);
|
||||
return Build(fileName, TransferFormat.Csv, encoding, separator, lines, null);
|
||||
}
|
||||
|
||||
private static async Task<ImportFile> ReadXlsxAsync(string fileName, Stream content, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var rows = await XlsxReader.ReadAsync(content, cancellationToken).ConfigureAwait(false);
|
||||
return Build(fileName, TransferFormat.Xlsx, null, null, rows, null);
|
||||
}
|
||||
catch (XlsxReadException ex)
|
||||
{
|
||||
throw new ImportFileException(ImportErrors.FileUnreadable, ex.Message, ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static ImportFile ReadJson(string fileName, byte[] bytes)
|
||||
{
|
||||
JsonDocument document;
|
||||
try
|
||||
{
|
||||
document = JsonDocument.Parse(bytes, new JsonDocumentOptions { MaxDepth = 16, AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
throw new ImportFileException(ImportErrors.FileUnreadable, ex.Message, ex);
|
||||
}
|
||||
|
||||
using (document)
|
||||
{
|
||||
var root = document.RootElement;
|
||||
Dictionary<string, int>? sections = null;
|
||||
JsonElement records;
|
||||
if (root.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
records = root;
|
||||
}
|
||||
else if (root.ValueKind == JsonValueKind.Object && root.TryGetProperty("accounts", out var accounts) && accounts.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
records = accounts;
|
||||
sections = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
foreach (var property in root.EnumerateObject())
|
||||
{
|
||||
if (property.Name != "accounts" && property.Value.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
sections[property.Name] = property.Value.GetArrayLength();
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new ImportFileException(ImportErrors.FileUnreadable, "Neither an array of objects nor a chart of accounts.", null);
|
||||
}
|
||||
|
||||
var headers = new List<string>();
|
||||
var index = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
var objects = new List<Dictionary<string, string>>();
|
||||
foreach (var element in records.EnumerateArray())
|
||||
{
|
||||
if (element.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
throw new ImportFileException(ImportErrors.FileUnreadable, "An entry is not an object.", null);
|
||||
}
|
||||
|
||||
var values = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
if (index.TryAdd(property.Name, headers.Count))
|
||||
{
|
||||
headers.Add(property.Name);
|
||||
}
|
||||
|
||||
values[property.Name] = Cell(property.Value);
|
||||
}
|
||||
|
||||
objects.Add(values);
|
||||
}
|
||||
|
||||
var rows = new List<IReadOnlyList<string>> { headers };
|
||||
rows.AddRange(objects.Select(o => (IReadOnlyList<string>)[.. headers.Select(h => o.GetValueOrDefault(h, string.Empty))]));
|
||||
return Build(fileName, TransferFormat.Json, "UTF-8", null, rows, sections);
|
||||
}
|
||||
}
|
||||
|
||||
private static string Cell(JsonElement value) => value.ValueKind switch
|
||||
{
|
||||
JsonValueKind.String => value.GetString() ?? string.Empty,
|
||||
JsonValueKind.Number => value.GetRawText(),
|
||||
JsonValueKind.True => "true",
|
||||
JsonValueKind.False => "false",
|
||||
JsonValueKind.Null or JsonValueKind.Undefined => string.Empty,
|
||||
_ => value.GetRawText(),
|
||||
};
|
||||
|
||||
private static ImportFile Build(string fileName, TransferFormat format, string? encoding, char? separator, IReadOnlyList<IReadOnlyList<string>> lines,
|
||||
IReadOnlyDictionary<string, int>? sections)
|
||||
{
|
||||
if (lines.Count == 0 || lines[0].All(string.IsNullOrWhiteSpace))
|
||||
{
|
||||
throw new ImportFileException(ImportErrors.FileEmpty, "No header.", null);
|
||||
}
|
||||
|
||||
if (lines.Count - 1 > MaxRows)
|
||||
{
|
||||
throw new ImportFileException(ImportErrors.FileTooLarge, "More than " + MaxRows.ToString(CultureInfo.InvariantCulture) + " rows.", null);
|
||||
}
|
||||
|
||||
var headers = lines[0].Select((h, i) => string.IsNullOrWhiteSpace(h) ? "colonna_" + (i + 1).ToString(CultureInfo.InvariantCulture) : h.Trim()).ToList();
|
||||
var rows = new List<IReadOnlyList<string>>(lines.Count - 1);
|
||||
foreach (var line in lines.Skip(1))
|
||||
{
|
||||
if (line.All(string.IsNullOrWhiteSpace))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
rows.Add([.. Enumerable.Range(0, headers.Count).Select(i => i < line.Count ? Unprotect(line[i]) : string.Empty)]);
|
||||
}
|
||||
|
||||
return new ImportFile(Path.GetFileName(fileName), format, encoding, separator, headers, rows, sections);
|
||||
}
|
||||
|
||||
// The apostrophe the export puts before text that a spreadsheet would read as a formula (CsvWriter).
|
||||
private static string Unprotect(string cell) =>
|
||||
cell.Length > 1 && cell[0] == '\'' && cell[1] is '=' or '+' or '-' or '@' ? cell[1..].Trim() : cell.Trim();
|
||||
|
||||
private static char Guess(string text)
|
||||
{
|
||||
var end = text.IndexOfAny(['\r', '\n']);
|
||||
var first = end < 0 ? text : text[..end];
|
||||
return Separators.OrderByDescending(s => first.Count(c => c == s)).First();
|
||||
}
|
||||
|
||||
private static readonly char[] Separators = [';', ',', '\t'];
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
using Khaemhat.Application.Security;
|
||||
|
||||
namespace Khaemhat.Application.ImportExport;
|
||||
|
||||
/// <summary>The formats of the guided import and export (SPEC §12.12).</summary>
|
||||
public enum TransferFormat
|
||||
{
|
||||
/// <summary>Text with <c>;</c>, UTF-8 (other separators and Windows-1252 are recognized when reading).</summary>
|
||||
Csv = 0,
|
||||
|
||||
/// <summary>Excel workbook, first sheet, headers in the first row.</summary>
|
||||
Xlsx = 1,
|
||||
|
||||
/// <summary>JSON: an array of objects keyed by column, or the object of <c>khaemhat-coa.json</c>.</summary>
|
||||
Json = 2,
|
||||
}
|
||||
|
||||
/// <summary>The kind of value of a column, for reading and writing it.</summary>
|
||||
public enum ImportFieldKind
|
||||
{
|
||||
/// <summary>Free text.</summary>
|
||||
Text = 0,
|
||||
|
||||
/// <summary>A code of another archive or table.</summary>
|
||||
Code = 1,
|
||||
|
||||
/// <summary>A decimal number (Italian or invariant notation).</summary>
|
||||
Number = 2,
|
||||
|
||||
/// <summary>A date (<c>dd/MM/yyyy</c>, ISO or a spreadsheet serial).</summary>
|
||||
Date = 3,
|
||||
|
||||
/// <summary>Yes or no.</summary>
|
||||
Boolean = 4,
|
||||
|
||||
/// <summary>One of a list of words.</summary>
|
||||
Choice = 5,
|
||||
}
|
||||
|
||||
/// <summary>A column an entity accepts.</summary>
|
||||
/// <param name="Key">The column name used in files and templates (<c>partita_iva</c>).</param>
|
||||
/// <param name="Kind">The kind of value.</param>
|
||||
/// <param name="Required">Whether a new record needs it.</param>
|
||||
/// <param name="Aliases">Other headers recognized by the automatic mapping, already normalized.</param>
|
||||
/// <param name="Choices">The words accepted for <see cref="ImportFieldKind.Choice"/>.</param>
|
||||
public sealed record ImportField(string Key, ImportFieldKind Kind = ImportFieldKind.Text, bool Required = false, IReadOnlyList<string>? Aliases = null,
|
||||
IReadOnlyList<string>? Choices = null);
|
||||
|
||||
/// <summary>A file read for the import.</summary>
|
||||
/// <param name="Name">The file name.</param>
|
||||
/// <param name="Format">The format.</param>
|
||||
/// <param name="Encoding">The text encoding (CSV), such as <c>UTF-8</c>.</param>
|
||||
/// <param name="Separator">The separator (CSV).</param>
|
||||
/// <param name="Headers">The headers of the columns.</param>
|
||||
/// <param name="Rows">The rows under the headers, each as long as the headers.</param>
|
||||
/// <param name="Sections">For <c>khaemhat-coa.json</c>: the other sections with their number of entries.</param>
|
||||
public sealed record ImportFile(string Name, TransferFormat Format, string? Encoding, char? Separator, IReadOnlyList<string> Headers,
|
||||
IReadOnlyList<IReadOnlyList<string>> Rows, IReadOnlyDictionary<string, int>? Sections = null)
|
||||
{
|
||||
/// <summary>The number of data rows.</summary>
|
||||
public int Count => Rows.Count;
|
||||
}
|
||||
|
||||
/// <summary>What happens to a row whose code is already in the archive.</summary>
|
||||
public enum ExistingCodeAction
|
||||
{
|
||||
/// <summary>The record is updated with the non empty cells of the row.</summary>
|
||||
Update = 0,
|
||||
|
||||
/// <summary>The row is skipped.</summary>
|
||||
Skip = 1,
|
||||
}
|
||||
|
||||
/// <summary>What happens to a row without a code.</summary>
|
||||
public enum MissingCodeAction
|
||||
{
|
||||
/// <summary>The code comes from the automatic code rules.</summary>
|
||||
Generate = 0,
|
||||
|
||||
/// <summary>The row is an error.</summary>
|
||||
Refuse = 1,
|
||||
}
|
||||
|
||||
/// <summary>The options of an import (mockup 077, step 1).</summary>
|
||||
public sealed record ImportOptions
|
||||
{
|
||||
/// <summary>Rows whose code exists.</summary>
|
||||
public ExistingCodeAction Existing { get; init; } = ExistingCodeAction.Update;
|
||||
|
||||
/// <summary>Rows without a code.</summary>
|
||||
public MissingCodeAction Missing { get; init; } = MissingCodeAction.Generate;
|
||||
|
||||
/// <summary>Check the VAT numbers of EU parties on VIES while importing.</summary>
|
||||
public bool VerifyVat { get; init; }
|
||||
|
||||
/// <summary>Fill the city from the postal code (and the postal code from the city) when one is missing.</summary>
|
||||
public bool FillFromPostalCode { get; init; } = true;
|
||||
}
|
||||
|
||||
/// <summary>Who imports, where and how: what a target needs besides the rows.</summary>
|
||||
/// <param name="Actor">Who imports.</param>
|
||||
/// <param name="CompanyCode">The company.</param>
|
||||
/// <param name="Options">The options.</param>
|
||||
public sealed record ImportContext(Actor Actor, string CompanyCode, ImportOptions Options);
|
||||
|
||||
/// <summary>A row of the file with the cells of the mapped columns by field key.</summary>
|
||||
/// <param name="Line">The line in the file, counting the header as line 1.</param>
|
||||
/// <param name="Values">The trimmed cells by field key; empty cells are left out.</param>
|
||||
public sealed record ImportRow(int Line, IReadOnlyDictionary<string, string> Values)
|
||||
{
|
||||
/// <summary>The cell of a field, or <see langword="null"/> when empty or not mapped.</summary>
|
||||
/// <param name="key">The field.</param>
|
||||
/// <returns>The text.</returns>
|
||||
public string? this[string key] => Values.TryGetValue(key, out var value) ? value : null;
|
||||
}
|
||||
|
||||
/// <summary>The outcome of a row in the preview (mockup 077: OK, avviso, errore).</summary>
|
||||
public enum ImportOutcome
|
||||
{
|
||||
/// <summary>Importable.</summary>
|
||||
Ok = 0,
|
||||
|
||||
/// <summary>Importable, with a correction proposed or a remark.</summary>
|
||||
Warning = 1,
|
||||
|
||||
/// <summary>Not importable.</summary>
|
||||
Error = 2,
|
||||
}
|
||||
|
||||
/// <summary>What the import does with a row.</summary>
|
||||
public enum ImportAction
|
||||
{
|
||||
/// <summary>A new record.</summary>
|
||||
Create = 0,
|
||||
|
||||
/// <summary>An existing record changes.</summary>
|
||||
Update = 1,
|
||||
|
||||
/// <summary>Nothing (existing code to skip, or an error).</summary>
|
||||
Skip = 2,
|
||||
}
|
||||
|
||||
/// <summary>A remark on a row: a text code with the field it concerns.</summary>
|
||||
/// <param name="Field">The field key, or empty for the whole row.</param>
|
||||
/// <param name="Code">The text code (an error code of the services or <c>import.*</c>).</param>
|
||||
/// <param name="IsWarning">A warning instead of an error.</param>
|
||||
/// <param name="Value">A value to show in the text (<c>{0}</c>), such as the code not found or the city proposed.</param>
|
||||
public sealed record ImportMessage(string Field, string Code, bool IsWarning = false, string? Value = null);
|
||||
|
||||
/// <summary>The check of a row.</summary>
|
||||
/// <param name="Line">The line in the file.</param>
|
||||
/// <param name="Key">The code or description that identifies the row in the preview.</param>
|
||||
/// <param name="Action">What the import will do.</param>
|
||||
/// <param name="Messages">The remarks.</param>
|
||||
public sealed record ImportRowResult(int Line, string Key, ImportAction Action, IReadOnlyList<ImportMessage> Messages)
|
||||
{
|
||||
/// <summary>The outcome from the remarks.</summary>
|
||||
public ImportOutcome Outcome =>
|
||||
Messages.Any(m => !m.IsWarning) ? ImportOutcome.Error : Messages.Count > 0 ? ImportOutcome.Warning : ImportOutcome.Ok;
|
||||
}
|
||||
|
||||
/// <summary>The preview of an import (mockup 077, steps 3 and 4).</summary>
|
||||
/// <param name="Target">The entity.</param>
|
||||
/// <param name="Rows">The checked rows, in file order.</param>
|
||||
/// <param name="CanApply">Whether the entity can be written now (opening stock and chart of accounts only check, until M6 and M7).</param>
|
||||
public sealed record ImportPreview(string Target, IReadOnlyList<ImportRowResult> Rows, bool CanApply)
|
||||
{
|
||||
/// <summary>Rows that will create a record.</summary>
|
||||
public int Creates => Rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Create);
|
||||
|
||||
/// <summary>Rows that will update a record.</summary>
|
||||
public int Updates => Rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Update);
|
||||
|
||||
/// <summary>Rows skipped on purpose.</summary>
|
||||
public int Skips => Rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Skip);
|
||||
|
||||
/// <summary>Rows with errors.</summary>
|
||||
public int Errors => Rows.Count(r => r.Outcome == ImportOutcome.Error);
|
||||
|
||||
/// <summary>Rows with warnings only.</summary>
|
||||
public int Warnings => Rows.Count(r => r.Outcome == ImportOutcome.Warning);
|
||||
|
||||
/// <summary>Rows the import writes.</summary>
|
||||
public int Importable => Creates + Updates;
|
||||
}
|
||||
|
||||
/// <summary>The result of an import.</summary>
|
||||
/// <param name="Target">The entity.</param>
|
||||
/// <param name="Created">Records created.</param>
|
||||
/// <param name="Updated">Records updated.</param>
|
||||
/// <param name="Skipped">Rows skipped on purpose.</param>
|
||||
/// <param name="Rows">Every row with its final outcome; rows refused while writing carry their errors.</param>
|
||||
public sealed record ImportReport(string Target, int Created, int Updated, int Skipped, IReadOnlyList<ImportRowResult> Rows)
|
||||
{
|
||||
/// <summary>Rows not imported because of errors.</summary>
|
||||
public int Failed => Rows.Count(r => r.Outcome == ImportOutcome.Error);
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
using System.Text.Json;
|
||||
using Khaemhat.Application.Licensing;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Logging;
|
||||
using Khaemhat.Infrastructure.Files;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Khaemhat.Application.ImportExport;
|
||||
|
||||
/// <summary>
|
||||
/// The guided import and export (SPEC §11.7, §12.12, mockup 077, ADR 0031): the entities the licence allows, the
|
||||
/// automatic mapping of the columns, the preview that checks every row as if typed in its record, the import of the
|
||||
/// rows without errors, the error report, the export with the same columns and the empty templates.
|
||||
/// </summary>
|
||||
public sealed partial class ImportService
|
||||
{
|
||||
private static readonly JsonWriterOptions JsonOptions = new() { Indented = true };
|
||||
|
||||
private readonly IReadOnlyList<IImportTarget> _targets;
|
||||
private readonly ILicenseGate _license;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly ILogger<ImportService> _logger;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="targets">The entities.</param>
|
||||
/// <param name="license">The licence.</param>
|
||||
/// <param name="permissions">The permissions and the user flags.</param>
|
||||
/// <param name="logger">The log.</param>
|
||||
public ImportService(IEnumerable<IImportTarget> targets, ILicenseGate license, PermissionService permissions, ILogger<ImportService> logger)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(targets);
|
||||
ArgumentNullException.ThrowIfNull(license);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(logger);
|
||||
_targets = [.. targets];
|
||||
_license = license;
|
||||
_permissions = permissions;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>The entities whose module is licensed, in the order of the screen.</summary>
|
||||
public IReadOnlyList<IImportTarget> Targets => [.. _targets.Where(t => _license.IsModuleActive(t.ModuleCode))];
|
||||
|
||||
/// <summary>A licensed entity by key.</summary>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <returns>The entity.</returns>
|
||||
/// <exception cref="ImportFileException">Unknown or not licensed (<see cref="ImportErrors.TargetUnknown"/>).</exception>
|
||||
public IImportTarget Target(string key) =>
|
||||
Targets.FirstOrDefault(t => string.Equals(t.Key, key, StringComparison.OrdinalIgnoreCase))
|
||||
?? throw new ImportFileException(ImportErrors.TargetUnknown, "Unknown import: " + key, null);
|
||||
|
||||
/// <summary>
|
||||
/// The field of each column of a file, by name or alias ignoring case, accents and punctuation; a field goes to one
|
||||
/// column only.
|
||||
/// </summary>
|
||||
/// <param name="target">The entity.</param>
|
||||
/// <param name="headers">The headers.</param>
|
||||
/// <returns>The field key per column, or <see langword="null"/> for columns to ignore.</returns>
|
||||
public static IReadOnlyList<string?> SuggestMapping(IImportTarget target, IReadOnlyList<string> headers)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(target);
|
||||
ArgumentNullException.ThrowIfNull(headers);
|
||||
var taken = new HashSet<string>(StringComparer.Ordinal);
|
||||
var mapping = new string?[headers.Count];
|
||||
for (var pass = 0; pass < 2; pass++)
|
||||
{
|
||||
for (var i = 0; i < headers.Count; i++)
|
||||
{
|
||||
if (mapping[i] is not null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var header = ImportValues.Normalize(headers[i]);
|
||||
var field = target.Fields.FirstOrDefault(f => !taken.Contains(f.Key)
|
||||
&& (pass == 0 ? f.Key == header : (f.Aliases ?? []).Any(a => ImportValues.Normalize(a) == header)));
|
||||
if (field is not null)
|
||||
{
|
||||
mapping[i] = field.Key;
|
||||
taken.Add(field.Key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return mapping;
|
||||
}
|
||||
|
||||
/// <summary>The rows of a file with the cells of the mapped columns.</summary>
|
||||
/// <param name="file">The file.</param>
|
||||
/// <param name="mapping">The field key per column, or <see langword="null"/>.</param>
|
||||
/// <returns>The rows, line numbers counting the header as line 1.</returns>
|
||||
public static IReadOnlyList<ImportRow> Rows(ImportFile file, IReadOnlyList<string?> mapping)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(file);
|
||||
ArgumentNullException.ThrowIfNull(mapping);
|
||||
var rows = new List<ImportRow>(file.Count);
|
||||
for (var r = 0; r < file.Count; r++)
|
||||
{
|
||||
var values = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
var cells = file.Rows[r];
|
||||
for (var c = 0; c < mapping.Count && c < cells.Count; c++)
|
||||
{
|
||||
if (mapping[c] is { } key && !string.IsNullOrWhiteSpace(cells[c]))
|
||||
{
|
||||
values.TryAdd(key, cells[c].Trim());
|
||||
}
|
||||
}
|
||||
|
||||
rows.Add(new ImportRow(r + 2, values));
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
/// <summary>Checks a file without writing (steps 2 and 3 of the screen).</summary>
|
||||
/// <param name="actor">Who imports.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="targetKey">The entity.</param>
|
||||
/// <param name="file">The file.</param>
|
||||
/// <param name="mapping">The field per column.</param>
|
||||
/// <param name="options">The options.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The preview.</returns>
|
||||
public async Task<ImportPreview> PreviewAsync(Actor actor, string companyCode, string targetKey, ImportFile file, IReadOnlyList<string?> mapping, ImportOptions options,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var target = Target(targetKey);
|
||||
var context = new ImportContext(actor, companyCode, options ?? new ImportOptions());
|
||||
var rows = await target.CheckAsync(context, Rows(file, mapping), cancellationToken).ConfigureAwait(false);
|
||||
return new ImportPreview(target.Key, rows, target.CanApply);
|
||||
}
|
||||
|
||||
/// <summary>Imports the rows without errors (step 4); rows with errors are left out and reported.</summary>
|
||||
/// <param name="actor">Who imports.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="targetKey">The entity.</param>
|
||||
/// <param name="file">The file.</param>
|
||||
/// <param name="mapping">The field per column.</param>
|
||||
/// <param name="options">The options.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>What was done.</returns>
|
||||
/// <exception cref="ImportFileException">The entity is only checked for now (<see cref="ImportErrors.CheckOnly"/>).</exception>
|
||||
public async Task<ImportReport> ImportAsync(Actor actor, string companyCode, string targetKey, ImportFile file, IReadOnlyList<string?> mapping, ImportOptions options,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
ArgumentNullException.ThrowIfNull(file);
|
||||
var target = Target(targetKey);
|
||||
if (!target.CanApply)
|
||||
{
|
||||
throw new ImportFileException(ImportErrors.CheckOnly, "Only checked for now: " + target.Key, null);
|
||||
}
|
||||
|
||||
var context = new ImportContext(actor, companyCode, options ?? new ImportOptions());
|
||||
var rows = await target.ApplyAsync(context, Rows(file, mapping), cancellationToken).ConfigureAwait(false);
|
||||
var report = new ImportReport(
|
||||
target.Key,
|
||||
rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Create),
|
||||
rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Update),
|
||||
rows.Count(r => r.Outcome != ImportOutcome.Error && r.Action == ImportAction.Skip),
|
||||
rows);
|
||||
using (_logger.BeginScope(LogSections.Scope(LogSection.System)))
|
||||
{
|
||||
LogImported(_logger, target.Key, file.Name, companyCode, actor.UserName, report.Created, report.Updated, report.Skipped, report.Failed);
|
||||
}
|
||||
|
||||
return report;
|
||||
}
|
||||
|
||||
/// <summary>Writes the rows with errors and warnings as CSV (button <i>Scarica report errori</i>).</summary>
|
||||
/// <param name="rows">The checked rows.</param>
|
||||
/// <param name="text">The text of a remark, in the language of the user.</param>
|
||||
/// <param name="labels">The headers: line, key, column, outcome, message.</param>
|
||||
/// <param name="output">Where to write.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public static async Task WriteErrorReportAsync(IReadOnlyList<ImportRowResult> rows, Func<ImportRowResult, ImportMessage, (string Outcome, string Message)> text,
|
||||
IReadOnlyList<string> labels, Stream output, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(rows);
|
||||
ArgumentNullException.ThrowIfNull(text);
|
||||
ArgumentNullException.ThrowIfNull(labels);
|
||||
await using var csv = new CsvWriter(output, CsvOptions.Italian, leaveOpen: true);
|
||||
await csv.WriteRowAsync(labels, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var row in rows)
|
||||
{
|
||||
foreach (var message in row.Messages)
|
||||
{
|
||||
var (outcome, line) = text(row, message);
|
||||
await csv.WriteRowAsync([row.Line, row.Key, message.Field, outcome, line], cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
await csv.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Exports an entity with the columns of its import, so that the file can be imported again.</summary>
|
||||
/// <param name="actor">Who exports: needs the export permission of the entity and the <i>can export</i> flag.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="targetKey">The entity.</param>
|
||||
/// <param name="format">The format.</param>
|
||||
/// <param name="output">Where to write.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The number of records written.</returns>
|
||||
/// <exception cref="AccessDeniedException">The user cannot export.</exception>
|
||||
public async Task<int> ExportAsync(Actor actor, string companyCode, string targetKey, TransferFormat format, Stream output, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
var target = Target(targetKey);
|
||||
if (!(await _permissions.GetAsync(actor, cancellationToken).ConfigureAwait(false)).Flags.CanExport)
|
||||
{
|
||||
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "The user cannot export.");
|
||||
}
|
||||
|
||||
var rows = target.CanExport
|
||||
? await target.ExportAsync(new ImportContext(actor, companyCode, new ImportOptions()), cancellationToken).ConfigureAwait(false)
|
||||
: [];
|
||||
await WriteAsync(target, format, rows, output, cancellationToken).ConfigureAwait(false);
|
||||
using (_logger.BeginScope(LogSections.Scope(LogSection.System)))
|
||||
{
|
||||
LogExported(_logger, target.Key, format, companyCode, actor.UserName, rows.Count);
|
||||
}
|
||||
|
||||
return rows.Count;
|
||||
}
|
||||
|
||||
/// <summary>Writes the empty template of an entity: the headers only (for JSON, one object with empty values).</summary>
|
||||
/// <param name="target">The entity.</param>
|
||||
/// <param name="format">The format.</param>
|
||||
/// <param name="output">Where to write.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public static Task WriteTemplateAsync(IImportTarget target, TransferFormat format, Stream output, CancellationToken cancellationToken = default) =>
|
||||
WriteAsync(target, format, [], output, cancellationToken);
|
||||
|
||||
/// <summary>The name of an export or template file (<c>clienti-2026-11-12.csv</c>, <c>modello-clienti.xlsx</c>).</summary>
|
||||
/// <param name="targetKey">The entity.</param>
|
||||
/// <param name="format">The format.</param>
|
||||
/// <param name="date">The day of an export, or <see langword="null"/> for a template.</param>
|
||||
/// <returns>The file name.</returns>
|
||||
public static string FileName(string targetKey, TransferFormat format, DateOnly? date)
|
||||
{
|
||||
var extension = format switch
|
||||
{
|
||||
TransferFormat.Xlsx => ".xlsx",
|
||||
TransferFormat.Json => ".json",
|
||||
_ => ".csv",
|
||||
};
|
||||
return date is { } day
|
||||
? targetKey + "-" + day.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture) + extension
|
||||
: "modello-" + targetKey + extension;
|
||||
}
|
||||
|
||||
/// <summary>The media type of a format.</summary>
|
||||
/// <param name="format">The format.</param>
|
||||
/// <returns>The media type.</returns>
|
||||
public static string MediaType(TransferFormat format) => format switch
|
||||
{
|
||||
TransferFormat.Xlsx => XlsxWriter.MediaType,
|
||||
TransferFormat.Json => "application/json",
|
||||
_ => "text/csv",
|
||||
};
|
||||
|
||||
private static async Task WriteAsync(IImportTarget target, TransferFormat format, IReadOnlyList<IReadOnlyList<object?>> rows, Stream output, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(target);
|
||||
ArgumentNullException.ThrowIfNull(output);
|
||||
var headers = target.Fields.Select(f => f.Key).ToList();
|
||||
switch (format)
|
||||
{
|
||||
case TransferFormat.Xlsx:
|
||||
await using (var xlsx = await XlsxWriter.CreateAsync(output, leaveOpen: true, cancellationToken: cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await xlsx.StartSheetAsync(target.Key, [.. target.Fields.Select(Column)], cancellationToken).ConfigureAwait(false);
|
||||
foreach (var row in rows)
|
||||
{
|
||||
await xlsx.WriteRowAsync(row, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await xlsx.CompleteAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
break;
|
||||
case TransferFormat.Json:
|
||||
await WriteJsonAsync(target, headers, rows, output, cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
default:
|
||||
await using (var csv = new CsvWriter(output, CsvOptions.Italian, leaveOpen: true))
|
||||
{
|
||||
await csv.WriteRowAsync(headers, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var row in rows)
|
||||
{
|
||||
await csv.WriteRowAsync(row, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await csv.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static XlsxColumn Column(ImportField field) => new(field.Key, field.Kind switch
|
||||
{
|
||||
ImportFieldKind.Text => 28,
|
||||
ImportFieldKind.Number or ImportFieldKind.Date => 14,
|
||||
_ => 16,
|
||||
});
|
||||
|
||||
private static async Task WriteJsonAsync(IImportTarget target, List<string> headers, IReadOnlyList<IReadOnlyList<object?>> rows, Stream output,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
await using var json = new Utf8JsonWriter(output, JsonOptions);
|
||||
var chart = target is ChartOfAccountsImportTarget;
|
||||
if (chart)
|
||||
{
|
||||
json.WriteStartObject();
|
||||
json.WriteString("format", ImportFileReader.ChartFormat);
|
||||
json.WriteNumber("version", 1);
|
||||
json.WritePropertyName("accounts");
|
||||
}
|
||||
|
||||
json.WriteStartArray();
|
||||
IEnumerable<IReadOnlyList<object?>> objects = rows.Count > 0 ? rows : [new object?[headers.Count]];
|
||||
foreach (var row in objects)
|
||||
{
|
||||
json.WriteStartObject();
|
||||
for (var i = 0; i < headers.Count; i++)
|
||||
{
|
||||
var value = i < row.Count ? row[i] : null;
|
||||
switch (value)
|
||||
{
|
||||
case null:
|
||||
json.WriteString(headers[i], string.Empty);
|
||||
break;
|
||||
case decimal number:
|
||||
json.WriteNumber(headers[i], number);
|
||||
break;
|
||||
case bool flag:
|
||||
json.WriteBoolean(headers[i], flag);
|
||||
break;
|
||||
case DateOnly day:
|
||||
json.WriteString(headers[i], day.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture));
|
||||
break;
|
||||
default:
|
||||
json.WriteString(headers[i], Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
json.WriteEndObject();
|
||||
}
|
||||
|
||||
json.WriteEndArray();
|
||||
if (chart)
|
||||
{
|
||||
foreach (var section in new[] { "statementLines", "journalTemplates", "mappings" })
|
||||
{
|
||||
json.WriteStartArray(section);
|
||||
json.WriteEndArray();
|
||||
}
|
||||
|
||||
json.WriteEndObject();
|
||||
}
|
||||
|
||||
await json.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
[LoggerMessage(EventId = 7101, Level = LogLevel.Information,
|
||||
Message = "Import {Target} from {File} in {Company} by {User}: {Created} created, {Updated} updated, {Skipped} skipped, {Failed} with errors")]
|
||||
private static partial void LogImported(ILogger logger, string target, string file, string company, string user, int created, int updated, int skipped, int failed);
|
||||
|
||||
[LoggerMessage(EventId = 7102, Level = LogLevel.Information, Message = "Export {Target} as {Format} from {Company} by {User}: {Count} records")]
|
||||
private static partial void LogExported(ILogger logger, string target, TransferFormat format, string company, string user, int count);
|
||||
}
|
||||
@@ -0,0 +1,442 @@
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.ImportExport;
|
||||
|
||||
/// <summary>
|
||||
/// An entity of the guided import and export (SPEC §12.12): its columns, the check of the rows as if typed in its
|
||||
/// record, the writing through its own service, and the export with the same columns so that a file exported can be
|
||||
/// imported again.
|
||||
/// </summary>
|
||||
public interface IImportTarget
|
||||
{
|
||||
/// <summary>The key in addresses and texts (<c>clienti</c>, <c>piano-dei-conti</c>).</summary>
|
||||
string Key { get; }
|
||||
|
||||
/// <summary>The licence module the entity belongs to.</summary>
|
||||
string ModuleCode { get; }
|
||||
|
||||
/// <summary>The permission to import it (the write permission of its record).</summary>
|
||||
string Permission { get; }
|
||||
|
||||
/// <summary>The permission to export it (besides the <i>can export</i> flag of the user).</summary>
|
||||
string ExportPermission { get; }
|
||||
|
||||
/// <summary>Whether rows can be written now; otherwise the file is only checked (opening stock until M6, chart of accounts until M7).</summary>
|
||||
bool CanApply { get; }
|
||||
|
||||
/// <summary>Whether there are records to export now.</summary>
|
||||
bool CanExport { get; }
|
||||
|
||||
/// <summary>The columns, in the order of templates and exports.</summary>
|
||||
IReadOnlyList<ImportField> Fields { get; }
|
||||
|
||||
/// <summary>Checks the rows without writing.</summary>
|
||||
/// <param name="context">Who, where, how.</param>
|
||||
/// <param name="rows">The rows.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A result per row, in order.</returns>
|
||||
Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Writes the rows without errors, each like a save of its record.</summary>
|
||||
/// <param name="context">Who, where, how.</param>
|
||||
/// <param name="rows">The rows.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A result per row, in order, with what was done.</returns>
|
||||
Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>The records as rows of cells in the order of <see cref="Fields"/>.</summary>
|
||||
/// <param name="context">Who, where.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rows.</returns>
|
||||
Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Reads the cells of a row as values, adding a remark for every cell that is not what its field wants.</summary>
|
||||
/// <param name="row">The row.</param>
|
||||
/// <param name="messages">Where the remarks go.</param>
|
||||
public sealed class CellReader(ImportRow row, List<ImportMessage> messages)
|
||||
{
|
||||
/// <summary>The row.</summary>
|
||||
public ImportRow Row => row;
|
||||
|
||||
/// <summary>The remarks so far.</summary>
|
||||
public List<ImportMessage> Messages => messages;
|
||||
|
||||
/// <summary>Whether the cell has a value.</summary>
|
||||
/// <param name="key">The field.</param>
|
||||
/// <returns><see langword="true"/> when not empty.</returns>
|
||||
public bool Has(string key) => row[key] is not null;
|
||||
|
||||
/// <summary>The text of a cell.</summary>
|
||||
/// <param name="key">The field.</param>
|
||||
/// <returns>The text, or <see langword="null"/>.</returns>
|
||||
public string? Text(string key) => row[key];
|
||||
|
||||
/// <summary>A number.</summary>
|
||||
/// <param name="key">The field.</param>
|
||||
/// <returns>The number, or <see langword="null"/> when empty or wrong (with a remark).</returns>
|
||||
public decimal? Number(string key)
|
||||
{
|
||||
if (row[key] is not { } text)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (ImportValues.TryNumber(text, out var value))
|
||||
{
|
||||
return value;
|
||||
}
|
||||
|
||||
messages.Add(new(key, ImportErrors.Number, Value: text));
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>A date.</summary>
|
||||
/// <param name="key">The field.</param>
|
||||
/// <returns>The date, or <see langword="null"/> when empty or wrong (with a remark).</returns>
|
||||
public DateOnly? Date(string key)
|
||||
{
|
||||
if (row[key] is not { } text)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (ImportValues.TryDate(text, out var value))
|
||||
{
|
||||
return value;
|
||||
}
|
||||
|
||||
messages.Add(new(key, ImportErrors.Date, Value: text));
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Yes or no.</summary>
|
||||
/// <param name="key">The field.</param>
|
||||
/// <returns>The value, or <see langword="null"/> when empty or wrong (with a remark).</returns>
|
||||
public bool? Boolean(string key)
|
||||
{
|
||||
if (row[key] is not { } text)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (ImportValues.TryBoolean(text, out var value))
|
||||
{
|
||||
return value;
|
||||
}
|
||||
|
||||
messages.Add(new(key, ImportErrors.Boolean, Value: text));
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>One of the words of a field.</summary>
|
||||
/// <param name="field">The field with its choices.</param>
|
||||
/// <returns>The position of the word, or <see langword="null"/> when empty or unknown (with a remark).</returns>
|
||||
public int? Choice(ImportField field)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(field);
|
||||
if (row[field.Key] is not { } text)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var choices = field.Choices ?? [];
|
||||
var index = ImportValues.Choice(text, choices);
|
||||
if (index >= 0)
|
||||
{
|
||||
return index;
|
||||
}
|
||||
|
||||
messages.Add(new(field.Key, ImportErrors.Choice, Value: string.Join(", ", choices)));
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>The id of a code of another archive or table.</summary>
|
||||
/// <param name="key">The field.</param>
|
||||
/// <param name="index">The codes.</param>
|
||||
/// <returns>The id, or <see langword="null"/> when empty or unknown (with a remark).</returns>
|
||||
public long? Code(string key, CodeIndex index)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(index);
|
||||
if (row[key] is not { } code)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (index.Find(code) is { } id)
|
||||
{
|
||||
return id;
|
||||
}
|
||||
|
||||
messages.Add(new(key, ImportErrors.CodeUnknown, Value: code));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The ids of the records of an archive or table by code, ignoring case.</summary>
|
||||
public sealed class CodeIndex
|
||||
{
|
||||
private readonly Dictionary<string, long> _ids = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly Dictionary<long, string> _codes = [];
|
||||
|
||||
/// <summary>Creates an index.</summary>
|
||||
/// <param name="entries">The codes with their ids.</param>
|
||||
public CodeIndex(IEnumerable<(string Code, long Id)> entries)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entries);
|
||||
foreach (var (code, id) in entries)
|
||||
{
|
||||
_ids.TryAdd(code, id);
|
||||
_codes[id] = code;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The number of codes.</summary>
|
||||
public int Count => _ids.Count;
|
||||
|
||||
/// <summary>Loads the codes of a table of the company.</summary>
|
||||
/// <typeparam name="T">The table.</typeparam>
|
||||
/// <param name="uow">The unit of work.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The index.</returns>
|
||||
public static async Task<CodeIndex> LoadAsync<T>(IUnitOfWork uow, CancellationToken cancellationToken)
|
||||
where T : CodedEntity, new()
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(uow);
|
||||
var rows = await uow.Repository<T, long>().ListAsync(Query.For<T>(), cancellationToken).ConfigureAwait(false);
|
||||
return new CodeIndex(rows.Items.Select(r => (r.Code, r.Id)));
|
||||
}
|
||||
|
||||
/// <summary>The id of a code.</summary>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <returns>The id, or <see langword="null"/>.</returns>
|
||||
public long? Find(string? code) => code is not null && _ids.TryGetValue(code.Trim(), out var id) ? id : null;
|
||||
|
||||
/// <summary>The code of an id.</summary>
|
||||
/// <param name="id">The id.</param>
|
||||
/// <returns>The code, or <see langword="null"/>.</returns>
|
||||
public string? CodeOf(long? id) => id is { } key && _codes.TryGetValue(key, out var code) ? code : null;
|
||||
|
||||
/// <summary>Adds a code written meanwhile.</summary>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <param name="id">The id.</param>
|
||||
public void Add(string code, long id)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(code);
|
||||
_ids[code] = id;
|
||||
_codes[id] = code;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The common steps of the entities written as records (parties, items): each row becomes a record, new or read by its
|
||||
/// code, checked by the service of the record and saved by it, so the import obeys the same rules as the screen.
|
||||
/// </summary>
|
||||
/// <typeparam name="TRecord">The record.</typeparam>
|
||||
/// <typeparam name="TState">What is loaded once per check or import (codes of tables and archives).</typeparam>
|
||||
public abstract class RecordImportTarget<TRecord, TState> : IImportTarget
|
||||
where TRecord : class
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public abstract string Key { get; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public abstract string ModuleCode { get; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public abstract string Permission { get; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public abstract string ExportPermission { get; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanApply => true;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanExport => true;
|
||||
|
||||
/// <inheritdoc />
|
||||
public abstract IReadOnlyList<ImportField> Fields { get; }
|
||||
|
||||
/// <summary>The column with the code of the record.</summary>
|
||||
protected virtual string CodeField => "codice";
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
|
||||
RunAsync(context, rows, write: false, cancellationToken);
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
|
||||
RunAsync(context, rows, write: true, cancellationToken);
|
||||
|
||||
/// <inheritdoc />
|
||||
public abstract Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Loads what every row needs, checking a permission.</summary>
|
||||
/// <param name="context">Who, where, how.</param>
|
||||
/// <param name="permission">The permission demanded (to import or to export).</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The state.</returns>
|
||||
protected abstract Task<TState> LoadAsync(ImportContext context, string permission, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>The id of an existing record with a code, or <see langword="null"/>; a remark refuses the code (another kind).</summary>
|
||||
/// <param name="state">The state.</param>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <param name="messages">Where remarks go.</param>
|
||||
/// <returns>The id.</returns>
|
||||
protected abstract long? Existing(TState state, string code, List<ImportMessage> messages);
|
||||
|
||||
/// <summary>A new record, or an existing one read by id.</summary>
|
||||
/// <param name="context">Who, where.</param>
|
||||
/// <param name="id">The id, or <see langword="null"/> for a new record.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The record.</returns>
|
||||
protected abstract Task<TRecord?> OpenAsync(ImportContext context, long? id, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Copies the cells of a row into the record; a code given for a new record is set too.</summary>
|
||||
/// <param name="context">Who, where, how.</param>
|
||||
/// <param name="state">The state.</param>
|
||||
/// <param name="record">The record.</param>
|
||||
/// <param name="cells">The row with its remarks.</param>
|
||||
/// <param name="isNew">Whether the record is new.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
protected abstract Task FillAsync(ImportContext context, TState state, TRecord record, CellReader cells, bool isNew, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Checks a record with the rules of its service.</summary>
|
||||
/// <param name="context">Who, where.</param>
|
||||
/// <param name="record">The record.</param>
|
||||
/// <param name="isNew">Whether the record is new (its code is checked against the code rules).</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The problems.</returns>
|
||||
protected abstract Task<IReadOnlyList<TableProblem>> ValidateAsync(ImportContext context, TRecord record, bool isNew, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Saves a record with its service.</summary>
|
||||
/// <param name="context">Who, where, how.</param>
|
||||
/// <param name="record">The record.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The code and id given by the save.</returns>
|
||||
protected abstract Task<(string Code, long Id)> SaveAsync(ImportContext context, TRecord record, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>What identifies the row in the preview (code, else description).</summary>
|
||||
/// <param name="row">The row.</param>
|
||||
/// <returns>The text.</returns>
|
||||
protected abstract string Label(ImportRow row);
|
||||
|
||||
/// <summary>Records a code saved, so that later rows find it.</summary>
|
||||
/// <param name="state">The state.</param>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <param name="id">The id.</param>
|
||||
protected abstract void Remember(TState state, string code, long id);
|
||||
|
||||
/// <summary>The column of a field of the service (<c>VatNumber</c>, <c>Fiscal.RecipientCode</c>); empty for the row.</summary>
|
||||
/// <param name="serviceField">The field named by the service.</param>
|
||||
/// <returns>The column key.</returns>
|
||||
protected abstract string ColumnOf(string serviceField);
|
||||
|
||||
private async Task<IReadOnlyList<ImportRowResult>> RunAsync(ImportContext context, IReadOnlyList<ImportRow> rows, bool write, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
ArgumentNullException.ThrowIfNull(rows);
|
||||
var state = await LoadAsync(context, Permission, cancellationToken).ConfigureAwait(false);
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var results = new List<ImportRowResult>(rows.Count);
|
||||
foreach (var row in rows)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var messages = new List<ImportMessage>();
|
||||
var cells = new CellReader(row, messages);
|
||||
var code = row[CodeField];
|
||||
long? id = null;
|
||||
if (code is not null)
|
||||
{
|
||||
if (!seen.Add(code))
|
||||
{
|
||||
messages.Add(new(CodeField, ImportErrors.CodeRepeated, Value: code));
|
||||
results.Add(new(row.Line, Label(row), ImportAction.Skip, messages));
|
||||
continue;
|
||||
}
|
||||
|
||||
id = Existing(state, code, messages);
|
||||
if (messages.Count > 0)
|
||||
{
|
||||
results.Add(new(row.Line, Label(row), ImportAction.Skip, messages));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (id is not null && context.Options.Existing == ExistingCodeAction.Skip)
|
||||
{
|
||||
results.Add(new(row.Line, Label(row), ImportAction.Skip, [new(CodeField, ImportErrors.CodeExists, IsWarning: true, Value: code)]));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
else if (context.Options.Missing == MissingCodeAction.Refuse)
|
||||
{
|
||||
messages.Add(new(CodeField, ImportErrors.CodeMissing));
|
||||
results.Add(new(row.Line, Label(row), ImportAction.Skip, messages));
|
||||
continue;
|
||||
}
|
||||
|
||||
var isNew = id is null;
|
||||
var action = isNew ? ImportAction.Create : ImportAction.Update;
|
||||
var record = await OpenAsync(context, id, cancellationToken).ConfigureAwait(false);
|
||||
if (record is null)
|
||||
{
|
||||
messages.Add(new(CodeField, ImportErrors.WriteFailed, Value: code));
|
||||
results.Add(new(row.Line, Label(row), ImportAction.Skip, messages));
|
||||
continue;
|
||||
}
|
||||
|
||||
await FillAsync(context, state, record, cells, isNew, cancellationToken).ConfigureAwait(false);
|
||||
if (isNew)
|
||||
{
|
||||
messages.AddRange(Fields.Where(f => f.Required && !cells.Has(f.Key) && messages.All(m => m.Field != f.Key))
|
||||
.Select(f => new ImportMessage(f.Key, ImportErrors.Required)));
|
||||
}
|
||||
|
||||
if (messages.All(m => m.IsWarning))
|
||||
{
|
||||
messages.AddRange((await ValidateAsync(context, record, isNew, cancellationToken).ConfigureAwait(false))
|
||||
.Select(p => new ImportMessage(ColumnOf(p.Field), p.Code, p.IsWarning)));
|
||||
}
|
||||
|
||||
if (write && messages.All(m => m.IsWarning))
|
||||
{
|
||||
try
|
||||
{
|
||||
var (savedCode, savedId) = await SaveAsync(context, record, cancellationToken).ConfigureAwait(false);
|
||||
Remember(state, savedCode, savedId);
|
||||
}
|
||||
catch (ValidationFailedException ex)
|
||||
{
|
||||
messages.AddRange(ex.Errors.Select(TableErrors.Split).Select(e => new ImportMessage(ColumnOf(e.Field), e.Code)));
|
||||
}
|
||||
catch (Core.Common.ConcurrencyException)
|
||||
{
|
||||
messages.Add(new(string.Empty, ImportErrors.WriteFailed));
|
||||
}
|
||||
}
|
||||
|
||||
results.Add(new(row.Line, Label(row), messages.Any(m => !m.IsWarning) ? ImportAction.Skip : action, messages));
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Splits the <c>Field:code</c> errors of <see cref="ValidationFailedException"/>.</summary>
|
||||
internal static class TableErrors
|
||||
{
|
||||
/// <summary>Splits an error.</summary>
|
||||
/// <param name="error">The error.</param>
|
||||
/// <returns>The field (empty for the record) and the code.</returns>
|
||||
public static (string Field, string Code) Split(string error)
|
||||
{
|
||||
var colon = error.LastIndexOf(':');
|
||||
return colon < 0 ? (string.Empty, error) : (error[..colon], error[(colon + 1)..]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace Khaemhat.Application.ImportExport;
|
||||
|
||||
/// <summary>The text codes of the import remarks (<c>import.*</c>), shown by the screen with the field and the value.</summary>
|
||||
public static class ImportErrors
|
||||
{
|
||||
/// <summary>The file is not CSV, XLSX or JSON.</summary>
|
||||
public const string FileFormat = "import.file.format";
|
||||
|
||||
/// <summary>The file has no header or no rows.</summary>
|
||||
public const string FileEmpty = "import.file.empty";
|
||||
|
||||
/// <summary>The file cannot be read (damaged spreadsheet, invalid JSON).</summary>
|
||||
public const string FileUnreadable = "import.file.unreadable";
|
||||
|
||||
/// <summary>The file has more rows than an import takes.</summary>
|
||||
public const string FileTooLarge = "import.file.too-large";
|
||||
|
||||
/// <summary>The entity is unknown or not licensed.</summary>
|
||||
public const string TargetUnknown = "import.target.unknown";
|
||||
|
||||
/// <summary>The entity is only checked for now (opening stock until M6, chart of accounts until M7).</summary>
|
||||
public const string CheckOnly = "import.target.check-only";
|
||||
|
||||
/// <summary>A required column of a new record is empty or not mapped.</summary>
|
||||
public const string Required = "import.value.required";
|
||||
|
||||
/// <summary>Not a number.</summary>
|
||||
public const string Number = "import.value.number";
|
||||
|
||||
/// <summary>Not a date.</summary>
|
||||
public const string Date = "import.value.date";
|
||||
|
||||
/// <summary>Not yes or no.</summary>
|
||||
public const string Boolean = "import.value.boolean";
|
||||
|
||||
/// <summary>Not one of the words accepted (<c>{0}</c> lists them).</summary>
|
||||
public const string Choice = "import.value.choice";
|
||||
|
||||
/// <summary>A code of another archive or table that does not exist (<c>{0}</c>).</summary>
|
||||
public const string CodeUnknown = "import.value.code-unknown";
|
||||
|
||||
/// <summary>The row has no code and the options do not generate it.</summary>
|
||||
public const string CodeMissing = "import.code.missing";
|
||||
|
||||
/// <summary>The same code is on an earlier row of the file.</summary>
|
||||
public const string CodeRepeated = "import.code.repeated";
|
||||
|
||||
/// <summary>The code exists and the options skip existing codes (a remark, not an error).</summary>
|
||||
public const string CodeExists = "import.code.exists";
|
||||
|
||||
/// <summary>The code belongs to a party of another kind (a supplier among the customers).</summary>
|
||||
public const string OtherKind = "import.party.other-kind";
|
||||
|
||||
/// <summary>The city was filled from the postal code (<c>{0}</c>).</summary>
|
||||
public const string CityFilled = "import.filled.city";
|
||||
|
||||
/// <summary>The postal code was filled from the city (<c>{0}</c>).</summary>
|
||||
public const string PostalCodeFilled = "import.filled.postal-code";
|
||||
|
||||
/// <summary>A price row names both a list and a customer, or neither.</summary>
|
||||
public const string PriceTarget = "import.price.target";
|
||||
|
||||
/// <summary>Opening stock of an item that is not stocked goods.</summary>
|
||||
public const string NotStocked = "import.stock.not-stocked";
|
||||
|
||||
/// <summary>The quantity must be more than zero.</summary>
|
||||
public const string Positive = "import.value.positive";
|
||||
|
||||
/// <summary>The record could not be written (someone changed it meanwhile, or an unexpected rule).</summary>
|
||||
public const string WriteFailed = "import.write.failed";
|
||||
|
||||
/// <summary>The level of an account is not 1 to 3, or not the number of parts of its code.</summary>
|
||||
public const string AccountLevel = "import.coa.level";
|
||||
|
||||
/// <summary>The parent of an account is not the code without its last part, or is not in the file (<c>{0}</c>).</summary>
|
||||
public const string AccountParent = "import.coa.parent";
|
||||
|
||||
/// <summary>An account has a nature other than its parent's.</summary>
|
||||
public const string AccountNature = "import.coa.nature";
|
||||
|
||||
/// <summary>An account with sub-accounts is marked as postable.</summary>
|
||||
public const string AccountPostable = "import.coa.postable";
|
||||
|
||||
/// <summary>A leaf account is not marked as postable (a remark).</summary>
|
||||
public const string AccountLeaf = "import.coa.leaf";
|
||||
|
||||
/// <summary>A flag letter is not M, I, P, C or X (<c>{0}</c>).</summary>
|
||||
public const string AccountFlag = "import.coa.flag";
|
||||
}
|
||||
|
||||
/// <summary>The cells of the import as values, and the values of the export as cells.</summary>
|
||||
public static class ImportValues
|
||||
{
|
||||
private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT");
|
||||
|
||||
private static readonly string[] DateFormats =
|
||||
["dd/MM/yyyy", "d/M/yyyy", "dd/MM/yy", "d/M/yy", "dd-MM-yyyy", "d-M-yyyy", "dd.MM.yyyy", "yyyy-MM-dd", "yyyy/MM/dd", "yyyyMMdd", "yyyy-MM-ddTHH:mm:ss"];
|
||||
|
||||
private static readonly HashSet<string> Yes = new(StringComparer.Ordinal) { "si", "s", "yes", "y", "x", "1", "true", "vero", "v" };
|
||||
|
||||
private static readonly HashSet<string> No = new(StringComparer.Ordinal) { "no", "n", "0", "false", "falso", "f", "-" };
|
||||
|
||||
private static readonly DateTime Epoch = new(1899, 12, 30, 0, 0, 0, DateTimeKind.Unspecified);
|
||||
|
||||
/// <summary>
|
||||
/// A header or a word as compared by the mapping and the choices: lower case, no accents, every run of other
|
||||
/// characters as one underscore (<c>Partita IVA</c> and <c>partita-iva</c> both give <c>partita_iva</c>).
|
||||
/// </summary>
|
||||
/// <param name="text">The text.</param>
|
||||
/// <returns>The normalized text.</returns>
|
||||
public static string Normalize(string? text)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
var builder = new StringBuilder(text.Length);
|
||||
var underscore = false;
|
||||
foreach (var c in text.Trim().Normalize(NormalizationForm.FormD))
|
||||
{
|
||||
if (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.NonSpacingMark)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char.IsAsciiLetterOrDigit(c))
|
||||
{
|
||||
if (underscore && builder.Length > 0)
|
||||
{
|
||||
builder.Append('_');
|
||||
}
|
||||
|
||||
builder.Append(char.ToLowerInvariant(c));
|
||||
underscore = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
underscore = true;
|
||||
}
|
||||
}
|
||||
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads a number written the Italian way (<c>1.234,56</c>, <c>€ 12,5</c>) or the machine way (<c>1234.56</c>):
|
||||
/// with both marks the last one is the decimal one; a single point alone is the decimal mark (as spreadsheets and JSON
|
||||
/// write it), several points alone group thousands; percent signs, currency signs and spaces are ignored.
|
||||
/// </summary>
|
||||
/// <param name="text">The cell.</param>
|
||||
/// <param name="value">The number.</param>
|
||||
/// <returns><see langword="true"/> when the cell is a number.</returns>
|
||||
public static bool TryNumber(string? text, out decimal value)
|
||||
{
|
||||
value = 0;
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var clean = new StringBuilder(text.Length);
|
||||
foreach (var c in text)
|
||||
{
|
||||
if (char.IsAsciiDigit(c) || c is ',' or '.' or '-' or '+' or 'e' or 'E')
|
||||
{
|
||||
clean.Append(c);
|
||||
}
|
||||
else if (!char.IsWhiteSpace(c) && c is not ('€' or '%' or '\'' or ' ' or ' '))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
var s = clean.ToString();
|
||||
var comma = s.LastIndexOf(',');
|
||||
var point = s.LastIndexOf('.');
|
||||
if (comma >= 0 && point >= 0)
|
||||
{
|
||||
s = comma > point ? s.Replace(".", string.Empty, StringComparison.Ordinal).Replace(',', '.') : s.Replace(",", string.Empty, StringComparison.Ordinal);
|
||||
}
|
||||
else if (comma >= 0)
|
||||
{
|
||||
s = s.Count(c => c == ',') > 1 ? s.Replace(",", string.Empty, StringComparison.Ordinal) : s.Replace(',', '.');
|
||||
}
|
||||
else if (point >= 0 && s.Count(c => c == '.') > 1)
|
||||
{
|
||||
s = s.Replace(".", string.Empty, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
return decimal.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out value);
|
||||
}
|
||||
|
||||
/// <summary>Reads a date: <c>dd/MM/yyyy</c> and its variants, ISO, or a spreadsheet serial number.</summary>
|
||||
/// <param name="text">The cell.</param>
|
||||
/// <param name="value">The date.</param>
|
||||
/// <returns><see langword="true"/> when the cell is a date.</returns>
|
||||
public static bool TryDate(string? text, out DateOnly value)
|
||||
{
|
||||
value = default;
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var s = text.Trim();
|
||||
if (s.Length > 10 && s[10] is ' ' or 'T')
|
||||
{
|
||||
s = s[..10];
|
||||
}
|
||||
|
||||
if (DateTime.TryParseExact(s, DateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out var day))
|
||||
{
|
||||
value = DateOnly.FromDateTime(day);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (s.All(char.IsAsciiDigit) && s.Length <= 5 && int.TryParse(s, NumberStyles.None, CultureInfo.InvariantCulture, out var serial) && serial > 0)
|
||||
{
|
||||
value = DateOnly.FromDateTime(Epoch.AddDays(serial));
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Reads yes or no: <c>sì</c>, <c>x</c>, <c>1</c>, <c>VERO</c>, <c>true</c>... and <c>no</c>, <c>0</c>, <c>FALSO</c>...</summary>
|
||||
/// <param name="text">The cell.</param>
|
||||
/// <param name="value">The value.</param>
|
||||
/// <returns><see langword="true"/> when the cell is yes or no.</returns>
|
||||
public static bool TryBoolean(string? text, out bool value)
|
||||
{
|
||||
var word = Normalize(text);
|
||||
value = Yes.Contains(word);
|
||||
return value || No.Contains(word);
|
||||
}
|
||||
|
||||
/// <summary>Finds a word among the choices of a field, ignoring case, accents, spaces and punctuation (<c>P.A.</c> is <c>pa</c>).</summary>
|
||||
/// <param name="text">The cell.</param>
|
||||
/// <param name="choices">The words accepted, in the order of the values they stand for.</param>
|
||||
/// <returns>The position of the word, or -1.</returns>
|
||||
public static int Choice(string? text, IReadOnlyList<string> choices)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(choices);
|
||||
var word = Normalize(text).Replace("_", string.Empty, StringComparison.Ordinal);
|
||||
for (var i = 0; i < choices.Count; i++)
|
||||
{
|
||||
if (Normalize(choices[i]).Replace("_", string.Empty, StringComparison.Ordinal) == word)
|
||||
{
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
/// <summary>A number for a text cell of the export, the Italian way without thousands marks (<c>1234,5</c>).</summary>
|
||||
/// <param name="value">The number.</param>
|
||||
/// <returns>The text, or <see langword="null"/>.</returns>
|
||||
public static string? Text(decimal? value) => value?.ToString("0.############", Italian);
|
||||
|
||||
/// <summary>A date for a text cell of the export (<c>dd/MM/yyyy</c>).</summary>
|
||||
/// <param name="value">The date.</param>
|
||||
/// <returns>The text, or <see langword="null"/>.</returns>
|
||||
public static string? Text(DateOnly? value) => value?.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
|
||||
|
||||
/// <summary>Yes or no for a text cell of the export.</summary>
|
||||
/// <param name="value">The value.</param>
|
||||
/// <returns><c>sì</c> or <c>no</c>.</returns>
|
||||
public static string Text(bool value) => value ? "sì" : "no";
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
using Khaemhat.Application.Items;
|
||||
using Khaemhat.Application.Modules;
|
||||
using Khaemhat.Application.Querying;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.ImportExport;
|
||||
|
||||
/// <summary>
|
||||
/// The items (SPEC §12.12): each row is an item read by its code, or a new one with the values proposed by the record,
|
||||
/// filled with the cells of the row, checked and saved by <see cref="ItemService"/>. Empty cells keep the values of an
|
||||
/// existing item; units, bar codes, prices and suppliers of the record are left as they are.
|
||||
/// </summary>
|
||||
/// <param name="items">The items.</param>
|
||||
/// <param name="codes">The automatic codes.</param>
|
||||
/// <param name="factory">Opens the company databases (codes of the tables).</param>
|
||||
/// <param name="permissions">Checks the permission to import.</param>
|
||||
public sealed class ItemsImportTarget(ItemService items, CodeRuleService codes, IUnitOfWorkFactory factory, PermissionService permissions)
|
||||
: RecordImportTarget<ItemRecord, ItemsImportTarget.State>
|
||||
{
|
||||
/// <summary>The words of <c>tipo</c>, in the order of <see cref="ItemKind"/>.</summary>
|
||||
public static readonly IReadOnlyList<string> KindWords = ["merce", "servizio", "spesa", "descrittivo", "cespite"];
|
||||
|
||||
private static readonly ImportField[] ItemFields =
|
||||
[
|
||||
new("codice", ImportFieldKind.Code, Aliases: ["cod", "codice_articolo", "cod_articolo", "sku", "code"]),
|
||||
new("descrizione", Required: true, Aliases: ["descr", "description", "nome"]),
|
||||
new("descrizione_estesa", Aliases: ["descrizione_lunga", "note_descrizione"]),
|
||||
new("tipo", ImportFieldKind.Choice, Aliases: ["tipologia", "tipo_articolo"], Choices: KindWords),
|
||||
new("categoria", ImportFieldKind.Code, Aliases: ["famiglia", "categoria_merceologica"]),
|
||||
new("um", ImportFieldKind.Code, Aliases: ["unita_misura", "unita_di_misura", "u_m"]),
|
||||
new("iva_vendite", ImportFieldKind.Code, Aliases: ["iva", "aliquota_iva", "codice_iva"]),
|
||||
new("iva_acquisti", ImportFieldKind.Code),
|
||||
new("ean", Aliases: ["barcode", "codice_a_barre", "ean13", "gtin"]),
|
||||
new("nc8", Aliases: ["nomenclatura", "codice_doganale", "taric"]),
|
||||
new("marca", Aliases: ["brand"]),
|
||||
new("produttore", Aliases: ["fabbricante", "manufacturer"]),
|
||||
new("peso_netto", ImportFieldKind.Number),
|
||||
new("peso_lordo", ImportFieldKind.Number, Aliases: ["peso"]),
|
||||
new("a_magazzino", ImportFieldKind.Boolean, Aliases: ["gestito_a_magazzino", "movimenta_magazzino"]),
|
||||
new("magazzino", ImportFieldKind.Code, Aliases: ["deposito"]),
|
||||
new("scorta_minima", ImportFieldKind.Number, Aliases: ["scorta"]),
|
||||
new("punto_riordino", ImportFieldKind.Number),
|
||||
new("lotto_riordino", ImportFieldKind.Number),
|
||||
new("prezzo", ImportFieldKind.Number, Aliases: ["prezzo_vendita", "prezzo_base", "price"]),
|
||||
new("costo_standard", ImportFieldKind.Number, Aliases: ["costo"]),
|
||||
new("conto_ricavo", Aliases: ["conto_ricavi"]),
|
||||
new("conto_costo", Aliases: ["conto_costi"]),
|
||||
new("note", Aliases: ["annotazioni", "notes"]),
|
||||
];
|
||||
|
||||
private static readonly Dictionary<string, string> Columns = new(StringComparer.Ordinal)
|
||||
{
|
||||
["Code"] = "codice",
|
||||
["Description"] = "descrizione",
|
||||
["ExtendedDescription"] = "descrizione_estesa",
|
||||
["Kind"] = "tipo",
|
||||
["CategoryId"] = "categoria",
|
||||
["UnitOfMeasureId"] = "um",
|
||||
["SalesTaxCodeId"] = "iva_vendite",
|
||||
["PurchaseTaxCodeId"] = "iva_acquisti",
|
||||
["Barcode"] = "ean",
|
||||
["CustomsCode"] = "nc8",
|
||||
["Brand"] = "marca",
|
||||
["Manufacturer"] = "produttore",
|
||||
["NetWeight"] = "peso_netto",
|
||||
["GrossWeight"] = "peso_lordo",
|
||||
["Stocked"] = "a_magazzino",
|
||||
["WarehouseId"] = "magazzino",
|
||||
["MinimumStock"] = "scorta_minima",
|
||||
["ReorderPoint"] = "punto_riordino",
|
||||
["ReorderLot"] = "lotto_riordino",
|
||||
["Price"] = "prezzo",
|
||||
["StandardCost"] = "costo_standard",
|
||||
["RevenueAccountCode"] = "conto_ricavo",
|
||||
["CostAccountCode"] = "conto_costo",
|
||||
["Notes"] = "note",
|
||||
};
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string Key => "articoli";
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string ModuleCode => ModuleCodes.Core;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string Permission => ItemService.WritePermission;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string ExportPermission => ItemService.ReadPermission;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override IReadOnlyList<ImportField> Fields => ItemFields;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override async Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var state = await LoadAsync(context, ExportPermission, cancellationToken).ConfigureAwait(false);
|
||||
var rows = new List<IReadOnlyList<object?>>();
|
||||
var offset = 0;
|
||||
while (true)
|
||||
{
|
||||
var page = await items.ListAsync(context.Actor, context.CompanyCode, new ListQuery { Offset = offset, Limit = 500, Sort = [new ListSort("code")] }, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
foreach (var row in page.Items)
|
||||
{
|
||||
if (await items.GetAsync(context.Actor, context.CompanyCode, row.Id, cancellationToken).ConfigureAwait(false) is { } record)
|
||||
{
|
||||
rows.Add(Cells(state, record.Item));
|
||||
}
|
||||
}
|
||||
|
||||
offset += page.Items.Count;
|
||||
if (page.Items.Count == 0 || offset >= page.Total)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task<State> LoadAsync(ImportContext context, string permission, CancellationToken cancellationToken)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, permission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var all = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>(), cancellationToken).ConfigureAwait(false)).Items;
|
||||
return new State
|
||||
{
|
||||
Items = new CodeIndex(all.Select(i => (i.Code, i.Id))),
|
||||
Categories = await CodeIndex.LoadAsync<ItemCategory>(uow, cancellationToken).ConfigureAwait(false),
|
||||
Units = await CodeIndex.LoadAsync<UnitOfMeasure>(uow, cancellationToken).ConfigureAwait(false),
|
||||
TaxCodes = await CodeIndex.LoadAsync<TaxCode>(uow, cancellationToken).ConfigureAwait(false),
|
||||
Warehouses = await CodeIndex.LoadAsync<Warehouse>(uow, cancellationToken).ConfigureAwait(false),
|
||||
};
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override long? Existing(State state, string code, List<ImportMessage> messages)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(state);
|
||||
return state.Items.Find(code);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task<ItemRecord?> OpenAsync(ImportContext context, long? id, CancellationToken cancellationToken) =>
|
||||
id is { } key
|
||||
? await items.GetAsync(context.Actor, context.CompanyCode, key, cancellationToken).ConfigureAwait(false)
|
||||
: await items.NewAsync(context.Actor, context.CompanyCode, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override Task FillAsync(ImportContext context, State state, ItemRecord record, CellReader cells, bool isNew, CancellationToken cancellationToken)
|
||||
{
|
||||
var item = record.Item;
|
||||
if (isNew && cells.Text("codice") is { } code)
|
||||
{
|
||||
item.Code = code;
|
||||
}
|
||||
|
||||
if (cells.Choice(ItemFields[3]) is { } kind)
|
||||
{
|
||||
item.Kind = (ItemKind)kind;
|
||||
if (isNew && item.Kind != ItemKind.Goods)
|
||||
{
|
||||
item.Stocked = false;
|
||||
}
|
||||
}
|
||||
|
||||
Set(cells, "descrizione", v => item.Description = v);
|
||||
Set(cells, "descrizione_estesa", v => item.ExtendedDescription = v);
|
||||
Set(cells, "ean", v => item.Barcode = v);
|
||||
Set(cells, "nc8", v => item.CustomsCode = v);
|
||||
Set(cells, "marca", v => item.Brand = v);
|
||||
Set(cells, "produttore", v => item.Manufacturer = v);
|
||||
Set(cells, "conto_ricavo", v => item.RevenueAccountCode = v);
|
||||
Set(cells, "conto_costo", v => item.CostAccountCode = v);
|
||||
Set(cells, "note", v => item.Notes = v);
|
||||
item.CategoryId = cells.Code("categoria", state.Categories) ?? item.CategoryId;
|
||||
item.UnitOfMeasureId = cells.Code("um", state.Units) ?? item.UnitOfMeasureId;
|
||||
item.SalesTaxCodeId = cells.Code("iva_vendite", state.TaxCodes) ?? item.SalesTaxCodeId;
|
||||
item.PurchaseTaxCodeId = cells.Code("iva_acquisti", state.TaxCodes) ?? item.PurchaseTaxCodeId;
|
||||
item.WarehouseId = cells.Code("magazzino", state.Warehouses) ?? item.WarehouseId;
|
||||
item.Stocked = cells.Boolean("a_magazzino") ?? item.Stocked;
|
||||
item.NetWeight = cells.Number("peso_netto") ?? item.NetWeight;
|
||||
item.GrossWeight = cells.Number("peso_lordo") ?? item.GrossWeight;
|
||||
item.MinimumStock = cells.Number("scorta_minima") ?? item.MinimumStock;
|
||||
item.ReorderPoint = cells.Number("punto_riordino") ?? item.ReorderPoint;
|
||||
item.ReorderLot = cells.Number("lotto_riordino") ?? item.ReorderLot;
|
||||
item.Price = cells.Number("prezzo") ?? item.Price;
|
||||
item.StandardCost = cells.Number("costo_standard") ?? item.StandardCost;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task<IReadOnlyList<TableProblem>> ValidateAsync(ImportContext context, ItemRecord record, bool isNew, CancellationToken cancellationToken)
|
||||
{
|
||||
var problems = (await items.ValidateAsync(context.Actor, context.CompanyCode, record, cancellationToken).ConfigureAwait(false)).ToList();
|
||||
if (isNew && record.Item.Code.Length > 0)
|
||||
{
|
||||
var rule = await codes.RuleAsync(context.CompanyCode, ItemService.CodeRule, cancellationToken).ConfigureAwait(false);
|
||||
if (CodeRuleService.CheckManual(rule, record.Item.Code) is { } manual)
|
||||
{
|
||||
problems.Add(new(nameof(Item.Code), manual));
|
||||
}
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task<(string Code, long Id)> SaveAsync(ImportContext context, ItemRecord record, CancellationToken cancellationToken)
|
||||
{
|
||||
var saved = await items.SaveAsync(context.Actor, context.CompanyCode, record, cancellationToken).ConfigureAwait(false);
|
||||
return (saved.Item.Code, saved.Item.Id);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string Label(ImportRow row)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(row);
|
||||
return row["codice"] ?? row["descrizione"] ?? string.Empty;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Remember(State state, string code, long id)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(state);
|
||||
state.Items.Add(code, id);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string ColumnOf(string serviceField) => Columns.GetValueOrDefault(serviceField ?? string.Empty, string.Empty);
|
||||
|
||||
private static void Set(CellReader cells, string key, Action<string> set)
|
||||
{
|
||||
if (cells.Text(key) is { } value)
|
||||
{
|
||||
set(value);
|
||||
}
|
||||
}
|
||||
|
||||
private static object?[] Cells(State state, Item item) =>
|
||||
[
|
||||
item.Code, item.Description, item.ExtendedDescription, KindWords[(int)item.Kind], state.Categories.CodeOf(item.CategoryId), state.Units.CodeOf(item.UnitOfMeasureId),
|
||||
state.TaxCodes.CodeOf(item.SalesTaxCodeId), state.TaxCodes.CodeOf(item.PurchaseTaxCodeId), item.Barcode, item.CustomsCode, item.Brand, item.Manufacturer,
|
||||
item.NetWeight, item.GrossWeight, item.Stocked, state.Warehouses.CodeOf(item.WarehouseId), item.MinimumStock, item.ReorderPoint, item.ReorderLot, item.Price,
|
||||
item.StandardCost, item.RevenueAccountCode, item.CostAccountCode, item.Notes,
|
||||
];
|
||||
|
||||
/// <summary>What a check or an import of items loads once.</summary>
|
||||
public sealed class State
|
||||
{
|
||||
/// <summary>The items.</summary>
|
||||
public required CodeIndex Items { get; init; }
|
||||
|
||||
/// <summary>The categories.</summary>
|
||||
public required CodeIndex Categories { get; init; }
|
||||
|
||||
/// <summary>The units of measure.</summary>
|
||||
public required CodeIndex Units { get; init; }
|
||||
|
||||
/// <summary>The VAT codes.</summary>
|
||||
public required CodeIndex TaxCodes { get; init; }
|
||||
|
||||
/// <summary>The warehouses.</summary>
|
||||
public required CodeIndex Warehouses { get; init; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
using System.Globalization;
|
||||
using Khaemhat.Application.Parties;
|
||||
using Khaemhat.Application.Querying;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Application.Modules;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.ImportExport;
|
||||
|
||||
/// <summary>
|
||||
/// The customers or the suppliers (SPEC §12.12): each row is a party read by its code, or a new one, filled with the
|
||||
/// cells of the row, checked and saved by <see cref="PartyService"/>, so the import obeys the rules of the record
|
||||
/// (fiscal checks, automatic codes, duplicates). Empty cells keep the values of an existing party.
|
||||
/// </summary>
|
||||
/// <param name="kind">Customers or suppliers.</param>
|
||||
/// <param name="parties">The parties.</param>
|
||||
/// <param name="codes">The automatic codes.</param>
|
||||
/// <param name="autoFill">The places by postal code.</param>
|
||||
/// <param name="factory">Opens the company databases (codes of the tables).</param>
|
||||
/// <param name="permissions">Checks the permission to import.</param>
|
||||
public sealed class PartiesImportTarget(
|
||||
PartyKind kind, PartyService parties, CodeRuleService codes, AutoFillService autoFill, IUnitOfWorkFactory factory, PermissionService permissions)
|
||||
: RecordImportTarget<PartyRecord, PartiesImportTarget.State>
|
||||
{
|
||||
/// <summary>The words of <c>tipo_soggetto</c>, in the order of <see cref="SubjectType"/>.</summary>
|
||||
public static readonly IReadOnlyList<string> SubjectWords = ["impresa", "privato", "pa", "ue", "extra-ue", "forfettario"];
|
||||
|
||||
private static readonly ImportField[] Common =
|
||||
[
|
||||
new("codice", ImportFieldKind.Code, Aliases: ["cod", "codice_cliente", "codice_fornitore", "code"]),
|
||||
new("ragione_sociale", Aliases: ["denominazione", "nome_ditta", "ragione", "rag_sociale", "name"]),
|
||||
new("nome", Aliases: ["first_name"]),
|
||||
new("cognome", Aliases: ["last_name"]),
|
||||
new("tipo_soggetto", ImportFieldKind.Choice, Aliases: ["tipo", "soggetto"], Choices: SubjectWords),
|
||||
new("partita_iva", Aliases: ["p_iva", "piva", "partitaiva", "vat", "vat_number"]),
|
||||
new("codice_fiscale", Aliases: ["cf", "c_f", "cod_fiscale", "codicefiscale"]),
|
||||
new("rea", Aliases: ["numero_rea"]),
|
||||
new("indirizzo", Aliases: ["via", "address"]),
|
||||
new("civico", Aliases: ["numero_civico", "n_civico"]),
|
||||
new("cap", Aliases: ["c_a_p", "codice_postale", "postal_code"]),
|
||||
new("comune", Aliases: ["citta", "localita", "city"]),
|
||||
new("provincia", Aliases: ["prov", "pr", "sigla_provincia"]),
|
||||
new("nazione", Aliases: ["paese", "stato", "country", "codice_nazione"]),
|
||||
new("telefono", Aliases: ["tel", "phone"]),
|
||||
new("email", Aliases: ["e_mail", "mail"]),
|
||||
new("pec", Aliases: ["email_pec", "posta_certificata"]),
|
||||
new("sito", Aliases: ["sito_web", "web", "website"]),
|
||||
new("codice_destinatario", Aliases: ["codice_sdi", "sdi", "codice_univoco"]),
|
||||
new("categoria", ImportFieldKind.Code),
|
||||
];
|
||||
|
||||
private static readonly ImportField[] CustomerFields =
|
||||
[
|
||||
.. Common,
|
||||
new("agente", ImportFieldKind.Code, Aliases: ["venditore"]),
|
||||
new("pagamento", ImportFieldKind.Code, Aliases: ["condizioni_pagamento", "cod_pagamento"]),
|
||||
new("listino", ImportFieldKind.Code),
|
||||
new("sconto1", ImportFieldKind.Number, Aliases: ["sconto", "sconto_1"]),
|
||||
new("sconto2", ImportFieldKind.Number, Aliases: ["sconto_2"]),
|
||||
new("fido", ImportFieldKind.Number, Aliases: ["limite_fido", "fido_massimo"]),
|
||||
new("iban", Aliases: ["codice_iban"]),
|
||||
new("note", Aliases: ["annotazioni", "notes"]),
|
||||
];
|
||||
|
||||
private static readonly ImportField[] SupplierFields =
|
||||
[
|
||||
.. Common,
|
||||
new("pagamento", ImportFieldKind.Code, Aliases: ["condizioni_pagamento", "cod_pagamento"]),
|
||||
new("iban", Aliases: ["codice_iban"]),
|
||||
new("note", Aliases: ["annotazioni", "notes"]),
|
||||
];
|
||||
|
||||
private static readonly Dictionary<string, string> Columns = new(StringComparer.Ordinal)
|
||||
{
|
||||
["Code"] = "codice",
|
||||
["Name"] = "ragione_sociale",
|
||||
["FirstName"] = "nome",
|
||||
["LastName"] = "cognome",
|
||||
["SubjectType"] = "tipo_soggetto",
|
||||
["VatNumber"] = "partita_iva",
|
||||
["TaxCode"] = "codice_fiscale",
|
||||
["Rea"] = "rea",
|
||||
["Address"] = "indirizzo",
|
||||
["StreetNumber"] = "civico",
|
||||
["PostalCode"] = "cap",
|
||||
["City"] = "comune",
|
||||
["Province"] = "provincia",
|
||||
["CountryCode"] = "nazione",
|
||||
["Phone"] = "telefono",
|
||||
["Email"] = "email",
|
||||
["Pec"] = "pec",
|
||||
["Website"] = "sito",
|
||||
["CategoryId"] = "categoria",
|
||||
["SalespersonId"] = "agente",
|
||||
["Notes"] = "note",
|
||||
["Fiscal.RecipientCode"] = "codice_destinatario",
|
||||
["Sales.PaymentTermId"] = "pagamento",
|
||||
["Purchase.PaymentTermId"] = "pagamento",
|
||||
["Sales.PriceListId"] = "listino",
|
||||
["Sales.Discount1"] = "sconto1",
|
||||
["Sales.Discount2"] = "sconto2",
|
||||
["Sales.CreditLimit"] = "fido",
|
||||
};
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string Key => kind == PartyKind.Supplier ? "fornitori" : "clienti";
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string ModuleCode => ModuleCodes.Core;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string Permission => PartyService.WritePermission;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string ExportPermission => "parties.party.export";
|
||||
|
||||
/// <inheritdoc />
|
||||
public override IReadOnlyList<ImportField> Fields => kind == PartyKind.Supplier ? SupplierFields : CustomerFields;
|
||||
|
||||
private bool IsCustomer => kind != PartyKind.Supplier;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override async Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var state = await LoadAsync(context, ExportPermission, cancellationToken).ConfigureAwait(false);
|
||||
var archive = IsCustomer ? PartyArchive.Customers : PartyArchive.Suppliers;
|
||||
var rows = new List<IReadOnlyList<object?>>();
|
||||
var offset = 0;
|
||||
while (true)
|
||||
{
|
||||
var page = await parties.ListAsync(context.Actor, context.CompanyCode, archive, new ListQuery { Offset = offset, Limit = 500, Sort = [new ListSort("code")] },
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
foreach (var row in page.Items.Where(r => r.Kind == kind))
|
||||
{
|
||||
if (await parties.GetAsync(context.Actor, context.CompanyCode, row.Id, cancellationToken).ConfigureAwait(false) is { } record)
|
||||
{
|
||||
rows.Add(Cells(state, record));
|
||||
}
|
||||
}
|
||||
|
||||
offset += page.Items.Count;
|
||||
if (page.Items.Count == 0 || offset >= page.Total)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task<State> LoadAsync(ImportContext context, string permission, CancellationToken cancellationToken)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, permission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var all = (await uow.Repository<Party, long>().ListAsync(Query.For<Party>(), cancellationToken).ConfigureAwait(false)).Items;
|
||||
return new State
|
||||
{
|
||||
Kinds = all.GroupBy(p => p.Code, StringComparer.OrdinalIgnoreCase).ToDictionary(g => g.Key, g => (g.First().Id, g.First().Kind), StringComparer.OrdinalIgnoreCase),
|
||||
Categories = await CodeIndex.LoadAsync<PartyCategory>(uow, cancellationToken).ConfigureAwait(false),
|
||||
Salespeople = await CodeIndex.LoadAsync<Salesperson>(uow, cancellationToken).ConfigureAwait(false),
|
||||
PaymentTerms = await CodeIndex.LoadAsync<PaymentTerm>(uow, cancellationToken).ConfigureAwait(false),
|
||||
PriceLists = await CodeIndex.LoadAsync<PriceList>(uow, cancellationToken).ConfigureAwait(false),
|
||||
};
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override long? Existing(State state, string code, List<ImportMessage> messages)
|
||||
{
|
||||
if (!state.Kinds.TryGetValue(code, out var found))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (found.Kind != kind)
|
||||
{
|
||||
messages.Add(new("codice", ImportErrors.OtherKind, Value: code));
|
||||
return null;
|
||||
}
|
||||
|
||||
return found.Id;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override Task<PartyRecord?> OpenAsync(ImportContext context, long? id, CancellationToken cancellationToken) =>
|
||||
id is { } key
|
||||
? parties.GetAsync(context.Actor, context.CompanyCode, key, cancellationToken)
|
||||
: NewAsync(context, cancellationToken);
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task FillAsync(ImportContext context, State state, PartyRecord record, CellReader cells, bool isNew, CancellationToken cancellationToken)
|
||||
{
|
||||
var party = record.Party;
|
||||
if (isNew && cells.Text("codice") is { } code)
|
||||
{
|
||||
party.Code = code;
|
||||
}
|
||||
|
||||
if (cells.Choice(Fields.First(f => f.Key == "tipo_soggetto")) is { } subject)
|
||||
{
|
||||
party.SubjectType = (SubjectType)subject;
|
||||
}
|
||||
else if (isNew && !cells.Has("tipo_soggetto") && !cells.Has("ragione_sociale") && cells.Has("cognome"))
|
||||
{
|
||||
party.SubjectType = SubjectType.Person;
|
||||
}
|
||||
|
||||
Set(cells, "ragione_sociale", v => party.Name = v);
|
||||
Set(cells, "nome", v => party.FirstName = v);
|
||||
Set(cells, "cognome", v => party.LastName = v);
|
||||
if (party.SubjectType == SubjectType.Person && !cells.Has("ragione_sociale") && (cells.Has("nome") || cells.Has("cognome")))
|
||||
{
|
||||
party.Name = string.Empty;
|
||||
}
|
||||
|
||||
Set(cells, "partita_iva", v => party.VatNumber = v);
|
||||
Set(cells, "codice_fiscale", v => party.TaxCode = v.ToUpperInvariant());
|
||||
Set(cells, "rea", v => party.Rea = v);
|
||||
Set(cells, "indirizzo", v => party.Address = v);
|
||||
Set(cells, "civico", v => party.StreetNumber = v);
|
||||
Set(cells, "cap", v => party.PostalCode = v);
|
||||
Set(cells, "comune", v => party.City = v);
|
||||
Set(cells, "provincia", v => party.Province = v.ToUpperInvariant());
|
||||
Set(cells, "nazione", v => party.CountryCode = v.ToUpperInvariant());
|
||||
Set(cells, "telefono", v => party.Phone = v);
|
||||
Set(cells, "email", v => party.Email = v);
|
||||
Set(cells, "pec", v => party.Pec = v);
|
||||
Set(cells, "sito", v => party.Website = v);
|
||||
Set(cells, "codice_destinatario", v => record.Fiscal.RecipientCode = v.ToUpperInvariant());
|
||||
Set(cells, "note", v => party.Notes = v);
|
||||
if (cells.Code("categoria", state.Categories) is { } category)
|
||||
{
|
||||
party.CategoryId = category;
|
||||
}
|
||||
|
||||
if (cells.Code("pagamento", state.PaymentTerms) is { } payment)
|
||||
{
|
||||
if (IsCustomer)
|
||||
{
|
||||
record.Sales.PaymentTermId = payment;
|
||||
}
|
||||
else
|
||||
{
|
||||
record.Purchase.PaymentTermId = payment;
|
||||
}
|
||||
}
|
||||
|
||||
if (IsCustomer)
|
||||
{
|
||||
if (cells.Code("agente", state.Salespeople) is { } salesperson)
|
||||
{
|
||||
party.SalespersonId = salesperson;
|
||||
}
|
||||
|
||||
if (cells.Code("listino", state.PriceLists) is { } list)
|
||||
{
|
||||
record.Sales.PriceListId = list;
|
||||
}
|
||||
|
||||
record.Sales.Discount1 = cells.Number("sconto1") ?? record.Sales.Discount1;
|
||||
record.Sales.Discount2 = cells.Number("sconto2") ?? record.Sales.Discount2;
|
||||
record.Sales.CreditLimit = cells.Number("fido") ?? record.Sales.CreditLimit;
|
||||
}
|
||||
|
||||
if (cells.Text("iban") is { } text)
|
||||
{
|
||||
var iban = string.Concat(text.Where(c => !char.IsWhiteSpace(c))).ToUpperInvariant();
|
||||
if (!record.BankAccounts.Any(b => string.Equals(b.Iban, iban, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
record.BankAccounts.Add(new PartyBankAccount { Iban = iban, IsDefault = !record.BankAccounts.Any(b => b.IsDefault) });
|
||||
}
|
||||
}
|
||||
|
||||
if (context.Options.FillFromPostalCode && (cells.Has("cap") || cells.Has("comune")))
|
||||
{
|
||||
await FillPlaceAsync(context, state, party, cells, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task<IReadOnlyList<TableProblem>> ValidateAsync(ImportContext context, PartyRecord record, bool isNew, CancellationToken cancellationToken)
|
||||
{
|
||||
var problems = (await parties.ValidateAsync(context.Actor, context.CompanyCode, record, cancellationToken).ConfigureAwait(false)).ToList();
|
||||
if (isNew && record.Party.Code.Length > 0 && CodeRuleService.CheckManual(await RuleAsync(context, cancellationToken).ConfigureAwait(false), record.Party.Code) is { } manual)
|
||||
{
|
||||
problems.Add(new(nameof(Party.Code), manual));
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task<(string Code, long Id)> SaveAsync(ImportContext context, PartyRecord record, CancellationToken cancellationToken)
|
||||
{
|
||||
var saved = await parties.SaveAsync(context.Actor, context.CompanyCode, record, context.Options.VerifyVat, cancellationToken).ConfigureAwait(false);
|
||||
return (saved.Party.Code, saved.Party.Id);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string Label(ImportRow row)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(row);
|
||||
return row["codice"] ?? row["ragione_sociale"] ?? string.Join(' ', new[] { row["cognome"], row["nome"] }.Where(n => n is not null));
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Remember(State state, string code, long id)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(state);
|
||||
state.Kinds[code] = (id, kind);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string ColumnOf(string serviceField)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(serviceField);
|
||||
if (Columns.TryGetValue(serviceField, out var column))
|
||||
{
|
||||
return column;
|
||||
}
|
||||
|
||||
return serviceField.StartsWith("BankAccounts.", StringComparison.Ordinal) ? "iban" : string.Empty;
|
||||
}
|
||||
|
||||
private static void Set(CellReader cells, string key, Action<string> set)
|
||||
{
|
||||
if (cells.Text(key) is { } value)
|
||||
{
|
||||
set(value);
|
||||
}
|
||||
}
|
||||
|
||||
private object?[] Cells(State state, PartyRecord record)
|
||||
{
|
||||
var p = record.Party;
|
||||
var common = new object?[]
|
||||
{
|
||||
p.Code, p.SubjectType == SubjectType.Person ? null : p.Name, p.FirstName, p.LastName, SubjectWords[(int)p.SubjectType], p.VatNumber, p.TaxCode, p.Rea,
|
||||
p.Address, p.StreetNumber, p.PostalCode, p.City, p.Province, p.CountryCode, p.Phone, p.Email, p.Pec, p.Website, record.Fiscal.RecipientCode,
|
||||
state.Categories.CodeOf(p.CategoryId),
|
||||
};
|
||||
var iban = record.BankAccounts.OrderByDescending(b => b.IsDefault).FirstOrDefault()?.Iban;
|
||||
return IsCustomer
|
||||
?
|
||||
[
|
||||
.. common, state.Salespeople.CodeOf(p.SalespersonId), state.PaymentTerms.CodeOf(record.Sales.PaymentTermId), state.PriceLists.CodeOf(record.Sales.PriceListId),
|
||||
record.Sales.Discount1, record.Sales.Discount2, record.Sales.CreditLimit, iban, p.Notes,
|
||||
]
|
||||
: [.. common, state.PaymentTerms.CodeOf(record.Purchase.PaymentTermId), iban, p.Notes];
|
||||
}
|
||||
|
||||
private async Task<PartyRecord?> NewAsync(ImportContext context, CancellationToken cancellationToken) =>
|
||||
await parties.NewAsync(context.Actor, context.CompanyCode, kind, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
private async Task<CodeRule> RuleAsync(ImportContext context, CancellationToken cancellationToken) =>
|
||||
await codes.RuleAsync(context.CompanyCode, PartyService.CodeRuleOf(kind), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// City from the postal code and postal code from the city, only for Italian addresses and only when one place fits.
|
||||
private async Task FillPlaceAsync(ImportContext context, State state, Party party, CellReader cells, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!string.Equals(party.CountryCode, "IT", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (party.PostalCode is { } cap && string.IsNullOrWhiteSpace(party.City))
|
||||
{
|
||||
if (!state.ByPostalCode.TryGetValue(cap, out var places))
|
||||
{
|
||||
places = await autoFill.PlacesByPostalCodeAsync(context.Actor, context.CompanyCode, cap, cancellationToken).ConfigureAwait(false);
|
||||
state.ByPostalCode[cap] = places;
|
||||
}
|
||||
|
||||
if (places.Count == 1)
|
||||
{
|
||||
party.City = places[0].Name;
|
||||
party.Province ??= places[0].ProvinceCode;
|
||||
cells.Messages.Add(new("comune", ImportErrors.CityFilled, IsWarning: true, Value: places[0].Name));
|
||||
}
|
||||
}
|
||||
else if (party.City is { } city && string.IsNullOrWhiteSpace(party.PostalCode))
|
||||
{
|
||||
var key = city.ToUpper(CultureInfo.InvariantCulture);
|
||||
if (!state.ByName.TryGetValue(key, out var places))
|
||||
{
|
||||
places = await autoFill.PlacesByNameAsync(context.Actor, context.CompanyCode, city, cancellationToken).ConfigureAwait(false);
|
||||
state.ByName[key] = places;
|
||||
}
|
||||
|
||||
var exact = places.Where(p => string.Equals(p.Name, city, StringComparison.OrdinalIgnoreCase)).ToList();
|
||||
if (exact.Count == 1 && exact[0].PostalCode is { } postalCode)
|
||||
{
|
||||
party.PostalCode = postalCode;
|
||||
party.Province ??= exact[0].ProvinceCode;
|
||||
cells.Messages.Add(new("cap", ImportErrors.PostalCodeFilled, IsWarning: true, Value: postalCode));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What a check or an import of parties loads once.</summary>
|
||||
public sealed class State
|
||||
{
|
||||
/// <summary>The id and kind of every party by code.</summary>
|
||||
public required Dictionary<string, (long Id, PartyKind Kind)> Kinds { get; init; }
|
||||
|
||||
/// <summary>The categories.</summary>
|
||||
public required CodeIndex Categories { get; init; }
|
||||
|
||||
/// <summary>The salespeople.</summary>
|
||||
public required CodeIndex Salespeople { get; init; }
|
||||
|
||||
/// <summary>The payment terms.</summary>
|
||||
public required CodeIndex PaymentTerms { get; init; }
|
||||
|
||||
/// <summary>The price lists.</summary>
|
||||
public required CodeIndex PriceLists { get; init; }
|
||||
|
||||
/// <summary>Places found by postal code.</summary>
|
||||
public Dictionary<string, IReadOnlyList<PlaceSuggestion>> ByPostalCode { get; } = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Places found by name.</summary>
|
||||
public Dictionary<string, IReadOnlyList<PlaceSuggestion>> ByName { get; } = new(StringComparer.Ordinal);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
using Khaemhat.Application.Items;
|
||||
using Khaemhat.Application.Modules;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.ImportExport;
|
||||
|
||||
/// <summary>
|
||||
/// The prices of the lists and the net prices of the customers (SPEC §12.12): each row is the price of an item in a list
|
||||
/// or for a customer, valid from a day; the same item, list or customer and day replaces the price, another day adds a
|
||||
/// dated price as the price grid does. All rows are written by <see cref="PriceListService"/> in one transaction.
|
||||
/// </summary>
|
||||
/// <param name="prices">The price lists.</param>
|
||||
/// <param name="factory">Opens the company databases.</param>
|
||||
/// <param name="permissions">Checks the permission.</param>
|
||||
public sealed class PricesImportTarget(PriceListService prices, IUnitOfWorkFactory factory, PermissionService permissions) : IImportTarget
|
||||
{
|
||||
private static readonly ImportField[] PriceFields =
|
||||
[
|
||||
new("articolo", ImportFieldKind.Code, Required: true, Aliases: ["codice_articolo", "codice", "cod_articolo", "sku"]),
|
||||
new("listino", ImportFieldKind.Code, Aliases: ["codice_listino", "cod_listino"]),
|
||||
new("cliente", ImportFieldKind.Code, Aliases: ["codice_cliente", "cod_cliente"]),
|
||||
new("prezzo", ImportFieldKind.Number, Required: true, Aliases: ["prezzo_netto", "price"]),
|
||||
new("valido_dal", ImportFieldKind.Date, Aliases: ["validita", "data_inizio", "dal", "decorrenza"]),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Key => "listini";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ModuleCode => ModuleCodes.Core;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Permission => ItemService.WritePermission;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ExportPermission => ItemService.ReadPermission;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanApply => true;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanExport => true;
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<ImportField> Fields => PriceFields;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
|
||||
(await PlanAsync(context, rows, cancellationToken).ConfigureAwait(false)).Results;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
|
||||
{
|
||||
var plan = await PlanAsync(context, rows, cancellationToken).ConfigureAwait(false);
|
||||
if (plan.Edits.Count == 0)
|
||||
{
|
||||
return plan.Results;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await prices.SaveAsync(context.Actor, context.CompanyCode, [.. plan.Edits.Select(e => e.Edit)], cancellationToken).ConfigureAwait(false);
|
||||
return plan.Results;
|
||||
}
|
||||
catch (ValidationFailedException ex)
|
||||
{
|
||||
// The rows were checked already: an error here is a change made meanwhile; it goes on its row and nothing is written.
|
||||
var results = plan.Results.ToList();
|
||||
foreach (var (index, code) in ex.Errors.Select(TableErrors.Split))
|
||||
{
|
||||
var position = int.TryParse(index, out var i) && i >= 0 && i < plan.Edits.Count ? plan.Edits[i].Result : -1;
|
||||
if (position >= 0)
|
||||
{
|
||||
var row = results[position];
|
||||
results[position] = row with { Action = ImportAction.Skip, Messages = [.. row.Messages, new ImportMessage("prezzo", code)] };
|
||||
}
|
||||
}
|
||||
|
||||
return [.. results.Select(r => r.Outcome == ImportOutcome.Error ? r : r with { Action = ImportAction.Skip, Messages = [.. r.Messages, new ImportMessage(string.Empty, ImportErrors.WriteFailed)] })];
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, ExportPermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var items = new CodeIndex((await uow.Repository<Item, long>().ListAsync(Query.For<Item>(), cancellationToken).ConfigureAwait(false)).Items.Select(i => (i.Code, i.Id)));
|
||||
var parties = new CodeIndex((await uow.Repository<Party, long>().ListAsync(Query.For<Party>(), cancellationToken).ConfigureAwait(false)).Items.Select(p => (p.Code, p.Id)));
|
||||
var lists = await CodeIndex.LoadAsync<PriceList>(uow, cancellationToken).ConfigureAwait(false);
|
||||
var rows = (await uow.Repository<ItemPrice, long>().ListAsync(Query.For<ItemPrice>(), cancellationToken).ConfigureAwait(false)).Items;
|
||||
return
|
||||
[
|
||||
.. rows.Select(p => (IReadOnlyList<object?>)[items.CodeOf(p.ItemId), lists.CodeOf(p.PriceListId), parties.CodeOf(p.PartyId), p.Price, p.ValidFrom])
|
||||
.OrderBy(r => (string?)r[0], StringComparer.OrdinalIgnoreCase)
|
||||
.ThenBy(r => (string?)r[1] ?? "~" + (string?)r[2], StringComparer.OrdinalIgnoreCase)
|
||||
.ThenBy(r => (DateOnly?)r[4]),
|
||||
];
|
||||
}
|
||||
|
||||
private async Task<Plan> PlanAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
ArgumentNullException.ThrowIfNull(rows);
|
||||
var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var items = new CodeIndex((await uow.Repository<Item, long>().ListAsync(Query.For<Item>(), cancellationToken).ConfigureAwait(false)).Items.Select(i => (i.Code, i.Id)));
|
||||
var allParties = (await uow.Repository<Party, long>().ListAsync(Query.For<Party>(), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var customers = new CodeIndex(allParties.Where(p => p.IsCustomer).Select(p => (p.Code, p.Id)));
|
||||
var others = new HashSet<string>(allParties.Where(p => !p.IsCustomer).Select(p => p.Code), StringComparer.OrdinalIgnoreCase);
|
||||
var lists = await CodeIndex.LoadAsync<PriceList>(uow, cancellationToken).ConfigureAwait(false);
|
||||
var existing = (await uow.Repository<ItemPrice, long>().ListAsync(Query.For<ItemPrice>(), cancellationToken).ConfigureAwait(false)).Items
|
||||
.Select(p => (p.ItemId, p.PriceListId, p.PartyId, p.ValidFrom)).ToHashSet();
|
||||
|
||||
var seen = new HashSet<(long, long?, long?, DateOnly?)>();
|
||||
var results = new List<ImportRowResult>(rows.Count);
|
||||
var edits = new List<(PriceEdit Edit, int Result)>();
|
||||
foreach (var row in rows)
|
||||
{
|
||||
var messages = new List<ImportMessage>();
|
||||
var cells = new CellReader(row, messages);
|
||||
var item = cells.Code("articolo", items);
|
||||
long? list = null;
|
||||
long? party = null;
|
||||
if (cells.Has("listino") == cells.Has("cliente"))
|
||||
{
|
||||
messages.Add(new(cells.Has("listino") ? "cliente" : "listino", ImportErrors.PriceTarget));
|
||||
}
|
||||
else if (cells.Has("listino"))
|
||||
{
|
||||
list = cells.Code("listino", lists);
|
||||
}
|
||||
else if (row["cliente"] is { } customer && others.Contains(customer))
|
||||
{
|
||||
messages.Add(new("cliente", ImportErrors.OtherKind, Value: customer));
|
||||
}
|
||||
else
|
||||
{
|
||||
party = cells.Code("cliente", customers);
|
||||
}
|
||||
|
||||
var price = cells.Number("prezzo");
|
||||
if (price < 0)
|
||||
{
|
||||
messages.Add(new("prezzo", ItemService.NotNegative));
|
||||
}
|
||||
|
||||
var from = cells.Date("valido_dal");
|
||||
messages.AddRange(PriceFields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required)));
|
||||
var label = row["articolo"] ?? string.Empty;
|
||||
if (messages.Any(m => !m.IsWarning) || item is not { } itemId || price is not { } value)
|
||||
{
|
||||
results.Add(new(row.Line, label, ImportAction.Skip, messages));
|
||||
continue;
|
||||
}
|
||||
|
||||
var key = (itemId, list, party, from);
|
||||
if (!seen.Add(key))
|
||||
{
|
||||
messages.Add(new("articolo", ImportErrors.CodeRepeated, Value: label));
|
||||
results.Add(new(row.Line, label, ImportAction.Skip, messages));
|
||||
continue;
|
||||
}
|
||||
|
||||
var update = existing.Contains(key);
|
||||
if (update && context.Options.Existing == ExistingCodeAction.Skip)
|
||||
{
|
||||
results.Add(new(row.Line, label, ImportAction.Skip, [new("articolo", ImportErrors.CodeExists, IsWarning: true, Value: label)]));
|
||||
continue;
|
||||
}
|
||||
|
||||
edits.Add((new PriceEdit(itemId, list, party, value, from), results.Count));
|
||||
results.Add(new(row.Line, label, update ? ImportAction.Update : ImportAction.Create, messages));
|
||||
}
|
||||
|
||||
return new Plan(results, edits);
|
||||
}
|
||||
|
||||
private sealed record Plan(IReadOnlyList<ImportRowResult> Results, IReadOnlyList<(PriceEdit Edit, int Result)> Edits);
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Instance;
|
||||
|
||||
/// <summary>
|
||||
/// Reads and writes the preferences of a company as a whole (<c>company_settings</c>, SPEC §11.12): the default
|
||||
/// dashboard of each role today, the company options of the later modules tomorrow. Reading is open to the company
|
||||
/// code (the callers check what they show); writing needs <c>company.settings.write</c>.
|
||||
/// </summary>
|
||||
/// <param name="factory">Opens the databases.</param>
|
||||
/// <param name="permissions">Checks the permission to write.</param>
|
||||
public sealed class CompanySettingsService(IUnitOfWorkFactory factory, PermissionService permissions)
|
||||
{
|
||||
/// <summary>The permission to change the settings.</summary>
|
||||
public const string WritePermission = "company.settings.write";
|
||||
|
||||
/// <summary>The longest value accepted (layouts are JSON).</summary>
|
||||
public const int MaxValueLength = 64 * 1024;
|
||||
|
||||
/// <summary>Reads the settings of a company, all or those whose key starts with a prefix.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="prefix">The start of the keys, or <see langword="null"/> for all.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The values by key.</returns>
|
||||
public async Task<IReadOnlyDictionary<string, string?>> GetAllAsync(string companyCode, string? prefix = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(companyCode);
|
||||
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
|
||||
var rows = await ListAsync(unitOfWork, cancellationToken).ConfigureAwait(false);
|
||||
return rows.Where(r => prefix is null || r.Key.StartsWith(prefix, StringComparison.Ordinal))
|
||||
.ToDictionary(r => r.Key, r => r.Value, StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>Reads one setting.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The value, or <see langword="null"/>.</returns>
|
||||
public async Task<string?> GetAsync(string companyCode, string key, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(key);
|
||||
var all = await GetAllAsync(companyCode, key, cancellationToken).ConfigureAwait(false);
|
||||
return all.TryGetValue(key, out var value) ? value : null;
|
||||
}
|
||||
|
||||
/// <summary>Writes one setting; <see langword="null"/> removes it.</summary>
|
||||
/// <param name="actor">Who writes: needs <see cref="WritePermission"/> in that company.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <param name="value">The value.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public Task SetAsync(Actor actor, string companyCode, string key, string? value, CancellationToken cancellationToken = default) =>
|
||||
SetManyAsync(actor, companyCode, new Dictionary<string, string?>(StringComparer.Ordinal) { [key] = value }, cancellationToken);
|
||||
|
||||
/// <summary>Writes several settings in one transaction; <see langword="null"/> values remove the key.</summary>
|
||||
/// <param name="actor">Who writes: needs <see cref="WritePermission"/> in that company.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="values">The values by key.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
/// <exception cref="AccessDeniedException">The actor may not change this company's settings.</exception>
|
||||
public async Task SetManyAsync(Actor actor, string companyCode, IReadOnlyDictionary<string, string?> values, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(companyCode);
|
||||
ArgumentNullException.ThrowIfNull(values);
|
||||
if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, companyCode, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new AccessDeniedException("Settings of another company.");
|
||||
}
|
||||
|
||||
await permissions.DemandAsync(actor, WritePermission, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var (key, value) in values)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(key) || key.Length > 200)
|
||||
{
|
||||
throw new ValidationFailedException("settings.key_invalid");
|
||||
}
|
||||
|
||||
if (value is { Length: > MaxValueLength })
|
||||
{
|
||||
throw new ValidationFailedException("settings.value_too_long");
|
||||
}
|
||||
}
|
||||
|
||||
if (values.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
|
||||
await unitOfWork.InTransactionAsync(ct => WriteAsync(unitOfWork, values, ct), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static async Task<IReadOnlyList<CompanySetting>> ListAsync(IUnitOfWork unitOfWork, CancellationToken cancellationToken) =>
|
||||
(await unitOfWork.Repository<CompanySetting, long>().ListAsync(Query.For<CompanySetting>(), cancellationToken).ConfigureAwait(false)).Items;
|
||||
|
||||
private static async Task WriteAsync(IUnitOfWork unitOfWork, IReadOnlyDictionary<string, string?> values, CancellationToken cancellationToken)
|
||||
{
|
||||
var repository = unitOfWork.Repository<CompanySetting, long>();
|
||||
var existing = (await ListAsync(unitOfWork, cancellationToken).ConfigureAwait(false)).ToDictionary(r => r.Key, StringComparer.Ordinal);
|
||||
foreach (var (key, value) in values)
|
||||
{
|
||||
if (existing.TryGetValue(key, out var row))
|
||||
{
|
||||
if (value is null)
|
||||
{
|
||||
await repository.DeleteAsync(row.Id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else if (!string.Equals(row.Value, value, StringComparison.Ordinal))
|
||||
{
|
||||
row.Value = value;
|
||||
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
else if (value is not null)
|
||||
{
|
||||
await repository.InsertAsync(new CompanySetting { Key = key, Value = value }, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,885 @@
|
||||
using System.Data.Common;
|
||||
using Khaemhat.Application.Audit;
|
||||
using Khaemhat.Application.Querying;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Core.Validation;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Items;
|
||||
|
||||
/// <summary>An item with all its details, as the record screen edits it (mockup 017).</summary>
|
||||
public sealed class ItemRecord
|
||||
{
|
||||
/// <summary>The item.</summary>
|
||||
public Item Item { get; set; } = new();
|
||||
|
||||
/// <summary>The alternative units.</summary>
|
||||
public List<ItemUnit> Units { get; set; } = [];
|
||||
|
||||
/// <summary>The alternative codes.</summary>
|
||||
public List<ItemBarcode> Barcodes { get; set; } = [];
|
||||
|
||||
/// <summary>The prices: of the price lists and net of the customers, each with its validity.</summary>
|
||||
public List<ItemPrice> Prices { get; set; } = [];
|
||||
|
||||
/// <summary>The suppliers.</summary>
|
||||
public List<ItemSupplier> Suppliers { get; set; } = [];
|
||||
|
||||
/// <summary>The substitutes.</summary>
|
||||
public List<ItemSubstitute> Substitutes { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>A row of the items radar.</summary>
|
||||
/// <param name="Id">The item.</param>
|
||||
/// <param name="Code">The code.</param>
|
||||
/// <param name="Description">The description.</param>
|
||||
/// <param name="Kind">What the item is.</param>
|
||||
/// <param name="CategoryId">The category.</param>
|
||||
/// <param name="UnitOfMeasureId">The base unit.</param>
|
||||
/// <param name="Barcode">The main bar code.</param>
|
||||
/// <param name="Brand">The brand.</param>
|
||||
/// <param name="Stocked">Kept in stock.</param>
|
||||
/// <param name="AverageCost">The average cost, only for who can see costs.</param>
|
||||
/// <param name="Disabled">Disabled.</param>
|
||||
public sealed record ItemRow(
|
||||
long Id, string Code, string Description, ItemKind Kind, long? CategoryId, long? UnitOfMeasureId, string? Barcode, string? Brand, bool Stocked,
|
||||
decimal? AverageCost, bool Disabled)
|
||||
{
|
||||
/// <summary>The price of the base list today.</summary>
|
||||
public decimal? BasePrice { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>What happened to an item asked to be deleted.</summary>
|
||||
public enum ItemDeleteOutcome
|
||||
{
|
||||
/// <summary>Deleted.</summary>
|
||||
Deleted = 0,
|
||||
|
||||
/// <summary>Used by other data: disabled instead.</summary>
|
||||
Disabled = 1,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Items (SPEC §11.2, mockup 017, ADR 0030): list, search by code, description, bar codes and codes of the parties,
|
||||
/// record with units, codes, prices, suppliers and substitutes, checks, automatic code per category, history.
|
||||
/// </summary>
|
||||
/// <remarks>Permissions <c>items.item.read</c>, <c>write</c>, <c>delete</c>; costs only with <c>items.cost.read</c>.</remarks>
|
||||
public sealed class ItemService
|
||||
{
|
||||
/// <summary>Permission to read items and price lists.</summary>
|
||||
public const string ReadPermission = "items.item.read";
|
||||
|
||||
/// <summary>Permission to write items and price lists.</summary>
|
||||
public const string WritePermission = "items.item.write";
|
||||
|
||||
/// <summary>Permission to delete items.</summary>
|
||||
public const string DeletePermission = "items.item.delete";
|
||||
|
||||
/// <summary>Permission to see costs and margins.</summary>
|
||||
public const string CostPermission = "items.cost.read";
|
||||
|
||||
/// <summary>The entity of the attachments of an item.</summary>
|
||||
public const string Entity = "items.item";
|
||||
|
||||
/// <summary>The code rule of the items (ADR 0027).</summary>
|
||||
public const string CodeRule = "items";
|
||||
|
||||
/// <summary>Error: no description.</summary>
|
||||
public const string DescriptionRequired = "items.description.required";
|
||||
|
||||
/// <summary>Error: the code is used by another item.</summary>
|
||||
public const string CodeDuplicate = "items.code.duplicate";
|
||||
|
||||
/// <summary>Error: the code mask needs the category.</summary>
|
||||
public const string CategoryRequired = "items.category.required";
|
||||
|
||||
/// <summary>Error: the bar code has a wrong check digit.</summary>
|
||||
public const string BarcodeInvalid = "items.barcode.invalid";
|
||||
|
||||
/// <summary>Error or warning (by preference): another item has the bar code.</summary>
|
||||
public const string BarcodeDuplicate = "items.barcode.duplicate";
|
||||
|
||||
/// <summary>Error: the NC8 code is not eight digits.</summary>
|
||||
public const string CustomsCodeInvalid = "items.customs-code.invalid";
|
||||
|
||||
/// <summary>Error: a negative quantity, weight, price or cost.</summary>
|
||||
public const string NotNegative = "items.value.negative";
|
||||
|
||||
/// <summary>Error: the factor of a unit is not above zero.</summary>
|
||||
public const string FactorInvalid = "items.factor.invalid";
|
||||
|
||||
/// <summary>Error: a unit is listed twice, or is the base unit.</summary>
|
||||
public const string UnitDuplicate = "items.unit.duplicate";
|
||||
|
||||
/// <summary>Error: a required detail field is empty.</summary>
|
||||
public const string DetailRequired = "items.detail.required";
|
||||
|
||||
/// <summary>Error: the party of a supplier row is not a supplier.</summary>
|
||||
public const string SupplierInvalid = "items.supplier.invalid";
|
||||
|
||||
/// <summary>Error: a supplier or a substitute is listed twice.</summary>
|
||||
public const string DetailDuplicate = "items.detail.duplicate";
|
||||
|
||||
/// <summary>Error: an item cannot be its own substitute.</summary>
|
||||
public const string SubstituteSelf = "items.substitute.self";
|
||||
|
||||
/// <summary>Error: a price is neither of a price list nor of a customer, or of both.</summary>
|
||||
public const string PriceTarget = "items.price.target";
|
||||
|
||||
/// <summary>Error: a net price is for a customer only.</summary>
|
||||
public const string PriceParty = "items.price.party";
|
||||
|
||||
/// <summary>Error: two prices of the same list or customer start on the same day.</summary>
|
||||
public const string PriceDuplicate = "items.price.duplicate";
|
||||
|
||||
/// <summary>Error: the code of a party is used for another item.</summary>
|
||||
public const string PartyCodeDuplicate = "items.party-code.duplicate";
|
||||
|
||||
/// <summary>Error: the item does not exist.</summary>
|
||||
public const string NotFound = "items.not-found";
|
||||
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly AuditTrail _audit;
|
||||
private readonly CodeRuleService _codes;
|
||||
private readonly TimeProvider _clock;
|
||||
|
||||
/// <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="codes">The automatic codes.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
public ItemService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, CodeRuleService codes, TimeProvider clock)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(audit);
|
||||
ArgumentNullException.ThrowIfNull(codes);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
_audit = audit;
|
||||
_codes = codes;
|
||||
_clock = clock;
|
||||
}
|
||||
|
||||
/// <summary>The fields of the items radar.</summary>
|
||||
public static ListFields<Item> Fields { get; } = new ListFields<Item>()
|
||||
.Add("code", i => i.Code, searchable: true)
|
||||
.Add("description", i => i.Description, searchable: true)
|
||||
.Add("barcode", i => i.Barcode, searchable: true)
|
||||
.Add("brand", i => i.Brand, searchable: true)
|
||||
.Add("manufacturer", i => i.Manufacturer, searchable: true)
|
||||
.Add("kind", i => i.Kind)
|
||||
.Add("category", i => i.CategoryId)
|
||||
.Add("unit", i => i.UnitOfMeasureId)
|
||||
.Add("stocked", i => i.Stocked)
|
||||
.Add("disabled", i => i.Disabled)
|
||||
.OrderByDefault(new ListSort("code"));
|
||||
|
||||
/// <summary>The items for the radar, with the price of the base list today.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="query">Search, filters, sort, page.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The page.</returns>
|
||||
public async Task<ListPage<ItemRow>> ListAsync(Actor actor, string companyCode, ListQuery query, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(query);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
var costs = await CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var page = await uow.Repository<Item, long>().ListAsync(Fields.Apply(Query.For<Item>(), query), cancellationToken).ConfigureAwait(false);
|
||||
var book = await BookAsync(uow, [.. page.Items.Select(i => i.Id)], cancellationToken).ConfigureAwait(false);
|
||||
var today = Today();
|
||||
IReadOnlyList<ItemRow> rows =
|
||||
[
|
||||
.. page.Items.Select(i => RowOf(i, costs) with
|
||||
{
|
||||
BasePrice = book.Base is { } baseList ? book.ListPrice(i.Id, baseList.Id, today).Price : i.Price,
|
||||
}),
|
||||
];
|
||||
return new ListPage<ItemRow>(rows, page.TotalCount, new Dictionary<string, decimal>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The active items matching a text, for the lookups: code, description, bar code and brand, or exactly an
|
||||
/// alternative code or the code a party uses for the item.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="text">The text.</param>
|
||||
/// <param name="partyId">The party of the document, whose codes count too.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>At most 20 items.</returns>
|
||||
public async Task<IReadOnlyList<ItemRow>> SearchAsync(Actor actor, string companyCode, string? text, long? partyId = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
var costs = await CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var items = uow.Repository<Item, long>();
|
||||
var page = await items.ListAsync(
|
||||
Fields.Apply(Query.For<Item>(), new ListQuery { Search = text, Filters = [ListFilter.Of("disabled", ListFilterOperator.Equals, "false")], Limit = 20 }),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
var found = page.Items.ToList();
|
||||
var exact = text?.Trim();
|
||||
if (!string.IsNullOrEmpty(exact))
|
||||
{
|
||||
var ids = (await uow.Repository<ItemBarcode, long>().ListAsync(Query.For<ItemBarcode>().Where(b => b.Code == exact), cancellationToken).ConfigureAwait(false))
|
||||
.Items.Select(b => b.ItemId).ToList();
|
||||
if (partyId is { } party)
|
||||
{
|
||||
ids.AddRange((await uow.Repository<PartyItemCode, long>().ListAsync(
|
||||
Query.For<PartyItemCode>().Where(c => c.PartyId == party && c.Code == exact), cancellationToken).ConfigureAwait(false)).Items.Select(c => c.ItemId));
|
||||
}
|
||||
|
||||
foreach (var id in ids.Distinct().Where(id => found.All(i => i.Id != id)))
|
||||
{
|
||||
if (await items.GetAsync(id, cancellationToken).ConfigureAwait(false) is { Disabled: false } item)
|
||||
{
|
||||
found.Insert(0, item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [.. found.Take(20).Select(i => RowOf(i, costs))];
|
||||
}
|
||||
|
||||
/// <summary>An item with its details; costs hidden without <c>items.cost.read</c>.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The item.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The record, or none.</returns>
|
||||
public async Task<ItemRecord?> GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
var costs = await CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var record = await LoadAsync(uow, id, cancellationToken).ConfigureAwait(false);
|
||||
if (record is not null && !costs)
|
||||
{
|
||||
HideCosts(record);
|
||||
}
|
||||
|
||||
return record;
|
||||
}
|
||||
|
||||
/// <summary>A new item with the usual values: goods kept in stock, unit PZ, VAT 22, the default warehouse.</summary>
|
||||
/// <param name="actor">Who asks.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The record to fill.</returns>
|
||||
public async Task<ItemRecord> NewAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var unit = await uow.Repository<UnitOfMeasure, long>().FindAsync(Query.For<UnitOfMeasure>().Where(u => u.Code == "PZ" && !u.Disabled), cancellationToken).ConfigureAwait(false);
|
||||
var tax = await uow.Repository<TaxCode, long>().FindAsync(Query.For<TaxCode>().Where(t => t.Code == "22" && !t.Disabled), cancellationToken).ConfigureAwait(false);
|
||||
var warehouse = await uow.Repository<Warehouse, long>().FindAsync(Query.For<Warehouse>().Where(w => w.IsDefault && !w.Disabled), cancellationToken).ConfigureAwait(false);
|
||||
return new ItemRecord
|
||||
{
|
||||
Item = new Item
|
||||
{
|
||||
Kind = ItemKind.Goods, Stocked = true, UnitOfMeasureId = unit?.Id, SalesTaxCodeId = tax?.Id, PurchaseTaxCodeId = tax?.Id, WarehouseId = warehouse?.Id,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Checks a record without saving it (also cleans it, as the save would).</summary>
|
||||
/// <param name="actor">Who asks.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="record">The record.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>Errors and warnings.</returns>
|
||||
public async Task<IReadOnlyList<TableProblem>> ValidateAsync(Actor actor, string companyCode, ItemRecord record, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(record);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
var rule = await _codes.RuleAsync(company, CodeRule, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return await CheckAsync(uow, rule, record, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves an item and its details in one transaction; a new item gets its code from the rule of the items
|
||||
/// (<c>{categoria}</c> is the code of its category). Without <c>items.cost.read</c> the costs stay as they were.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who saves.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="record">The record.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The record as saved.</returns>
|
||||
/// <exception cref="ValidationFailedException">With the errors (<c>field:code</c>).</exception>
|
||||
public async Task<ItemRecord> SaveAsync(Actor actor, string companyCode, ItemRecord record, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(record);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
|
||||
var costs = await CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false);
|
||||
var rule = await _codes.RuleAsync(company, CodeRule, cancellationToken).ConfigureAwait(false);
|
||||
var item = record.Item;
|
||||
long id;
|
||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var before = item.Id == 0 ? null : await LoadAsync(uow, item.Id, cancellationToken).ConfigureAwait(false) ?? throw new ValidationFailedException([":" + NotFound]);
|
||||
|
||||
// The last and average costs come from the receipts (M6); the standard cost only from who sees costs.
|
||||
item.LastCost = before?.Item.LastCost;
|
||||
item.AverageCost = before?.Item.AverageCost;
|
||||
if (!costs)
|
||||
{
|
||||
item.StandardCost = before?.Item.StandardCost;
|
||||
}
|
||||
|
||||
var problems = (await CheckAsync(uow, rule, record, cancellationToken).ConfigureAwait(false)).Where(p => !p.IsWarning).Select(p => p.Field + ":" + p.Code).ToList();
|
||||
if (problems.Count > 0)
|
||||
{
|
||||
throw new ValidationFailedException(problems);
|
||||
}
|
||||
|
||||
if (item.Code.Length == 0)
|
||||
{
|
||||
var category = item.CategoryId is { } categoryId ? (await uow.Repository<ItemCategory, long>().GetAsync(categoryId, cancellationToken).ConfigureAwait(false))?.Code : null;
|
||||
item.Code = await CodeRuleService.AssignAsync(uow, rule, Today(), category, (c, ct) => TakenAsync(uow, c, ct), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
id = await WriteAsync(uow, record, before, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return await GetAsync(actor, company, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
|
||||
}
|
||||
|
||||
/// <summary>Disables or enables items (radar selection).</summary>
|
||||
/// <param name="actor">Who does it.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="ids">The items.</param>
|
||||
/// <param name="disabled">Disable or enable.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>How many changed.</returns>
|
||||
public async Task<int> SetDisabledAsync(Actor actor, string companyCode, IEnumerable<long> ids, bool disabled, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(ids);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var repository = uow.Repository<Item, long>();
|
||||
var changed = 0;
|
||||
foreach (var id in ids.Distinct())
|
||||
{
|
||||
if (await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } item && item.Disabled != disabled)
|
||||
{
|
||||
var before = Clone(item);
|
||||
item.Disabled = disabled;
|
||||
await repository.UpdateAsync(item, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Update, id, before, item, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
changed++;
|
||||
}
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return changed;
|
||||
}
|
||||
|
||||
/// <summary>Deletes an item; one used by other data (a substitute, documents from M5) is disabled instead.</summary>
|
||||
/// <param name="actor">Who deletes.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The item.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>What happened.</returns>
|
||||
public async Task<ItemDeleteOutcome> DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, DeletePermission, cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var before = await uow.Repository<Item, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
|
||||
await uow.Repository<Item, long>().DeleteAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Delete, id, before, null, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return ItemDeleteOutcome.Deleted;
|
||||
}
|
||||
catch (DbException)
|
||||
{
|
||||
await SetDisabledAsync(actor, company, [id], true, cancellationToken).ConfigureAwait(false);
|
||||
return ItemDeleteOutcome.Disabled;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The history of an item and of its prices, newest first.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The item.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The changes.</returns>
|
||||
public async Task<IReadOnlyList<AuditEntry>> HistoryAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var key = id.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
var entries = new List<AuditEntry>();
|
||||
foreach (var entity in new[] { nameof(Item), nameof(ItemPrice) })
|
||||
{
|
||||
entries.AddRange(await AuditTrail.HistoryAsync(uow, entity, key, cancellationToken).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
return [.. entries.OrderByDescending(e => e.At).ThenByDescending(e => e.Id)];
|
||||
}
|
||||
|
||||
/// <summary>The rows of some items, for the lookups that show them by id.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="ids">The items.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rows found.</returns>
|
||||
public async Task<IReadOnlyList<ItemRow>> RowsAsync(Actor actor, string companyCode, IEnumerable<long> ids, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(ids);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
var costs = await CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false);
|
||||
long[] wanted = [.. ids.Distinct()];
|
||||
if (wanted.Length == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return [.. (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => wanted.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items
|
||||
.Select(i => RowOf(i, costs))];
|
||||
}
|
||||
|
||||
/// <summary>Checks the codes of a party: code and item required, no code twice.</summary>
|
||||
/// <param name="codes">The codes.</param>
|
||||
/// <returns>The errors.</returns>
|
||||
public static IReadOnlyList<TableProblem> CheckPartyCodes(IReadOnlyList<PartyItemCode> codes)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(codes);
|
||||
var problems = new List<TableProblem>();
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
for (var i = 0; i < codes.Count; i++)
|
||||
{
|
||||
var code = codes[i];
|
||||
code.Code = code.Code.Trim();
|
||||
code.Description = Clean(code.Description);
|
||||
if (code.Code.Length == 0)
|
||||
{
|
||||
problems.Add(new($"ItemCodes.{i}.{nameof(PartyItemCode.Code)}", DetailRequired));
|
||||
}
|
||||
else if (!seen.Add(code.Code))
|
||||
{
|
||||
problems.Add(new($"ItemCodes.{i}.{nameof(PartyItemCode.Code)}", PartyCodeDuplicate));
|
||||
}
|
||||
|
||||
if (code.ItemId == 0)
|
||||
{
|
||||
problems.Add(new($"ItemCodes.{i}.{nameof(PartyItemCode.ItemId)}", DetailRequired));
|
||||
}
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
|
||||
/// <summary>Whether an actor sees costs and margins.</summary>
|
||||
/// <param name="actor">The actor.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>Whether costs are visible.</returns>
|
||||
public async Task<bool> CanSeeCostsAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
return (actor.IsInstanceAccount || string.Equals(actor.CompanyCode, CompanyCodes.Normalize(companyCode), StringComparison.Ordinal))
|
||||
&& (await _permissions.CheckAsync(actor, CostPermission, cancellationToken).ConfigureAwait(false)).Allowed;
|
||||
}
|
||||
|
||||
/// <summary>The prices of some items and all the price lists, in memory.</summary>
|
||||
/// <param name="uow">The unit of work of the company.</param>
|
||||
/// <param name="itemIds">The items.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The book.</returns>
|
||||
public static async Task<PriceBook> BookAsync(IUnitOfWork uow, IReadOnlyList<long> itemIds, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(uow);
|
||||
ArgumentNullException.ThrowIfNull(itemIds);
|
||||
var lists = (await uow.Repository<PriceList, long>().ListAsync(Query.For<PriceList>(), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var prices = new List<ItemPrice>();
|
||||
foreach (var chunk in itemIds.Distinct().Chunk(500))
|
||||
{
|
||||
long[] ids = [.. chunk];
|
||||
prices.AddRange((await uow.Repository<ItemPrice, long>().ListAsync(Query.For<ItemPrice>().Where(p => ids.Contains(p.ItemId)), cancellationToken).ConfigureAwait(false)).Items);
|
||||
}
|
||||
|
||||
return new PriceBook(lists, prices);
|
||||
}
|
||||
|
||||
private DateOnly Today() => DateOnly.FromDateTime(_clock.GetLocalNow().DateTime);
|
||||
|
||||
private static ItemRow RowOf(Item i, bool costs) =>
|
||||
new(i.Id, i.Code, i.Description, i.Kind, i.CategoryId, i.UnitOfMeasureId, i.Barcode, i.Brand, i.Stocked, costs ? i.AverageCost : null, i.Disabled);
|
||||
|
||||
private static void HideCosts(ItemRecord record)
|
||||
{
|
||||
record.Item.StandardCost = null;
|
||||
record.Item.LastCost = null;
|
||||
record.Item.AverageCost = null;
|
||||
}
|
||||
|
||||
private static async Task<bool> TakenAsync(IUnitOfWork uow, string code, CancellationToken cancellationToken) =>
|
||||
await uow.Repository<Item, long>().CountAsync(Query.For<Item>().Where(i => i.Code == code), cancellationToken).ConfigureAwait(false) > 0;
|
||||
|
||||
private static async Task<ItemRecord?> LoadAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
|
||||
{
|
||||
if (await uow.Repository<Item, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } item)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new ItemRecord
|
||||
{
|
||||
Item = item,
|
||||
Units = [.. (await uow.Repository<ItemUnit, long>().ListAsync(Query.For<ItemUnit>().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items],
|
||||
Barcodes = [.. (await uow.Repository<ItemBarcode, long>().ListAsync(Query.For<ItemBarcode>().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items],
|
||||
Prices = [.. (await uow.Repository<ItemPrice, long>().ListAsync(Query.For<ItemPrice>().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items],
|
||||
Suppliers = [.. (await uow.Repository<ItemSupplier, long>().ListAsync(Query.For<ItemSupplier>().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items],
|
||||
Substitutes = [.. (await uow.Repository<ItemSubstitute, long>().ListAsync(Query.For<ItemSubstitute>().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items],
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<long> WriteAsync(IUnitOfWork uow, ItemRecord record, ItemRecord? before, string userName, CancellationToken cancellationToken)
|
||||
{
|
||||
var item = record.Item;
|
||||
var items = uow.Repository<Item, long>();
|
||||
if (before is null)
|
||||
{
|
||||
item.Id = await items.InsertAsync(item, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync<Item>(uow, AuditAction.Insert, item.Id, null, item, userName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await items.UpdateAsync(item, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Update, item.Id, before.Item, item, userName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var id = item.Id;
|
||||
await ReplaceAsync(uow, record.Units, before?.Units ?? [], u => u.ItemId = id, cancellationToken).ConfigureAwait(false);
|
||||
await ReplaceAsync(uow, record.Barcodes, before?.Barcodes ?? [], u => u.ItemId = id, cancellationToken).ConfigureAwait(false);
|
||||
await ReplaceAsync(uow, record.Suppliers, before?.Suppliers ?? [], u => u.ItemId = id, cancellationToken).ConfigureAwait(false);
|
||||
await ReplaceAsync(uow, record.Substitutes, before?.Substitutes ?? [], u => u.ItemId = id, cancellationToken).ConfigureAwait(false);
|
||||
await ReplaceAsync(uow, record.Prices, before?.Prices ?? [], u => u.ItemId = id, cancellationToken, async (old, row, ct) =>
|
||||
await _audit.RecordAsync(uow, old is null ? AuditAction.Insert : row is null ? AuditAction.Delete : AuditAction.Update, id, old, row, userName, ct).ConfigureAwait(false))
|
||||
.ConfigureAwait(false);
|
||||
return id;
|
||||
}
|
||||
|
||||
// The lists: rows removed are deleted, rows kept are updated, new rows inserted; the prices are written in the history.
|
||||
private static async Task ReplaceAsync<T>(
|
||||
IUnitOfWork uow, List<T> rows, List<T> before, Action<T> link, CancellationToken cancellationToken, Func<T?, T?, CancellationToken, Task>? audit = null)
|
||||
where T : Core.Entities.Entity<long>, new()
|
||||
{
|
||||
var repository = uow.Repository<T, long>();
|
||||
var kept = rows.Where(r => r.Id != 0).Select(r => r.Id).ToHashSet();
|
||||
foreach (var old in before.Where(b => !kept.Contains(b.Id)))
|
||||
{
|
||||
await repository.DeleteAsync(old.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (audit is not null)
|
||||
{
|
||||
await audit(old, null, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
var previous = before.ToDictionary(b => b.Id);
|
||||
foreach (var row in rows)
|
||||
{
|
||||
link(row);
|
||||
if (row.Id != 0 && previous.TryGetValue(row.Id, out var old))
|
||||
{
|
||||
row.RowVersion = old.RowVersion;
|
||||
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
|
||||
if (audit is not null)
|
||||
{
|
||||
await audit(old, row, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false);
|
||||
if (audit is not null)
|
||||
{
|
||||
await audit(null, row, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<IReadOnlyList<TableProblem>> CheckAsync(IUnitOfWork uow, CodeRule rule, ItemRecord record, CancellationToken cancellationToken)
|
||||
{
|
||||
var problems = new List<TableProblem>();
|
||||
var item = record.Item;
|
||||
Normalize(item);
|
||||
if (item.Description.Length == 0)
|
||||
{
|
||||
problems.Add(new(nameof(Item.Description), DescriptionRequired));
|
||||
}
|
||||
|
||||
var id = item.Id;
|
||||
if (item.Code.Length > 0)
|
||||
{
|
||||
var code = item.Code;
|
||||
if (await uow.Repository<Item, long>().CountAsync(Query.For<Item>().Where(i => i.Code == code && i.Id != id), cancellationToken).ConfigureAwait(false) > 0)
|
||||
{
|
||||
problems.Add(new(nameof(Item.Code), CodeDuplicate));
|
||||
}
|
||||
}
|
||||
else if (item.CategoryId is null && CodeMask.TryParse(rule.Mask, out var mask, out _) && mask!.UsesCategory)
|
||||
{
|
||||
problems.Add(new(nameof(Item.CategoryId), CategoryRequired));
|
||||
}
|
||||
|
||||
if (item.Barcode is { } barcode)
|
||||
{
|
||||
if (!EanValidator.IsValid(barcode))
|
||||
{
|
||||
problems.Add(new(nameof(Item.Barcode), BarcodeInvalid));
|
||||
}
|
||||
else if (await BarcodeUsedAsync(uow, barcode, id, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
problems.Add(new(nameof(Item.Barcode), BarcodeDuplicate, IsWarning: !rule.UniqueBarcode));
|
||||
}
|
||||
}
|
||||
|
||||
if (item.CustomsCode is { } customs && (customs.Length != 8 || !customs.All(char.IsAsciiDigit)))
|
||||
{
|
||||
problems.Add(new(nameof(Item.CustomsCode), CustomsCodeInvalid));
|
||||
}
|
||||
|
||||
foreach (var (value, field) in new (decimal?, string)[]
|
||||
{
|
||||
(item.NetWeight, nameof(Item.NetWeight)), (item.GrossWeight, nameof(Item.GrossWeight)), (item.MinimumStock, nameof(Item.MinimumStock)),
|
||||
(item.ReorderPoint, nameof(Item.ReorderPoint)), (item.ReorderLot, nameof(Item.ReorderLot)), (item.Price, nameof(Item.Price)),
|
||||
(item.StandardCost, nameof(Item.StandardCost)),
|
||||
})
|
||||
{
|
||||
if (value < 0)
|
||||
{
|
||||
problems.Add(new(field, NotNegative));
|
||||
}
|
||||
}
|
||||
|
||||
CheckUnits(record, problems);
|
||||
CheckBarcodes(record, problems);
|
||||
await CheckPricesAsync(uow, record, problems, cancellationToken).ConfigureAwait(false);
|
||||
await CheckSuppliersAsync(uow, record, problems, cancellationToken).ConfigureAwait(false);
|
||||
CheckSubstitutes(record, problems);
|
||||
return problems;
|
||||
}
|
||||
|
||||
private static void Normalize(Item item)
|
||||
{
|
||||
item.Code = item.Code.Trim();
|
||||
item.Description = item.Description.Trim();
|
||||
item.ExtendedDescription = Clean(item.ExtendedDescription);
|
||||
item.Barcode = Clean(item.Barcode);
|
||||
item.CustomsCode = Clean(item.CustomsCode)?.Replace(" ", string.Empty, StringComparison.Ordinal).Replace(".", string.Empty, StringComparison.Ordinal);
|
||||
item.Manufacturer = Clean(item.Manufacturer);
|
||||
item.Brand = Clean(item.Brand);
|
||||
item.RevenueAccountCode = Clean(item.RevenueAccountCode);
|
||||
item.CostAccountCode = Clean(item.CostAccountCode);
|
||||
item.Notes = Clean(item.Notes);
|
||||
|
||||
// Only goods move in the warehouse.
|
||||
if (item.Kind != ItemKind.Goods)
|
||||
{
|
||||
item.Stocked = false;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<bool> BarcodeUsedAsync(IUnitOfWork uow, string barcode, long id, CancellationToken cancellationToken) =>
|
||||
await uow.Repository<Item, long>().CountAsync(Query.For<Item>().Where(i => i.Barcode == barcode && i.Id != id), cancellationToken).ConfigureAwait(false) > 0
|
||||
|| await uow.Repository<ItemBarcode, long>().CountAsync(Query.For<ItemBarcode>().Where(b => b.Code == barcode && b.ItemId != id), cancellationToken).ConfigureAwait(false) > 0;
|
||||
|
||||
private static void CheckUnits(ItemRecord record, List<TableProblem> problems)
|
||||
{
|
||||
var seen = new HashSet<long>();
|
||||
if (record.Item.UnitOfMeasureId is { } baseUnit)
|
||||
{
|
||||
seen.Add(baseUnit);
|
||||
}
|
||||
|
||||
for (var i = 0; i < record.Units.Count; i++)
|
||||
{
|
||||
var unit = record.Units[i];
|
||||
unit.Barcode = Clean(unit.Barcode);
|
||||
if (unit.UnitOfMeasureId == 0)
|
||||
{
|
||||
problems.Add(new($"Units.{i}.{nameof(ItemUnit.UnitOfMeasureId)}", DetailRequired));
|
||||
}
|
||||
else if (!seen.Add(unit.UnitOfMeasureId))
|
||||
{
|
||||
problems.Add(new($"Units.{i}.{nameof(ItemUnit.UnitOfMeasureId)}", UnitDuplicate));
|
||||
}
|
||||
|
||||
if (unit.Factor <= 0)
|
||||
{
|
||||
problems.Add(new($"Units.{i}.{nameof(ItemUnit.Factor)}", FactorInvalid));
|
||||
}
|
||||
|
||||
if (unit.Barcode is { } barcode && !EanValidator.IsValid(barcode))
|
||||
{
|
||||
problems.Add(new($"Units.{i}.{nameof(ItemUnit.Barcode)}", BarcodeInvalid));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void CheckBarcodes(ItemRecord record, List<TableProblem> problems)
|
||||
{
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||
if (record.Item.Barcode is { } main)
|
||||
{
|
||||
seen.Add(main);
|
||||
}
|
||||
|
||||
for (var i = 0; i < record.Barcodes.Count; i++)
|
||||
{
|
||||
var code = record.Barcodes[i];
|
||||
code.Code = code.Code.Trim();
|
||||
code.Description = Clean(code.Description);
|
||||
if (code.Code.Length == 0)
|
||||
{
|
||||
problems.Add(new($"Barcodes.{i}.{nameof(ItemBarcode.Code)}", DetailRequired));
|
||||
}
|
||||
else if (!seen.Add(code.Code))
|
||||
{
|
||||
problems.Add(new($"Barcodes.{i}.{nameof(ItemBarcode.Code)}", DetailDuplicate));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task CheckPricesAsync(IUnitOfWork uow, ItemRecord record, List<TableProblem> problems, CancellationToken cancellationToken)
|
||||
{
|
||||
var seen = new HashSet<(long?, long?, DateOnly?)>();
|
||||
var parties = uow.Repository<Party, long>();
|
||||
for (var i = 0; i < record.Prices.Count; i++)
|
||||
{
|
||||
var price = record.Prices[i];
|
||||
var field = $"Prices.{i}.";
|
||||
if ((price.PriceListId is null) == (price.PartyId is null))
|
||||
{
|
||||
problems.Add(new(field + nameof(ItemPrice.PriceListId), PriceTarget));
|
||||
continue;
|
||||
}
|
||||
|
||||
// A row added on the screen and not filled has id 0.
|
||||
if (price.PriceListId is 0 || price.PartyId is 0)
|
||||
{
|
||||
problems.Add(new(field + (price.PartyId is null ? nameof(ItemPrice.PriceListId) : nameof(ItemPrice.PartyId)), DetailRequired));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (price.PartyId is { } partyId && await parties.GetAsync(partyId, cancellationToken).ConfigureAwait(false) is not { IsCustomer: true })
|
||||
{
|
||||
problems.Add(new(field + nameof(ItemPrice.PartyId), PriceParty));
|
||||
}
|
||||
|
||||
if (price.Price < 0)
|
||||
{
|
||||
problems.Add(new(field + nameof(ItemPrice.Price), NotNegative));
|
||||
}
|
||||
|
||||
if (!seen.Add((price.PriceListId, price.PartyId, price.ValidFrom)))
|
||||
{
|
||||
problems.Add(new(field + nameof(ItemPrice.ValidFrom), PriceDuplicate));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task CheckSuppliersAsync(IUnitOfWork uow, ItemRecord record, List<TableProblem> problems, CancellationToken cancellationToken)
|
||||
{
|
||||
var seen = new HashSet<long>();
|
||||
var parties = uow.Repository<Party, long>();
|
||||
for (var i = 0; i < record.Suppliers.Count; i++)
|
||||
{
|
||||
var supplier = record.Suppliers[i];
|
||||
var field = $"Suppliers.{i}.";
|
||||
supplier.SupplierCode = Clean(supplier.SupplierCode);
|
||||
if (supplier.PartyId == 0)
|
||||
{
|
||||
problems.Add(new(field + nameof(ItemSupplier.PartyId), DetailRequired));
|
||||
}
|
||||
else if (!seen.Add(supplier.PartyId))
|
||||
{
|
||||
problems.Add(new(field + nameof(ItemSupplier.PartyId), DetailDuplicate));
|
||||
}
|
||||
else if (await parties.GetAsync(supplier.PartyId, cancellationToken).ConfigureAwait(false) is not { IsSupplier: true })
|
||||
{
|
||||
problems.Add(new(field + nameof(ItemSupplier.PartyId), SupplierInvalid));
|
||||
}
|
||||
|
||||
if (supplier.Price < 0)
|
||||
{
|
||||
problems.Add(new(field + nameof(ItemSupplier.Price), NotNegative));
|
||||
}
|
||||
|
||||
if (supplier.MinimumQuantity < 0)
|
||||
{
|
||||
problems.Add(new(field + nameof(ItemSupplier.MinimumQuantity), NotNegative));
|
||||
}
|
||||
|
||||
if (supplier.LeadTimeDays < 0)
|
||||
{
|
||||
problems.Add(new(field + nameof(ItemSupplier.LeadTimeDays), NotNegative));
|
||||
}
|
||||
}
|
||||
|
||||
// One usual supplier: the first one marked.
|
||||
var found = false;
|
||||
foreach (var supplier in record.Suppliers.Where(s => s.IsDefault))
|
||||
{
|
||||
supplier.IsDefault = !found;
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
|
||||
private static void CheckSubstitutes(ItemRecord record, List<TableProblem> problems)
|
||||
{
|
||||
var seen = new HashSet<long>();
|
||||
for (var i = 0; i < record.Substitutes.Count; i++)
|
||||
{
|
||||
var substitute = record.Substitutes[i];
|
||||
var field = $"Substitutes.{i}.{nameof(ItemSubstitute.SubstituteId)}";
|
||||
substitute.Notes = Clean(substitute.Notes);
|
||||
if (substitute.SubstituteId == 0)
|
||||
{
|
||||
problems.Add(new(field, DetailRequired));
|
||||
}
|
||||
else if (substitute.SubstituteId == record.Item.Id)
|
||||
{
|
||||
problems.Add(new(field, SubstituteSelf));
|
||||
}
|
||||
else if (!seen.Add(substitute.SubstituteId))
|
||||
{
|
||||
problems.Add(new(field, DetailDuplicate));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static string? Clean(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||
|
||||
private static Item Clone(Item item)
|
||||
{
|
||||
var copy = new Item();
|
||||
foreach (var property in typeof(Item).GetProperties().Where(p => p.CanRead && p.CanWrite))
|
||||
{
|
||||
property.SetValue(copy, property.GetValue(item));
|
||||
}
|
||||
|
||||
return copy;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Core.Tables;
|
||||
|
||||
namespace Khaemhat.Application.Items;
|
||||
|
||||
/// <summary>The price proposed for an item and where it comes from (<c>price_source</c> of the document lines).</summary>
|
||||
/// <param name="Price">The price, or none.</param>
|
||||
/// <param name="Source">Where it comes from.</param>
|
||||
/// <param name="PriceListId">The price list it comes from.</param>
|
||||
/// <param name="VatIncluded">The price includes VAT (a price list with VAT included).</param>
|
||||
/// <param name="ValidFrom">The price is valid from this day.</param>
|
||||
public sealed record PriceQuote(decimal? Price, PriceSource Source, long? PriceListId, bool VatIncluded, DateOnly? ValidFrom)
|
||||
{
|
||||
/// <summary>No price.</summary>
|
||||
public static PriceQuote None { get; } = new(null, PriceSource.None, null, false, null);
|
||||
}
|
||||
|
||||
/// <summary>The discounts proposed on a line.</summary>
|
||||
/// <param name="Formula">The chain, such as <c>5+2</c>, or none.</param>
|
||||
/// <param name="Equivalent">The single discount equal to the chain, in percent.</param>
|
||||
public sealed record DiscountQuote(string? Formula, decimal Equivalent)
|
||||
{
|
||||
/// <summary>No discount.</summary>
|
||||
public static DiscountQuote None { get; } = new(null, 0m);
|
||||
}
|
||||
|
||||
/// <summary>A price of a price list for an item at a date.</summary>
|
||||
/// <param name="Price">The price, or none.</param>
|
||||
/// <param name="Derived">The price is computed from the base list of a derived list, not written.</param>
|
||||
/// <param name="ValidFrom">The price is valid from this day.</param>
|
||||
public sealed record PriceCell(decimal? Price, bool Derived, DateOnly? ValidFrom)
|
||||
{
|
||||
/// <summary>No price.</summary>
|
||||
public static PriceCell Empty { get; } = new(null, false, null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The prices of some items in memory, and the search of SPEC §11.3 (ADR 0030): net price of the party for the item,
|
||||
/// then the price list of the party or of the document, then the base price list, then the price of the item. A
|
||||
/// derived list without its own price takes the price of its base list with the markup and the rounding of the list.
|
||||
/// </summary>
|
||||
public sealed class PriceBook
|
||||
{
|
||||
// A derived list of a derived list... is followed at most this deep (the table forbids only a list on itself).
|
||||
private const int MaxDepth = 5;
|
||||
|
||||
private readonly Dictionary<long, PriceList> _lists;
|
||||
private readonly ILookup<(long Item, long List), ItemPrice> _listPrices;
|
||||
private readonly ILookup<(long Item, long Party), ItemPrice> _netPrices;
|
||||
|
||||
/// <summary>Creates the book.</summary>
|
||||
/// <param name="lists">The price lists of the company.</param>
|
||||
/// <param name="prices">The prices of the items wanted (all their rows).</param>
|
||||
public PriceBook(IEnumerable<PriceList> lists, IEnumerable<ItemPrice> prices)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(lists);
|
||||
ArgumentNullException.ThrowIfNull(prices);
|
||||
_lists = lists.ToDictionary(l => l.Id);
|
||||
var all = prices.ToList();
|
||||
_listPrices = all.Where(p => p.PriceListId is not null).ToLookup(p => (p.ItemId, p.PriceListId!.Value));
|
||||
_netPrices = all.Where(p => p.PartyId is not null).ToLookup(p => (p.ItemId, p.PartyId!.Value));
|
||||
Base = BaseOf(_lists.Values);
|
||||
}
|
||||
|
||||
/// <summary>The base price list: the one marked, or the one with code <c>BASE</c>.</summary>
|
||||
public PriceList? Base { get; }
|
||||
|
||||
/// <summary>The price lists.</summary>
|
||||
public IReadOnlyCollection<PriceList> Lists => _lists.Values;
|
||||
|
||||
/// <summary>The base price list among some.</summary>
|
||||
/// <param name="lists">The price lists.</param>
|
||||
/// <returns>The base one, or none.</returns>
|
||||
public static PriceList? BaseOf(IEnumerable<PriceList> lists)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(lists);
|
||||
var active = lists.Where(l => !l.Disabled).OrderBy(l => l.Code, StringComparer.Ordinal).ToList();
|
||||
return active.FirstOrDefault(l => l.IsBase) ?? active.FirstOrDefault(l => l.Code == "BASE");
|
||||
}
|
||||
|
||||
/// <summary>The row in effect at a date: the latest start not after it (a row without start is always valid).</summary>
|
||||
/// <param name="rows">The rows of one item and one list or party.</param>
|
||||
/// <param name="date">The date.</param>
|
||||
/// <returns>The row, or none.</returns>
|
||||
public static ItemPrice? At(IEnumerable<ItemPrice> rows, DateOnly date)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(rows);
|
||||
return rows.Where(r => r.ValidFrom is null || r.ValidFrom <= date).OrderByDescending(r => r.ValidFrom ?? DateOnly.MinValue).FirstOrDefault();
|
||||
}
|
||||
|
||||
/// <summary>Whether a price list can be used at a date: active and within its validity.</summary>
|
||||
/// <param name="list">The list.</param>
|
||||
/// <param name="date">The date.</param>
|
||||
/// <returns>Whether it is valid.</returns>
|
||||
public static bool IsValid(PriceList list, DateOnly date)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(list);
|
||||
return !list.Disabled && (list.ValidFrom is null || list.ValidFrom <= date) && (list.ValidTo is null || list.ValidTo >= date);
|
||||
}
|
||||
|
||||
/// <summary>The price of an item in a list at a date, derived from the base list when the list has none.</summary>
|
||||
/// <param name="itemId">The item.</param>
|
||||
/// <param name="listId">The list.</param>
|
||||
/// <param name="date">The date.</param>
|
||||
/// <returns>The price.</returns>
|
||||
public PriceCell ListPrice(long itemId, long listId, DateOnly date) => ListPrice(itemId, listId, date, 0);
|
||||
|
||||
/// <summary>The price written in a list for an item at a date, without derivation.</summary>
|
||||
/// <param name="itemId">The item.</param>
|
||||
/// <param name="listId">The list.</param>
|
||||
/// <param name="date">The date.</param>
|
||||
/// <returns>The row, or none.</returns>
|
||||
public ItemPrice? OwnPrice(long itemId, long listId, DateOnly date) => At(_listPrices[(itemId, listId)], date);
|
||||
|
||||
/// <summary>The net price of a party for an item at a date.</summary>
|
||||
/// <param name="itemId">The item.</param>
|
||||
/// <param name="partyId">The party.</param>
|
||||
/// <param name="date">The date.</param>
|
||||
/// <returns>The row, or none.</returns>
|
||||
public ItemPrice? NetPrice(long itemId, long partyId, DateOnly date) => At(_netPrices[(itemId, partyId)], date);
|
||||
|
||||
/// <summary>The price proposed for an item (SPEC §11.3): net of the party, list, base list, item.</summary>
|
||||
/// <param name="item">The item.</param>
|
||||
/// <param name="partyId">The party of the document.</param>
|
||||
/// <param name="priceListId">The price list of the party or of the document.</param>
|
||||
/// <param name="date">The date of the document.</param>
|
||||
/// <returns>The price and its source.</returns>
|
||||
public PriceQuote Quote(Item item, long? partyId, long? priceListId, DateOnly date)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(item);
|
||||
if (partyId is { } party && NetPrice(item.Id, party, date) is { } net)
|
||||
{
|
||||
return new PriceQuote(net.Price, PriceSource.PartyNet, null, false, net.ValidFrom);
|
||||
}
|
||||
|
||||
if (priceListId is { } listId && _lists.TryGetValue(listId, out var list) && IsValid(list, date)
|
||||
&& ListPrice(item.Id, listId, date) is { Price: { } listPrice } cell)
|
||||
{
|
||||
return new PriceQuote(listPrice, PriceSource.PartyPriceList, listId, list.VatIncluded, cell.ValidFrom);
|
||||
}
|
||||
|
||||
if (Base is { } baseList && baseList.Id != priceListId && IsValid(baseList, date)
|
||||
&& ListPrice(item.Id, baseList.Id, date) is { Price: { } basePrice } baseCell)
|
||||
{
|
||||
return new PriceQuote(basePrice, PriceSource.BasePriceList, baseList.Id, baseList.VatIncluded, baseCell.ValidFrom);
|
||||
}
|
||||
|
||||
return item.Price is { } own ? new PriceQuote(own, PriceSource.Item, null, false, null) : PriceQuote.None;
|
||||
}
|
||||
|
||||
/// <summary>The discounts of the party on a price (SPEC §11.3): none on a net price, else the two of the sales terms.</summary>
|
||||
/// <param name="price">The price proposed.</param>
|
||||
/// <param name="terms">The sales terms of the party.</param>
|
||||
/// <returns>The discounts.</returns>
|
||||
public static DiscountQuote Discounts(PriceQuote price, PartySalesTerms? terms)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(price);
|
||||
if (price.Source == PriceSource.PartyNet || terms is null)
|
||||
{
|
||||
return DiscountQuote.None;
|
||||
}
|
||||
|
||||
decimal[] steps = [.. new[] { terms.Discount1, terms.Discount2 }.Where(d => d is > 0).Select(d => d!.Value)];
|
||||
return steps.Length == 0 ? DiscountQuote.None : new DiscountQuote(DiscountFormula.Format(steps), DiscountFormula.Equivalent(steps));
|
||||
}
|
||||
|
||||
private PriceCell ListPrice(long itemId, long listId, DateOnly date, int depth)
|
||||
{
|
||||
if (depth > MaxDepth || !_lists.TryGetValue(listId, out var list))
|
||||
{
|
||||
return PriceCell.Empty;
|
||||
}
|
||||
|
||||
if (OwnPrice(itemId, listId, date) is { } own)
|
||||
{
|
||||
return new PriceCell(own.Price, false, own.ValidFrom);
|
||||
}
|
||||
|
||||
if (list.BasePriceListId is { } parent && ListPrice(itemId, parent, date, depth + 1) is { Price: { } basePrice } from)
|
||||
{
|
||||
return new PriceCell(PriceRounding.Round(PriceRounding.Change(basePrice, list.MarkupPercent), list.RoundingStep), true, from.ValidFrom);
|
||||
}
|
||||
|
||||
return PriceCell.Empty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
using Khaemhat.Application.Audit;
|
||||
using Khaemhat.Application.Querying;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Items;
|
||||
|
||||
/// <summary>A column of the price grid: a price list.</summary>
|
||||
/// <param name="Id">The list.</param>
|
||||
/// <param name="Code">Its code.</param>
|
||||
/// <param name="Description">Its description.</param>
|
||||
/// <param name="IsBase">The base list.</param>
|
||||
/// <param name="Derived">Derived from another list.</param>
|
||||
/// <param name="VatIncluded">Prices with VAT.</param>
|
||||
public sealed record PriceListColumn(long Id, string Code, string Description, bool IsBase, bool Derived, bool VatIncluded);
|
||||
|
||||
/// <summary>A row of the price grid: an item with its price in every list at the date.</summary>
|
||||
/// <param name="ItemId">The item.</param>
|
||||
/// <param name="Code">Its code.</param>
|
||||
/// <param name="Description">Its description.</param>
|
||||
/// <param name="UnitOfMeasureId">Its unit.</param>
|
||||
/// <param name="AverageCost">Its average cost (standard when none), only for who sees costs.</param>
|
||||
/// <param name="Prices">The prices by list.</param>
|
||||
/// <param name="Net">The net price of the party chosen, if any.</param>
|
||||
public sealed record PriceGridRow(
|
||||
long ItemId, string Code, string Description, long? UnitOfMeasureId, decimal? AverageCost, IReadOnlyDictionary<long, PriceCell> Prices, PriceCell? Net);
|
||||
|
||||
/// <summary>The price grid (mockup 018).</summary>
|
||||
/// <param name="Lists">The columns.</param>
|
||||
/// <param name="Page">The rows.</param>
|
||||
public sealed record PriceGrid(IReadOnlyList<PriceListColumn> Lists, ListPage<PriceGridRow> Page);
|
||||
|
||||
/// <summary>A price to write: of a list or net of a customer, valid from a day; no price removes the row of that day.</summary>
|
||||
/// <param name="ItemId">The item.</param>
|
||||
/// <param name="PriceListId">The list.</param>
|
||||
/// <param name="PartyId">The customer.</param>
|
||||
/// <param name="Price">The price, or none to remove it.</param>
|
||||
/// <param name="ValidFrom">Valid from this day.</param>
|
||||
public sealed record PriceEdit(long ItemId, long? PriceListId, long? PartyId, decimal? Price, DateOnly? ValidFrom);
|
||||
|
||||
/// <summary>A mass update of a price list (mockup 018): from the list itself or another one, a percent and a rounding.</summary>
|
||||
public sealed record BulkUpdate
|
||||
{
|
||||
/// <summary>The list to update.</summary>
|
||||
public long PriceListId { get; init; }
|
||||
|
||||
/// <summary>The list the prices start from; none: the list itself.</summary>
|
||||
public long? SourcePriceListId { get; init; }
|
||||
|
||||
/// <summary>The change in percent, also negative.</summary>
|
||||
public decimal Percent { get; init; }
|
||||
|
||||
/// <summary>The rounding step, such as 0.10, 0.50 or 1.00; zero: cents.</summary>
|
||||
public decimal RoundingStep { get; init; }
|
||||
|
||||
/// <summary>Rounding up, down or to the nearest.</summary>
|
||||
public RoundingDirection Direction { get; init; }
|
||||
|
||||
/// <summary>The prices are read at this day and the new ones are valid from it.</summary>
|
||||
public DateOnly Date { get; init; }
|
||||
|
||||
/// <summary>Only the items of this category.</summary>
|
||||
public long? CategoryId { get; init; }
|
||||
|
||||
/// <summary>Only these items (the selection); none: all the active items with a price.</summary>
|
||||
public IReadOnlyList<long>? ItemIds { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Price lists (mockup 018, ADR 0030): the grid of items by lists at a date with the net prices of a customer, mass
|
||||
/// updates, the writing of prices with their validity, and the price and discounts proposed for a document line.
|
||||
/// </summary>
|
||||
/// <remarks>Permissions <c>items.item.read</c> and <c>write</c>; costs and margins with <c>items.cost.read</c>.</remarks>
|
||||
public sealed class PriceListService
|
||||
{
|
||||
/// <summary>Error: a price is negative.</summary>
|
||||
public const string NotNegative = ItemService.NotNegative;
|
||||
|
||||
/// <summary>Error: the list of a mass update does not exist.</summary>
|
||||
public const string ListUnknown = "items.price-list.unknown";
|
||||
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly AuditTrail _audit;
|
||||
private readonly ItemService _items;
|
||||
|
||||
/// <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="items">The items (for the cost permission).</param>
|
||||
public PriceListService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, ItemService items)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(audit);
|
||||
ArgumentNullException.ThrowIfNull(items);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
_audit = audit;
|
||||
_items = items;
|
||||
}
|
||||
|
||||
/// <summary>The active price lists: the base one first, then by code.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The lists.</returns>
|
||||
public async Task<IReadOnlyList<PriceListColumn>> ListsAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ItemService.ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return await ColumnsAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The price grid: a page of items (no text items) with the price of every list at a date.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="query">Search, filters (those of the items radar), sort, page.</param>
|
||||
/// <param name="date">The day the prices are read at.</param>
|
||||
/// <param name="partyId">The customer whose net prices are shown.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The grid.</returns>
|
||||
public async Task<PriceGrid> GridAsync(Actor actor, string companyCode, ListQuery query, DateOnly date, long? partyId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(query);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ItemService.ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
var costs = await _items.CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var columns = await ColumnsAsync(uow, cancellationToken).ConfigureAwait(false);
|
||||
var page = await uow.Repository<Item, long>().ListAsync(
|
||||
ItemService.Fields.Apply(Query.For<Item>().Where(i => i.Kind != ItemKind.Text), query), cancellationToken).ConfigureAwait(false);
|
||||
var book = await ItemService.BookAsync(uow, [.. page.Items.Select(i => i.Id)], cancellationToken).ConfigureAwait(false);
|
||||
IReadOnlyList<PriceGridRow> rows =
|
||||
[
|
||||
.. page.Items.Select(i => new PriceGridRow(
|
||||
i.Id, i.Code, i.Description, i.UnitOfMeasureId, costs ? i.AverageCost ?? i.StandardCost : null,
|
||||
columns.ToDictionary(c => c.Id, c => book.ListPrice(i.Id, c.Id, date)),
|
||||
partyId is { } party ? book.NetPrice(i.Id, party, date) is { } net ? new PriceCell(net.Price, false, net.ValidFrom) : PriceCell.Empty : null)),
|
||||
];
|
||||
return new PriceGrid(columns, new ListPage<PriceGridRow>(rows, page.TotalCount, new Dictionary<string, decimal>()));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes a mass update without saving it: for every item with a price in the source list at the date, the new
|
||||
/// price of the list, changed by the percent and rounded. The screen shows them highlighted until saved.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who asks.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="update">The update.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The prices to write; unchanged ones are left out.</returns>
|
||||
/// <exception cref="ValidationFailedException">When the lists are unknown or the step negative.</exception>
|
||||
public async Task<IReadOnlyList<PriceEdit>> PreviewAsync(Actor actor, string companyCode, BulkUpdate update, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(update);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ItemService.WritePermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var lists = uow.Repository<PriceList, long>();
|
||||
var source = update.SourcePriceListId ?? update.PriceListId;
|
||||
if (await lists.GetAsync(update.PriceListId, cancellationToken).ConfigureAwait(false) is null || await lists.GetAsync(source, cancellationToken).ConfigureAwait(false) is null)
|
||||
{
|
||||
throw new ValidationFailedException([nameof(BulkUpdate.PriceListId) + ":" + ListUnknown]);
|
||||
}
|
||||
|
||||
if (update.RoundingStep < 0)
|
||||
{
|
||||
throw new ValidationFailedException([nameof(BulkUpdate.RoundingStep) + ":" + TableCatalog.NumberRange]);
|
||||
}
|
||||
|
||||
var select = Query.For<Item>().Where(i => !i.Disabled && i.Kind != ItemKind.Text);
|
||||
if (update.CategoryId is { } category)
|
||||
{
|
||||
select = select.Where(i => i.CategoryId == category);
|
||||
}
|
||||
|
||||
var items = (await uow.Repository<Item, long>().ListAsync(select, cancellationToken).ConfigureAwait(false)).Items;
|
||||
if (update.ItemIds is { } wanted)
|
||||
{
|
||||
var only = wanted.ToHashSet();
|
||||
items = [.. items.Where(i => only.Contains(i.Id))];
|
||||
}
|
||||
|
||||
var book = await ItemService.BookAsync(uow, [.. items.Select(i => i.Id)], cancellationToken).ConfigureAwait(false);
|
||||
var edits = new List<PriceEdit>();
|
||||
foreach (var item in items.OrderBy(i => i.Code, StringComparer.Ordinal))
|
||||
{
|
||||
if (book.ListPrice(item.Id, source, update.Date).Price is not { } from)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var price = PriceRounding.Round(PriceRounding.Change(from, update.Percent), update.RoundingStep, update.Direction);
|
||||
if (book.ListPrice(item.Id, update.PriceListId, update.Date).Price != price)
|
||||
{
|
||||
edits.Add(new PriceEdit(item.Id, update.PriceListId, null, price, update.Date));
|
||||
}
|
||||
}
|
||||
|
||||
return edits;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes prices: a row of the same list or customer and day is changed (or removed when the price is none), else a
|
||||
/// new row starts that day, so the prices before it stay for older documents. A price equal to the one in effect is
|
||||
/// not written again. Every change goes in the history of the item.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who saves.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="edits">The prices.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>How many rows were written or removed.</returns>
|
||||
/// <exception cref="ValidationFailedException">With the errors (<c>index:code</c>).</exception>
|
||||
public async Task<int> SaveAsync(Actor actor, string companyCode, IReadOnlyList<PriceEdit> edits, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(edits);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ItemService.WritePermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var problems = new List<string>();
|
||||
var parties = uow.Repository<Party, long>();
|
||||
for (var i = 0; i < edits.Count; i++)
|
||||
{
|
||||
var edit = edits[i];
|
||||
if ((edit.PriceListId is null) == (edit.PartyId is null))
|
||||
{
|
||||
problems.Add(i + ":" + ItemService.PriceTarget);
|
||||
}
|
||||
else if (edit.PartyId is { } partyId && await parties.GetAsync(partyId, cancellationToken).ConfigureAwait(false) is not { IsCustomer: true })
|
||||
{
|
||||
problems.Add(i + ":" + ItemService.PriceParty);
|
||||
}
|
||||
|
||||
if (edit.Price < 0)
|
||||
{
|
||||
problems.Add(i + ":" + NotNegative);
|
||||
}
|
||||
}
|
||||
|
||||
if (problems.Count > 0)
|
||||
{
|
||||
throw new ValidationFailedException(problems);
|
||||
}
|
||||
|
||||
var prices = uow.Repository<ItemPrice, long>();
|
||||
var written = 0;
|
||||
foreach (var group in edits.GroupBy(e => e.ItemId))
|
||||
{
|
||||
var itemId = group.Key;
|
||||
var rows = (await prices.ListAsync(Query.For<ItemPrice>().Where(p => p.ItemId == itemId), cancellationToken).ConfigureAwait(false)).Items.ToList();
|
||||
foreach (var edit in group)
|
||||
{
|
||||
var same = rows.Where(r => r.PriceListId == edit.PriceListId && r.PartyId == edit.PartyId).ToList();
|
||||
var day = same.FirstOrDefault(r => r.ValidFrom == edit.ValidFrom);
|
||||
if (edit.Price is not { } price)
|
||||
{
|
||||
if (day is not null)
|
||||
{
|
||||
await prices.DeleteAsync(day.Id, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Delete, itemId, day, null, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
rows.Remove(day);
|
||||
written++;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (day is not null)
|
||||
{
|
||||
if (day.Price != price)
|
||||
{
|
||||
var before = Copy(day);
|
||||
day.Price = price;
|
||||
await prices.UpdateAsync(day, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync(uow, AuditAction.Update, itemId, before, day, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
written++;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (edit.ValidFrom is { } from && PriceBook.At(same, from) is { } current && current.Price == price)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var row = new ItemPrice { ItemId = itemId, PriceListId = edit.PriceListId, PartyId = edit.PartyId, Price = price, ValidFrom = edit.ValidFrom };
|
||||
row.Id = await prices.InsertAsync(row, cancellationToken).ConfigureAwait(false);
|
||||
await _audit.RecordAsync<ItemPrice>(uow, AuditAction.Insert, itemId, null, row, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
rows.Add(row);
|
||||
written++;
|
||||
}
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return written;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The price and the discounts proposed for an item on a document (SPEC §11.3): net price of the party, then the
|
||||
/// list given or the one of the party, then the base list, then the item; the discounts of the party unless net.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who asks.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="itemId">The item.</param>
|
||||
/// <param name="partyId">The party of the document.</param>
|
||||
/// <param name="priceListId">The list of the document; none: the one of the party.</param>
|
||||
/// <param name="date">The date of the document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The price and the discounts.</returns>
|
||||
public async Task<(PriceQuote Price, DiscountQuote Discounts)> QuoteAsync(
|
||||
Actor actor, string companyCode, long itemId, long? partyId, long? priceListId, DateOnly date, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ItemService.ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return await QuoteAsync(uow, itemId, partyId, priceListId, date, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The price and the discounts of a line, inside the unit of work of a document.</summary>
|
||||
/// <param name="uow">The unit of work of the company.</param>
|
||||
/// <param name="itemId">The item.</param>
|
||||
/// <param name="partyId">The party of the document.</param>
|
||||
/// <param name="priceListId">The list of the document; none: the one of the party.</param>
|
||||
/// <param name="date">The date of the document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The price and the discounts.</returns>
|
||||
public static async Task<(PriceQuote Price, DiscountQuote Discounts)> QuoteAsync(
|
||||
IUnitOfWork uow, long itemId, long? partyId, long? priceListId, DateOnly date, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(uow);
|
||||
var item = await uow.Repository<Item, long>().GetAsync(itemId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(ItemService.NotFound);
|
||||
var terms = partyId is { } party
|
||||
? await uow.Repository<PartySalesTerms, long>().FindAsync(Query.For<PartySalesTerms>().Where(t => t.PartyId == party), cancellationToken).ConfigureAwait(false)
|
||||
: null;
|
||||
var book = await ItemService.BookAsync(uow, [itemId], cancellationToken).ConfigureAwait(false);
|
||||
var price = book.Quote(item, partyId, priceListId ?? terms?.PriceListId, date);
|
||||
return (price, PriceBook.Discounts(price, terms));
|
||||
}
|
||||
|
||||
private static async Task<IReadOnlyList<PriceListColumn>> ColumnsAsync(IUnitOfWork uow, CancellationToken cancellationToken)
|
||||
{
|
||||
var lists = (await uow.Repository<PriceList, long>().ListAsync(Query.For<PriceList>().Where(l => !l.Disabled), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var baseList = PriceBook.BaseOf(lists);
|
||||
return
|
||||
[
|
||||
.. lists.OrderBy(l => l.Id == baseList?.Id ? 0 : 1).ThenBy(l => l.Code, StringComparer.Ordinal)
|
||||
.Select(l => new PriceListColumn(l.Id, l.Code, l.Description, l.Id == baseList?.Id, l.BasePriceListId is not null, l.VatIncluded)),
|
||||
];
|
||||
}
|
||||
|
||||
private static ItemPrice Copy(ItemPrice price) => new()
|
||||
{
|
||||
Id = price.Id, ItemId = price.ItemId, PriceListId = price.PriceListId, PartyId = price.PartyId, Price = price.Price, ValidFrom = price.ValidFrom,
|
||||
};
|
||||
}
|
||||
@@ -39,7 +39,8 @@ public interface IScheduledJob
|
||||
/// <param name="JobType">The job type.</param>
|
||||
/// <param name="Cron">When it runs.</param>
|
||||
/// <param name="TimeoutSeconds">Its timeout.</param>
|
||||
public sealed record SystemTaskDefinition(string Code, string Name, string JobType, string Cron, int TimeoutSeconds = 600);
|
||||
/// <param name="UsesNetwork">Whether it calls services outside the instance (the tests run it with a stub).</param>
|
||||
public sealed record SystemTaskDefinition(string Code, string Name, string JobType, string Cron, int TimeoutSeconds = 600, bool UsesNetwork = false);
|
||||
|
||||
/// <summary>
|
||||
/// The scheduler (SPEC §9.4; mockup 083): reads <c>sys_scheduled_tasks</c>, runs the due ones with a lock in
|
||||
@@ -49,12 +50,14 @@ public sealed record SystemTaskDefinition(string Code, string Name, string JobTy
|
||||
/// </summary>
|
||||
public sealed class JobScheduler
|
||||
{
|
||||
/// <summary>The system tasks of M2.</summary>
|
||||
/// <summary>The system tasks (M2, attachments trash from M3, ECB rates from M4).</summary>
|
||||
public static readonly IReadOnlyList<SystemTaskDefinition> SystemTasks =
|
||||
[
|
||||
new("system.sessions-cleanup", "Pulizia sessioni scadute", SessionCleanupJob.JobType, "15 * * * *", 300),
|
||||
new("system.license-check", "Verifica licenza", LicenseCheckJob.JobType, "0 * * * *", 120),
|
||||
new("system.log-retention", "Conservazione del log", LogRetentionJob.JobType, "30 3 * * *", 1800),
|
||||
new("system.attachments-trash", "Svuotamento cestino allegati", Files.AttachmentTrashPurgeJob.JobType, "45 3 * * *", 1800),
|
||||
new("system.ecb-rates", "Cambi di riferimento BCE", Tables.EcbRatesJob.JobType, "30 16 * * 1-5", 300, UsesNetwork: true),
|
||||
];
|
||||
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
|
||||
@@ -9,6 +9,11 @@
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Base data shipped with the code (SPEC §14). -->
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="Seeding/Data/*.csv" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../Khaemhat.Core/Khaemhat.Core.csproj" />
|
||||
<ProjectReference Include="../Khaemhat.Data/Khaemhat.Data.csproj" />
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
using System.Collections.Frozen;
|
||||
using System.Globalization;
|
||||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Khaemhat.Application.Localization;
|
||||
|
||||
/// <summary>
|
||||
/// The texts of the interface (SPEC §1.9, §10.8): keys such as <c>Shell.Menu.Home</c> resolved from
|
||||
/// <c>Resources/<culture>/*.json</c>. Components never contain literal texts; they ask this service.
|
||||
/// </summary>
|
||||
public interface ITexts
|
||||
{
|
||||
/// <summary>The culture of the texts and of number and date formats.</summary>
|
||||
CultureInfo Culture { get; }
|
||||
|
||||
/// <summary>The text of a key; a missing key gives <c>[key]</c>, visible in the page and caught by the tests.</summary>
|
||||
/// <param name="key">The key, <c>Area.Entity.Text</c>.</param>
|
||||
/// <returns>The text.</returns>
|
||||
string this[string key] { get; }
|
||||
|
||||
/// <summary>The text of a key with <see cref="string.Format(IFormatProvider, string, object[])"/> placeholders filled in the culture.</summary>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <param name="args">The values for <c>{0}</c>, <c>{1}</c>...</param>
|
||||
/// <returns>The text.</returns>
|
||||
string Format(string key, params object?[] args);
|
||||
|
||||
/// <summary>Whether a key exists.</summary>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <returns><see langword="true"/> when it has a text.</returns>
|
||||
bool Contains(string key);
|
||||
|
||||
/// <summary>Every key, for the tests and the documentation.</summary>
|
||||
IReadOnlyCollection<string> Keys { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the texts from JSON files. Nested objects become dotted keys: <c>{"Shell": {"Menu": {"Home": "Home"}}}</c>
|
||||
/// gives <c>Shell.Menu.Home</c>; the property <c>_</c> gives a text to an object that also has children. The file
|
||||
/// name is not part of the key; two files defining the same key are an error.
|
||||
/// </summary>
|
||||
public sealed class JsonTextProvider : ITexts
|
||||
{
|
||||
/// <summary>The prefix of the embedded resources holding the texts: <c>texts/it-IT/Shell.json</c>.</summary>
|
||||
public const string ResourcePrefix = "texts/";
|
||||
|
||||
private readonly FrozenDictionary<string, string> _texts;
|
||||
|
||||
/// <summary>Creates the provider from JSON documents.</summary>
|
||||
/// <param name="culture">The culture.</param>
|
||||
/// <param name="documents">The documents, by name (used in error messages).</param>
|
||||
public JsonTextProvider(CultureInfo culture, IEnumerable<KeyValuePair<string, string>> documents)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(culture);
|
||||
ArgumentNullException.ThrowIfNull(documents);
|
||||
Culture = culture;
|
||||
var texts = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var (name, json) in documents)
|
||||
{
|
||||
using var document = JsonDocument.Parse(json, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true });
|
||||
if (document.RootElement.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
throw new InvalidDataException($"The texts file {name} must contain an object.");
|
||||
}
|
||||
|
||||
Flatten(document.RootElement, string.Empty, name, texts);
|
||||
}
|
||||
|
||||
_texts = texts.ToFrozenDictionary(StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public CultureInfo Culture { get; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyCollection<string> Keys => _texts.Keys;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string this[string key] => key is not null && _texts.TryGetValue(key, out var text) ? text : "[" + key + "]";
|
||||
|
||||
/// <summary>Loads the texts of a culture from the embedded resources of an assembly (<see cref="ResourcePrefix"/>).</summary>
|
||||
/// <param name="assembly">The assembly, usually the web project.</param>
|
||||
/// <param name="culture">The culture, for example <c>it-IT</c>.</param>
|
||||
/// <returns>The provider.</returns>
|
||||
public static JsonTextProvider FromAssembly(Assembly assembly, CultureInfo culture)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(assembly);
|
||||
ArgumentNullException.ThrowIfNull(culture);
|
||||
var prefix = ResourcePrefix + culture.Name + "/";
|
||||
var documents = new List<KeyValuePair<string, string>>();
|
||||
foreach (var resource in assembly.GetManifestResourceNames().Order(StringComparer.Ordinal))
|
||||
{
|
||||
var name = resource.Replace('\\', '/');
|
||||
if (!name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) || !name.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
using var stream = assembly.GetManifestResourceStream(resource)!;
|
||||
using var reader = new StreamReader(stream);
|
||||
documents.Add(new(name, reader.ReadToEnd()));
|
||||
}
|
||||
|
||||
if (documents.Count == 0)
|
||||
{
|
||||
throw new InvalidOperationException($"No texts for {culture.Name} in {assembly.GetName().Name}.");
|
||||
}
|
||||
|
||||
return new JsonTextProvider(culture, documents);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Format(string key, params object?[] args) => string.Format(Culture, this[key], args);
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool Contains(string key) => key is not null && _texts.ContainsKey(key);
|
||||
|
||||
private static void Flatten(JsonElement element, string prefix, string file, Dictionary<string, string> texts)
|
||||
{
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
// "_" gives a text to the object itself: {"Menu": {"Parties": {"_": "Anagrafiche", "Customers": "Clienti"}}}.
|
||||
var key = property.Name == "_" && prefix.Length > 0 ? prefix : prefix.Length == 0 ? property.Name : prefix + "." + property.Name;
|
||||
switch (property.Value.ValueKind)
|
||||
{
|
||||
case JsonValueKind.Object:
|
||||
Flatten(property.Value, key, file, texts);
|
||||
break;
|
||||
case JsonValueKind.String:
|
||||
if (!texts.TryAdd(key, property.Value.GetString()!))
|
||||
{
|
||||
throw new InvalidDataException($"The text {key} is defined twice ({file}).");
|
||||
}
|
||||
|
||||
break;
|
||||
default:
|
||||
throw new InvalidDataException($"The text {key} in {file} must be a string or an object.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Number, money and date formats of the interface, in the culture of <see cref="ITexts"/> (SPEC §10.8).</summary>
|
||||
public static class TextFormats
|
||||
{
|
||||
/// <summary>An amount in euro: <c>€ 1.234,50</c>.</summary>
|
||||
/// <param name="texts">The texts.</param>
|
||||
/// <param name="amount">The amount.</param>
|
||||
/// <returns>The text.</returns>
|
||||
public static string Money(this ITexts texts, decimal amount)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(texts);
|
||||
return "€ " + amount.ToString("#,##0.00", texts.Culture);
|
||||
}
|
||||
|
||||
/// <summary>A number with a fixed count of decimals: <c>1.234,5</c>.</summary>
|
||||
/// <param name="texts">The texts.</param>
|
||||
/// <param name="value">The value.</param>
|
||||
/// <param name="decimals">The decimals.</param>
|
||||
/// <returns>The text.</returns>
|
||||
public static string Number(this ITexts texts, decimal value, int decimals = 0)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(texts);
|
||||
return value.ToString("N" + decimals.ToString(CultureInfo.InvariantCulture), texts.Culture);
|
||||
}
|
||||
|
||||
/// <summary>A date: <c>13/10/2026</c>.</summary>
|
||||
/// <param name="texts">The texts.</param>
|
||||
/// <param name="date">The date.</param>
|
||||
/// <returns>The text.</returns>
|
||||
public static string Date(this ITexts texts, DateOnly date)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(texts);
|
||||
return date.ToString("dd/MM/yyyy", texts.Culture);
|
||||
}
|
||||
|
||||
/// <summary>A date and time in the given time zone: <c>13/10/2026 14:05</c>.</summary>
|
||||
/// <param name="texts">The texts.</param>
|
||||
/// <param name="utc">The moment, in UTC.</param>
|
||||
/// <param name="zone">The time zone of the user.</param>
|
||||
/// <returns>The text.</returns>
|
||||
public static string DateTime(this ITexts texts, DateTime utc, TimeZoneInfo zone)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(texts);
|
||||
ArgumentNullException.ThrowIfNull(zone);
|
||||
var local = TimeZoneInfo.ConvertTimeFromUtc(System.DateTime.SpecifyKind(utc, DateTimeKind.Utc), zone);
|
||||
return local.ToString("dd/MM/yyyy HH:mm", texts.Culture);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
@@ -13,14 +14,27 @@ namespace Khaemhat.Application.Notifications;
|
||||
/// <param name="Link">A link inside the application.</param>
|
||||
public sealed record NotificationMessage(string Category, NotificationSeverity Severity, string Title, string? Body = null, string? Link = null);
|
||||
|
||||
/// <summary>A notification as its recipient sees it.</summary>
|
||||
/// <param name="Id">The id.</param>
|
||||
/// <param name="Category">The area.</param>
|
||||
/// <param name="Severity">The weight.</param>
|
||||
/// <param name="Title">The title.</param>
|
||||
/// <param name="Body">The text.</param>
|
||||
/// <param name="Link">A link inside the application.</param>
|
||||
/// <param name="CreatedAt">When it was sent (UTC).</param>
|
||||
/// <param name="Read">Whether this user read it.</param>
|
||||
/// <param name="Personal">Addressed to this user only, not to everyone.</param>
|
||||
public sealed record InboxItem(long Id, string Category, NotificationSeverity Severity, string Title, string? Body, string? Link, DateTime CreatedAt, bool Read, bool Personal);
|
||||
|
||||
/// <summary>
|
||||
/// Delivers in-app notifications (SPEC §9; mockup 010): to instance accounts in <c>sys_notifications</c>, to company
|
||||
/// users in the company's <c>notifications</c>. A notification without recipient goes to everyone in the scope.
|
||||
/// Delivery never breaks the caller: a failure is logged.
|
||||
/// </summary>
|
||||
/// <param name="factory">Opens the databases.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
/// <param name="logger">The log.</param>
|
||||
public sealed class NotificationDispatcher(IUnitOfWorkFactory factory, ILogger<NotificationDispatcher> logger)
|
||||
public sealed class NotificationDispatcher(IUnitOfWorkFactory factory, TimeProvider clock, ILogger<NotificationDispatcher> logger)
|
||||
{
|
||||
/// <summary>Notifies instance accounts.</summary>
|
||||
/// <param name="message">The notification.</param>
|
||||
@@ -61,29 +75,114 @@ public sealed class NotificationDispatcher(IUnitOfWorkFactory factory, ILogger<N
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The unread notifications of an instance account (its own and those for everyone).</summary>
|
||||
/// <param name="userId">The account.</param>
|
||||
/// <summary>The most notifications a user sees: the newest ones.</summary>
|
||||
public const int InboxSize = 100;
|
||||
|
||||
/// <summary>The notifications of a user, newest first (mockup 010).</summary>
|
||||
/// <param name="actor">The user: instance accounts read the system ones, company users those of their company.</param>
|
||||
/// <param name="unreadOnly">Only those not read yet.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The notifications, newest first.</returns>
|
||||
public async Task<IReadOnlyList<SystemNotification>> UnreadForInstanceAsync(long userId, CancellationToken cancellationToken = default)
|
||||
/// <returns>The notifications, at most <see cref="InboxSize"/>.</returns>
|
||||
public Task<IReadOnlyList<InboxItem>> InboxAsync(Actor actor, bool unreadOnly = false, CancellationToken cancellationToken = default) =>
|
||||
ScopeOf(actor) switch
|
||||
{
|
||||
({ } scope, { } user, true) => InboxAsync<SystemNotification, SystemNotificationRead>(scope, user, unreadOnly, cancellationToken),
|
||||
({ } scope, { } user, false) => InboxAsync<Notification, NotificationRead>(scope, user, unreadOnly, cancellationToken),
|
||||
_ => Task.FromResult<IReadOnlyList<InboxItem>>([]),
|
||||
};
|
||||
|
||||
/// <summary>Marks a notification as read by the user. A notification for everyone stays unread for the others.</summary>
|
||||
/// <param name="actor">The user.</param>
|
||||
/// <param name="notificationId">The notification.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public Task MarkReadAsync(Actor actor, long notificationId, CancellationToken cancellationToken = default) =>
|
||||
MarkAsync(actor, [notificationId], cancellationToken);
|
||||
|
||||
/// <summary>Marks every notification of the user as read.</summary>
|
||||
/// <param name="actor">The user.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task MarkAllReadAsync(Actor actor, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
|
||||
return (await unitOfWork.Repository<SystemNotification, long>().ListAsync(
|
||||
Query.For<SystemNotification>().Where(n => n.ReadAt == null && (n.RecipientUserId == null || n.RecipientUserId == userId)).OrderByDescending(n => n.Id).Take(100),
|
||||
cancellationToken).ConfigureAwait(false)).Items;
|
||||
var unread = await InboxAsync(actor, unreadOnly: true, cancellationToken).ConfigureAwait(false);
|
||||
await MarkAsync(actor, [.. unread.Select(n => n.Id)], cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The unread notifications of a company user.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="userId">The user.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The notifications, newest first.</returns>
|
||||
public async Task<IReadOnlyList<Notification>> UnreadForUserAsync(string companyCode, long userId, CancellationToken cancellationToken = default)
|
||||
private Task MarkAsync(Actor actor, IReadOnlyList<long> ids, CancellationToken cancellationToken) =>
|
||||
ids.Count == 0
|
||||
? Task.CompletedTask
|
||||
: ScopeOf(actor) switch
|
||||
{
|
||||
({ } scope, { } user, true) => MarkAsync<SystemNotification, SystemNotificationRead>(scope, user, ids, cancellationToken),
|
||||
({ } scope, { } user, false) => MarkAsync<Notification, NotificationRead>(scope, user, ids, cancellationToken),
|
||||
_ => Task.CompletedTask,
|
||||
};
|
||||
|
||||
private static (DatabaseScope? Scope, long? User, bool System) ScopeOf(Actor actor)
|
||||
{
|
||||
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
|
||||
return (await unitOfWork.Repository<Notification, long>().ListAsync(
|
||||
Query.For<Notification>().Where(n => n.ReadAt == null && (n.RecipientUserId == null || n.RecipientUserId == userId)).OrderByDescending(n => n.Id).Take(100),
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
return actor switch
|
||||
{
|
||||
{ SystemUserId: { } id } => (DatabaseScope.System, id, true),
|
||||
{ CompanyUserId: { } id, CompanyCode: { } company } => (DatabaseScope.Company(company), id, false),
|
||||
_ => (null, null, false),
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<InboxItem>> InboxAsync<TNotification, TRead>(DatabaseScope scope, long userId, bool unreadOnly, CancellationToken cancellationToken)
|
||||
where TNotification : NotificationRecord, new()
|
||||
where TRead : NotificationReadRecord, new()
|
||||
{
|
||||
await using var unitOfWork = await factory.CreateAsync(scope, cancellationToken).ConfigureAwait(false);
|
||||
var notifications = (await unitOfWork.Repository<TNotification, long>().ListAsync(
|
||||
Query.For<TNotification>().Where(n => n.RecipientUserId == null || n.RecipientUserId == userId).OrderByDescending(n => n.Id).Take(InboxSize),
|
||||
cancellationToken).ConfigureAwait(false)).Items;
|
||||
var everyone = notifications.Where(n => n.RecipientUserId == null).Select(n => n.Id).ToList();
|
||||
var read = everyone.Count == 0
|
||||
? []
|
||||
: (await unitOfWork.Repository<TRead, long>().ListAsync(
|
||||
Query.For<TRead>().Where(r => r.UserId == userId && everyone.Contains(r.NotificationId)), cancellationToken).ConfigureAwait(false)).Items
|
||||
.Select(r => r.NotificationId).ToHashSet();
|
||||
return [.. notifications
|
||||
.Select(n => new InboxItem(n.Id, n.Category, n.Severity, n.Title, n.Body, n.Link, n.CreatedAt,
|
||||
n.RecipientUserId is null ? read.Contains(n.Id) : n.ReadAt is not null, n.RecipientUserId is not null))
|
||||
.Where(n => !unreadOnly || !n.Read)];
|
||||
}
|
||||
|
||||
private async Task MarkAsync<TNotification, TRead>(DatabaseScope scope, long userId, IReadOnlyList<long> ids, CancellationToken cancellationToken)
|
||||
where TNotification : NotificationRecord, new()
|
||||
where TRead : NotificationReadRecord, new()
|
||||
{
|
||||
await using var unitOfWork = await factory.CreateAsync(scope, cancellationToken).ConfigureAwait(false);
|
||||
var list = ids.ToList();
|
||||
var repository = unitOfWork.Repository<TNotification, long>();
|
||||
var notifications = (await repository.ListAsync(
|
||||
Query.For<TNotification>().Where(n => list.Contains(n.Id) && (n.RecipientUserId == null || n.RecipientUserId == userId)), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var reads = unitOfWork.Repository<TRead, long>();
|
||||
var already = (await reads.ListAsync(Query.For<TRead>().Where(r => r.UserId == userId && list.Contains(r.NotificationId)), cancellationToken).ConfigureAwait(false)).Items
|
||||
.Select(r => r.NotificationId).ToHashSet();
|
||||
var now = clock.GetUtcNow().UtcDateTime;
|
||||
await unitOfWork.InTransactionAsync(
|
||||
async ct =>
|
||||
{
|
||||
foreach (var notification in notifications)
|
||||
{
|
||||
if (notification.RecipientUserId is null)
|
||||
{
|
||||
if (already.Add(notification.Id))
|
||||
{
|
||||
await reads.InsertAsync(new TRead { NotificationId = notification.Id, UserId = userId }, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
else if (notification.ReadAt is null)
|
||||
{
|
||||
notification.ReadAt = now;
|
||||
await repository.UpdateAsync(notification, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static T Fill<T>(T notification, NotificationMessage message, long? recipient)
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace Khaemhat.Application.Preferences;
|
||||
|
||||
/// <summary>The colour theme (SPEC §10.6). <see cref="Auto"/> follows the operating system.</summary>
|
||||
public enum ThemeMode
|
||||
{
|
||||
/// <summary>Follows the operating system.</summary>
|
||||
Auto = 0,
|
||||
|
||||
/// <summary>Light.</summary>
|
||||
Light = 1,
|
||||
|
||||
/// <summary>Dark ("notturno").</summary>
|
||||
Dark = 2,
|
||||
|
||||
/// <summary>High contrast (AAA).</summary>
|
||||
HighContrast = 3,
|
||||
}
|
||||
|
||||
/// <summary>The row height and spacing of lists and forms.</summary>
|
||||
public enum Density
|
||||
{
|
||||
/// <summary>The default spacing.</summary>
|
||||
Comfortable = 0,
|
||||
|
||||
/// <summary>Shorter rows and smaller gaps.</summary>
|
||||
Compact = 1,
|
||||
}
|
||||
|
||||
/// <summary>What the user sees after signing in (SPEC §10.3).</summary>
|
||||
public enum StartPage
|
||||
{
|
||||
/// <summary>The dashboard.</summary>
|
||||
Dashboard = 0,
|
||||
|
||||
/// <summary>The tab that was active at the last sign-out.</summary>
|
||||
LastTab = 1,
|
||||
|
||||
/// <summary>A page chosen by the user (<see cref="UserPreferences.StartPath"/>).</summary>
|
||||
Page = 2,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The interface preferences of a user (SPEC §10.6, mockup 008), stored as key/value pairs in <c>user_settings</c>
|
||||
/// (company users) or <c>sys_user_settings</c> (instance accounts).
|
||||
/// </summary>
|
||||
public sealed record UserPreferences
|
||||
{
|
||||
/// <summary>The eight accents of <c>mockup.css</c>; <c>nilo</c> is the default.</summary>
|
||||
public static readonly IReadOnlyList<string> Accents = ["nilo", "lapislazzuli", "malachite", "turchese", "ocra", "corniola", "ametista", "grafite"];
|
||||
|
||||
/// <summary>The text sizes offered, in percent of the base size.</summary>
|
||||
public static readonly IReadOnlyList<int> TextSizes = [100, 110, 120];
|
||||
|
||||
/// <summary>The preferences of a new user.</summary>
|
||||
public static UserPreferences Default { get; } = new();
|
||||
|
||||
/// <summary>The theme.</summary>
|
||||
public ThemeMode Theme { get; init; } = ThemeMode.Auto;
|
||||
|
||||
/// <summary>The accent, one of <see cref="Accents"/>.</summary>
|
||||
public string Accent { get; init; } = "nilo";
|
||||
|
||||
/// <summary>The density.</summary>
|
||||
public Density Density { get; init; } = Density.Comfortable;
|
||||
|
||||
/// <summary>The text size in percent, one of <see cref="TextSizes"/>.</summary>
|
||||
public int TextSize { get; init; } = 100;
|
||||
|
||||
/// <summary>Whether numbers use tabular figures everywhere (grids always do).</summary>
|
||||
public bool TabularNumbers { get; init; } = true;
|
||||
|
||||
/// <summary>Whether animations and transitions are turned off.</summary>
|
||||
public bool ReducedMotion { get; init; }
|
||||
|
||||
/// <summary>Whether tooltips appear on hover.</summary>
|
||||
public bool Tooltips { get; init; } = true;
|
||||
|
||||
/// <summary>Whether the grid row under the pointer is highlighted.</summary>
|
||||
public bool RowHover { get; init; } = true;
|
||||
|
||||
/// <summary>Whether the side menu is collapsed; <see langword="null"/> lets the window width decide (collapsed under 1100 px).</summary>
|
||||
public bool? MenuCollapsed { get; init; }
|
||||
|
||||
/// <summary>Whether the dashboard is shown on the home page.</summary>
|
||||
public bool ShowDashboard { get; init; } = true;
|
||||
|
||||
/// <summary>The page opened after signing in.</summary>
|
||||
public StartPage StartPage { get; init; } = StartPage.Dashboard;
|
||||
|
||||
/// <summary>The address opened when <see cref="StartPage"/> is <see cref="Preferences.StartPage.Page"/>.</summary>
|
||||
public string? StartPath { get; init; }
|
||||
|
||||
/// <summary>The value of <c>data-theme</c> on the root element.</summary>
|
||||
public string ThemeAttribute => ThemeName(Theme);
|
||||
|
||||
/// <summary>The value of <c>data-density</c> on the root element.</summary>
|
||||
public string DensityAttribute => Density == Density.Compact ? "compact" : "comfortable";
|
||||
|
||||
/// <summary>The attribute value of a theme.</summary>
|
||||
/// <param name="theme">The theme.</param>
|
||||
/// <returns><c>auto</c>, <c>light</c>, <c>dark</c> or <c>high-contrast</c>.</returns>
|
||||
public static string ThemeName(ThemeMode theme) => theme switch
|
||||
{
|
||||
ThemeMode.Light => "light",
|
||||
ThemeMode.Dark => "dark",
|
||||
ThemeMode.HighContrast => "high-contrast",
|
||||
_ => "auto",
|
||||
};
|
||||
|
||||
/// <summary>Reads a theme name; unknown values give <see cref="ThemeMode.Auto"/>.</summary>
|
||||
/// <param name="value">The name.</param>
|
||||
/// <returns>The theme.</returns>
|
||||
public static ThemeMode ParseTheme(string? value) => value switch
|
||||
{
|
||||
"light" => ThemeMode.Light,
|
||||
"dark" => ThemeMode.Dark,
|
||||
"high-contrast" => ThemeMode.HighContrast,
|
||||
_ => ThemeMode.Auto,
|
||||
};
|
||||
|
||||
/// <summary>Reads the preferences from stored values; missing or invalid values keep the default.</summary>
|
||||
/// <param name="values">The stored values by key.</param>
|
||||
/// <returns>The preferences.</returns>
|
||||
public static UserPreferences FromSettings(IReadOnlyDictionary<string, string?> values)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(values);
|
||||
var d = Default;
|
||||
return new UserPreferences
|
||||
{
|
||||
Theme = values.TryGetValue(PreferenceKeys.Theme, out var theme) ? ParseTheme(theme) : d.Theme,
|
||||
Accent = values.TryGetValue(PreferenceKeys.Accent, out var accent) && accent is not null && Accents.Contains(accent) ? accent : d.Accent,
|
||||
Density = values.TryGetValue(PreferenceKeys.Density, out var density) && density == "compact" ? Density.Compact : d.Density,
|
||||
TextSize = values.TryGetValue(PreferenceKeys.TextSize, out var size)
|
||||
&& int.TryParse(size, NumberStyles.None, CultureInfo.InvariantCulture, out var s) && TextSizes.Contains(s) ? s : d.TextSize,
|
||||
TabularNumbers = Bool(values, PreferenceKeys.TabularNumbers) ?? d.TabularNumbers,
|
||||
ReducedMotion = Bool(values, PreferenceKeys.ReducedMotion) ?? d.ReducedMotion,
|
||||
Tooltips = Bool(values, PreferenceKeys.Tooltips) ?? d.Tooltips,
|
||||
RowHover = Bool(values, PreferenceKeys.RowHover) ?? d.RowHover,
|
||||
MenuCollapsed = Bool(values, PreferenceKeys.MenuCollapsed),
|
||||
ShowDashboard = Bool(values, PreferenceKeys.ShowDashboard) ?? d.ShowDashboard,
|
||||
StartPage = values.TryGetValue(PreferenceKeys.StartPage, out var start)
|
||||
? start switch
|
||||
{
|
||||
"last-tab" => StartPage.LastTab,
|
||||
"page" => StartPage.Page,
|
||||
_ => StartPage.Dashboard,
|
||||
}
|
||||
: d.StartPage,
|
||||
StartPath = values.TryGetValue(PreferenceKeys.StartPath, out var path) && IsLocalPath(path) ? path : null,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The values to store.</summary>
|
||||
/// <returns>The values by key; <see langword="null"/> removes the key.</returns>
|
||||
public IReadOnlyDictionary<string, string?> ToSettings() => new Dictionary<string, string?>(StringComparer.Ordinal)
|
||||
{
|
||||
[PreferenceKeys.Theme] = ThemeAttribute,
|
||||
[PreferenceKeys.Accent] = Accents.Contains(Accent) ? Accent : Default.Accent,
|
||||
[PreferenceKeys.Density] = DensityAttribute,
|
||||
[PreferenceKeys.TextSize] = TextSize.ToString(CultureInfo.InvariantCulture),
|
||||
[PreferenceKeys.TabularNumbers] = Text(TabularNumbers),
|
||||
[PreferenceKeys.ReducedMotion] = Text(ReducedMotion),
|
||||
[PreferenceKeys.Tooltips] = Text(Tooltips),
|
||||
[PreferenceKeys.RowHover] = Text(RowHover),
|
||||
[PreferenceKeys.MenuCollapsed] = MenuCollapsed is { } collapsed ? Text(collapsed) : null,
|
||||
[PreferenceKeys.ShowDashboard] = Text(ShowDashboard),
|
||||
[PreferenceKeys.StartPage] = StartPage switch
|
||||
{
|
||||
StartPage.LastTab => "last-tab",
|
||||
StartPage.Page => "page",
|
||||
_ => "dashboard",
|
||||
},
|
||||
[PreferenceKeys.StartPath] = IsLocalPath(StartPath) ? StartPath : null,
|
||||
};
|
||||
|
||||
/// <summary>Whether an address is a path inside the application (no scheme, no host): the start page cannot leave the site.</summary>
|
||||
/// <param name="path">The address.</param>
|
||||
/// <returns><see langword="true"/> for <c>/something</c>.</returns>
|
||||
public static bool IsLocalPath(string? path) =>
|
||||
path is { Length: > 0 and <= 400 }
|
||||
&& path[0] == '/'
|
||||
&& (path.Length == 1 || (path[1] != '/' && path[1] != '\\'))
|
||||
&& !path.Contains("://", StringComparison.Ordinal);
|
||||
|
||||
private static bool? Bool(IReadOnlyDictionary<string, string?> values, string key) =>
|
||||
values.TryGetValue(key, out var value)
|
||||
? value switch
|
||||
{
|
||||
"true" => true,
|
||||
"false" => false,
|
||||
_ => null,
|
||||
}
|
||||
: null;
|
||||
|
||||
private static string Text(bool value) => value ? "true" : "false";
|
||||
}
|
||||
|
||||
/// <summary>The keys of <see cref="UserPreferences"/> in <c>user_settings</c>.</summary>
|
||||
public static class PreferenceKeys
|
||||
{
|
||||
/// <summary>Theme.</summary>
|
||||
public const string Theme = "ui.theme";
|
||||
|
||||
/// <summary>Accent.</summary>
|
||||
public const string Accent = "ui.accent";
|
||||
|
||||
/// <summary>Density.</summary>
|
||||
public const string Density = "ui.density";
|
||||
|
||||
/// <summary>Text size.</summary>
|
||||
public const string TextSize = "ui.text-size";
|
||||
|
||||
/// <summary>Tabular numbers.</summary>
|
||||
public const string TabularNumbers = "ui.tabular-numbers";
|
||||
|
||||
/// <summary>Reduced motion.</summary>
|
||||
public const string ReducedMotion = "ui.reduced-motion";
|
||||
|
||||
/// <summary>Tooltips.</summary>
|
||||
public const string Tooltips = "ui.tooltips";
|
||||
|
||||
/// <summary>Row highlight in grids.</summary>
|
||||
public const string RowHover = "ui.row-hover";
|
||||
|
||||
/// <summary>Menu state.</summary>
|
||||
public const string MenuCollapsed = "ui.menu-collapsed";
|
||||
|
||||
/// <summary>Dashboard on or off.</summary>
|
||||
public const string ShowDashboard = "home.show-dashboard";
|
||||
|
||||
/// <summary>Start page.</summary>
|
||||
public const string StartPage = "home.start-page";
|
||||
|
||||
/// <summary>Start address.</summary>
|
||||
public const string StartPath = "home.start-path";
|
||||
|
||||
/// <summary>The open tabs at the last sign-out (JSON array of addresses).</summary>
|
||||
public const string OpenTabs = "ui.open-tabs";
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Preferences;
|
||||
|
||||
/// <summary>
|
||||
/// Reads and writes the preferences of the signed-in user (SPEC §10.6). Instance accounts keep theirs in the system
|
||||
/// database, so they follow them in every company; company users keep them in the company database.
|
||||
/// </summary>
|
||||
/// <param name="factory">Opens the databases.</param>
|
||||
public sealed class UserSettingsService(IUnitOfWorkFactory factory)
|
||||
{
|
||||
/// <summary>The longest value accepted (dashboard and grid layouts are JSON).</summary>
|
||||
public const int MaxValueLength = 64 * 1024;
|
||||
|
||||
/// <summary>Reads every preference of the actor.</summary>
|
||||
/// <param name="actor">The signed-in user.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The values by key; empty for the instance itself.</returns>
|
||||
public async Task<IReadOnlyDictionary<string, string?>> GetAllAsync(Actor actor, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
if (Owner(actor) is not { } owner)
|
||||
{
|
||||
return new Dictionary<string, string?>(StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
await using var unitOfWork = await factory.CreateAsync(owner.Scope, cancellationToken).ConfigureAwait(false);
|
||||
IReadOnlyList<UserSettingRecord> rows = owner.Scope.IsSystem
|
||||
? await ListAsync<SystemUserSetting>(unitOfWork, owner.UserId, cancellationToken).ConfigureAwait(false)
|
||||
: await ListAsync<UserSetting>(unitOfWork, owner.UserId, cancellationToken).ConfigureAwait(false);
|
||||
return rows.ToDictionary(r => r.Key, r => r.Value, StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>Reads one preference.</summary>
|
||||
/// <param name="actor">The signed-in user.</param>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The value, or <see langword="null"/>.</returns>
|
||||
public async Task<string?> GetAsync(Actor actor, string key, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(key);
|
||||
var all = await GetAllAsync(actor, cancellationToken).ConfigureAwait(false);
|
||||
return all.TryGetValue(key, out var value) ? value : null;
|
||||
}
|
||||
|
||||
/// <summary>Writes one preference; <see langword="null"/> removes it.</summary>
|
||||
/// <param name="actor">The signed-in user.</param>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <param name="value">The value.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public Task SetAsync(Actor actor, string key, string? value, CancellationToken cancellationToken = default) =>
|
||||
SetManyAsync(actor, new Dictionary<string, string?>(StringComparer.Ordinal) { [key] = value }, cancellationToken);
|
||||
|
||||
/// <summary>Writes several preferences in one transaction; <see langword="null"/> values remove the key.</summary>
|
||||
/// <param name="actor">The signed-in user.</param>
|
||||
/// <param name="values">The values by key.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task SetManyAsync(Actor actor, IReadOnlyDictionary<string, string?> values, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
ArgumentNullException.ThrowIfNull(values);
|
||||
foreach (var (key, value) in values)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(key) || key.Length > 200)
|
||||
{
|
||||
throw new ValidationFailedException("settings.key_invalid");
|
||||
}
|
||||
|
||||
if (value is { Length: > MaxValueLength })
|
||||
{
|
||||
throw new ValidationFailedException("settings.value_too_long");
|
||||
}
|
||||
}
|
||||
|
||||
if (Owner(actor) is not { } owner || values.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await using var unitOfWork = await factory.CreateAsync(owner.Scope, cancellationToken).ConfigureAwait(false);
|
||||
await unitOfWork.InTransactionAsync(
|
||||
ct => owner.Scope.IsSystem
|
||||
? WriteAsync<SystemUserSetting>(unitOfWork, owner.UserId, values, ct)
|
||||
: WriteAsync<UserSetting>(unitOfWork, owner.UserId, values, ct),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Reads the interface preferences.</summary>
|
||||
/// <param name="actor">The signed-in user.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The preferences, with defaults for what was never set.</returns>
|
||||
public async Task<UserPreferences> GetPreferencesAsync(Actor actor, CancellationToken cancellationToken = default) =>
|
||||
UserPreferences.FromSettings(await GetAllAsync(actor, cancellationToken).ConfigureAwait(false));
|
||||
|
||||
/// <summary>Writes the interface preferences.</summary>
|
||||
/// <param name="actor">The signed-in user.</param>
|
||||
/// <param name="preferences">The preferences.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public Task SavePreferencesAsync(Actor actor, UserPreferences preferences, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(preferences);
|
||||
return SetManyAsync(actor, preferences.ToSettings(), cancellationToken);
|
||||
}
|
||||
|
||||
private static (DatabaseScope Scope, long UserId)? Owner(Actor actor) => actor switch
|
||||
{
|
||||
{ SystemUserId: { } id } => (DatabaseScope.System, id),
|
||||
{ CompanyUserId: { } id, CompanyCode: { } code } => (DatabaseScope.Company(code), id),
|
||||
_ => null,
|
||||
};
|
||||
|
||||
private static async Task<IReadOnlyList<T>> ListAsync<T>(IUnitOfWork unitOfWork, long userId, CancellationToken cancellationToken)
|
||||
where T : UserSettingRecord, new() =>
|
||||
(await unitOfWork.Repository<T, long>().ListAsync(Query.For<T>().Where(s => s.UserId == userId), cancellationToken).ConfigureAwait(false)).Items;
|
||||
|
||||
private static async Task WriteAsync<T>(IUnitOfWork unitOfWork, long userId, IReadOnlyDictionary<string, string?> values, CancellationToken cancellationToken)
|
||||
where T : UserSettingRecord, new()
|
||||
{
|
||||
var repository = unitOfWork.Repository<T, long>();
|
||||
var existing = (await ListAsync<T>(unitOfWork, userId, cancellationToken).ConfigureAwait(false)).ToDictionary(r => r.Key, StringComparer.Ordinal);
|
||||
foreach (var (key, value) in values)
|
||||
{
|
||||
if (existing.TryGetValue(key, out var row))
|
||||
{
|
||||
if (value is null)
|
||||
{
|
||||
await repository.DeleteAsync(row.Id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else if (!string.Equals(row.Value, value, StringComparison.Ordinal))
|
||||
{
|
||||
row.Value = value;
|
||||
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
else if (value is not null)
|
||||
{
|
||||
await repository.InsertAsync(new T { UserId = userId, Key = key, Value = value }, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
namespace Khaemhat.Application.Querying;
|
||||
|
||||
/// <summary>
|
||||
/// A <see cref="ListSource{T}"/> over rows kept in memory (small tables, catalogs, tests). The rows a request selects
|
||||
/// are kept until the search, filters or ordering change, so scrolling through the pages of 100,000 rows only cuts
|
||||
/// slices.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The row type.</typeparam>
|
||||
/// <param name="rows">The rows.</param>
|
||||
/// <param name="fields">The fields.</param>
|
||||
public sealed class InMemoryListSource<T>(IReadOnlyList<T> rows, ListFields<T> fields)
|
||||
where T : class
|
||||
{
|
||||
private readonly Lock _lock = new();
|
||||
private (ListQuery Query, IReadOnlyList<T> Rows)? _last;
|
||||
|
||||
/// <summary>The fields.</summary>
|
||||
public ListFields<T> Fields => fields;
|
||||
|
||||
/// <summary>Answers a request.</summary>
|
||||
/// <param name="query">The request.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The page.</returns>
|
||||
public Task<ListPage<T>> QueryAsync(ListQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(query);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
return Task.FromResult(fields.Page(Selected(query), query));
|
||||
}
|
||||
|
||||
/// <summary>Every row a request selects, in order, for exports.</summary>
|
||||
/// <param name="query">The request; its page is ignored.</param>
|
||||
/// <returns>The rows.</returns>
|
||||
public IReadOnlyList<T> All(ListQuery query) => Selected(query);
|
||||
|
||||
private IReadOnlyList<T> Selected(ListQuery query)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_last is { } last && last.Query.SameRows(query))
|
||||
{
|
||||
return last.Rows;
|
||||
}
|
||||
}
|
||||
|
||||
var selected = fields.Select(rows, query);
|
||||
lock (_lock)
|
||||
{
|
||||
_last = (query, selected);
|
||||
}
|
||||
|
||||
return selected;
|
||||
}
|
||||
}
|
||||