Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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,84 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [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
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -385,6 +385,8 @@ Migrazioni applicate in ordine:
|
||||
- `core` 20261111009 `create_sys_security_audit` (M20261111_009_CreateSysSecurityAudit)
|
||||
- `core` 20261111010 `create_sys_scheduler` (M20261111_010_CreateSysScheduler)
|
||||
- `core` 20261111011 `create_sys_notifications` (M20261111_011_CreateSysNotifications)
|
||||
- `core` 20261111012 `create_sys_user_settings` (M20261111_012_CreateSysUserSettings)
|
||||
- `core` 20261111013 `create_sys_notification_reads` (M20261111_013_CreateSysNotificationReads)
|
||||
|
||||
#### `schema_version`
|
||||
|
||||
@@ -517,6 +519,22 @@ Chiave primaria: `module`, `version`.
|
||||
- indice `ix_sys_log_section_at` su `section`, `at`
|
||||
- indice `ix_sys_log_trace_id` su `trace_id`
|
||||
|
||||
#### `sys_notification_reads`
|
||||
|
||||
| Colonna | Tipo | Null | Default | Note |
|
||||
|---|---|---|---|---|
|
||||
| `id` | Int64 | no | | chiave primaria, identity |
|
||||
| `notification_id` | Int64 | no | | |
|
||||
| `user_id` | Int64 | no | | |
|
||||
| `created_at` | DateTimeUtc | no | | |
|
||||
| `created_by` | String(100) | sì | | |
|
||||
| `updated_at` | DateTimeUtc | sì | | |
|
||||
| `updated_by` | String(100) | sì | | |
|
||||
| `row_version` | Int64 | no | `1` | |
|
||||
|
||||
- indice `ix_sys_notification_reads_user_id` su `user_id`
|
||||
- indice unico `ux_sys_notification_reads_notification_user` su `notification_id`, `user_id`
|
||||
|
||||
#### `sys_notifications`
|
||||
|
||||
| Colonna | Tipo | Null | Default | Note |
|
||||
@@ -640,6 +658,22 @@ Chiave primaria: `module`, `version`.
|
||||
|
||||
- indice unico `ux_sys_settings_key` su `key`
|
||||
|
||||
#### `sys_user_settings`
|
||||
|
||||
| Colonna | Tipo | Null | Default | Note |
|
||||
|---|---|---|---|---|
|
||||
| `id` | Int64 | no | | chiave primaria, identity |
|
||||
| `user_id` | Int64 | no | | |
|
||||
| `key` | String(200) | no | | |
|
||||
| `value` | Text | sì | | |
|
||||
| `created_at` | DateTimeUtc | no | | |
|
||||
| `created_by` | String(100) | sì | | |
|
||||
| `updated_at` | DateTimeUtc | sì | | |
|
||||
| `updated_by` | String(100) | sì | | |
|
||||
| `row_version` | Int64 | no | `1` | |
|
||||
|
||||
- indice unico `ux_sys_user_settings_user_id_key` su `user_id`, `key`
|
||||
|
||||
#### `sys_users`
|
||||
|
||||
| Colonna | Tipo | Null | Default | Note |
|
||||
@@ -683,6 +717,39 @@ Migrazioni applicate in ordine:
|
||||
- `core` 20261111003 `create_roles` (M20261111_003_CreateRoles)
|
||||
- `core` 20261111004 `create_audit_log` (M20261111_004_CreateAuditLog)
|
||||
- `core` 20261111005 `create_notifications` (M20261111_005_CreateNotifications)
|
||||
- `core` 20261111006 `create_user_settings` (M20261111_006_CreateUserSettings)
|
||||
- `core` 20261111007 `create_attachments` (M20261111_007_CreateAttachments)
|
||||
- `core` 20261111008 `create_company_settings` (M20261111_008_CreateCompanySettings)
|
||||
- `core` 20261111009 `create_notification_reads` (M20261111_009_CreateNotificationReads)
|
||||
|
||||
#### `attachments`
|
||||
|
||||
| Colonna | Tipo | Null | Default | Note |
|
||||
|---|---|---|---|---|
|
||||
| `id` | Int64 | no | | chiave primaria, identity |
|
||||
| `entity` | String(100) | no | | |
|
||||
| `entity_id` | Int64 | no | | |
|
||||
| `kind` | String(40) | no | | |
|
||||
| `name` | String(255) | no | | |
|
||||
| `mime` | String(150) | no | | |
|
||||
| `size` | Int64 | no | | |
|
||||
| `sha256` | String(64) | no | | |
|
||||
| `version` | Int32 | no | | |
|
||||
| `version_key` | String(300) | no | | |
|
||||
| `generated_by` | String(100) | sì | | |
|
||||
| `storage_key` | String(60) | no | | |
|
||||
| `user_name` | String(100) | sì | | |
|
||||
| `locked` | Bool | no | `false` | |
|
||||
| `deleted_at` | DateTimeUtc | sì | | |
|
||||
| `created_at` | DateTimeUtc | no | | |
|
||||
| `created_by` | String(100) | sì | | |
|
||||
| `updated_at` | DateTimeUtc | sì | | |
|
||||
| `updated_by` | String(100) | sì | | |
|
||||
| `row_version` | Int64 | no | `1` | |
|
||||
|
||||
- indice `ix_attachments_deleted_at` su `deleted_at`
|
||||
- indice `ix_attachments_entity_entity_id` su `entity`, `entity_id`
|
||||
- indice unico `ux_attachments_entity_entity_id_version_key_version` su `entity`, `entity_id`, `version_key`, `version`
|
||||
|
||||
#### `audit_log`
|
||||
|
||||
@@ -700,6 +767,37 @@ Migrazioni applicate in ordine:
|
||||
- indice `ix_audit_log_at` su `at`
|
||||
- indice `ix_audit_log_entity_entity_id` su `entity`, `entity_id`
|
||||
|
||||
#### `company_settings`
|
||||
|
||||
| Colonna | Tipo | Null | Default | Note |
|
||||
|---|---|---|---|---|
|
||||
| `id` | Int64 | no | | chiave primaria, identity |
|
||||
| `key` | String(200) | no | | |
|
||||
| `value` | Text | sì | | |
|
||||
| `created_at` | DateTimeUtc | no | | |
|
||||
| `created_by` | String(100) | sì | | |
|
||||
| `updated_at` | DateTimeUtc | sì | | |
|
||||
| `updated_by` | String(100) | sì | | |
|
||||
| `row_version` | Int64 | no | `1` | |
|
||||
|
||||
- indice unico `ux_company_settings_key` su `key`
|
||||
|
||||
#### `notification_reads`
|
||||
|
||||
| Colonna | Tipo | Null | Default | Note |
|
||||
|---|---|---|---|---|
|
||||
| `id` | Int64 | no | | chiave primaria, identity |
|
||||
| `notification_id` | Int64 | no | | |
|
||||
| `user_id` | Int64 | no | | |
|
||||
| `created_at` | DateTimeUtc | no | | |
|
||||
| `created_by` | String(100) | sì | | |
|
||||
| `updated_at` | DateTimeUtc | sì | | |
|
||||
| `updated_by` | String(100) | sì | | |
|
||||
| `row_version` | Int64 | no | `1` | |
|
||||
|
||||
- indice `ix_notification_reads_user_id` su `user_id`
|
||||
- indice unico `ux_notification_reads_notification_user` su `notification_id`, `user_id`
|
||||
|
||||
#### `notifications`
|
||||
|
||||
| Colonna | Tipo | Null | Default | Note |
|
||||
@@ -821,6 +919,22 @@ Chiave primaria: `module`, `version`.
|
||||
- indice `ix_user_sessions_user_id` su `user_id`
|
||||
- indice unico `ux_user_sessions_token_hash` su `token_hash`
|
||||
|
||||
#### `user_settings`
|
||||
|
||||
| Colonna | Tipo | Null | Default | Note |
|
||||
|---|---|---|---|---|
|
||||
| `id` | Int64 | no | | chiave primaria, identity |
|
||||
| `user_id` | Int64 | no | | |
|
||||
| `key` | String(200) | no | | |
|
||||
| `value` | Text | sì | | |
|
||||
| `created_at` | DateTimeUtc | no | | |
|
||||
| `created_by` | String(100) | sì | | |
|
||||
| `updated_at` | DateTimeUtc | sì | | |
|
||||
| `updated_by` | String(100) | sì | | |
|
||||
| `row_version` | Int64 | no | `1` | |
|
||||
|
||||
- indice unico `ux_user_settings_user_id_key` su `user_id`, `key`
|
||||
|
||||
#### `users`
|
||||
|
||||
| Colonna | Tipo | Null | Default | Note |
|
||||
|
||||
@@ -3,16 +3,18 @@
|
||||
> 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.
|
||||
**Milestone corrente:** M4 — Tabelle, anagrafiche, articoli (issue #37-#46, nel progetto in *Da fare*). M3 chiusa:
|
||||
PR #119 in `main`, tag `v0.3.0`, immagine e release.
|
||||
**Prossimo passo:** M4, a partire dal pacchetto fiscale (#37) e dal profilo azienda (#38). #35 (PNG ad alta
|
||||
risoluzione) resta aperta e non blocca.
|
||||
Da recuperare: misure di riferimento su PostgreSQL in `docs/DATA-MODEL.md` §6.1; indicatore di robustezza della
|
||||
password (mockup 003); schede *Layout salvati* (M4) e *Notifiche* (con le e-mail, M5) del profilo; rinomina e
|
||||
filtro predefinito nei radar.
|
||||
|
||||
## Fatto
|
||||
|
||||
- Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E6.
|
||||
- ADR 0001-0019.
|
||||
- ADR 0001-0024.
|
||||
- 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,16 @@ 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.
|
||||
- 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).
|
||||
@@ -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,6 +1,6 @@
|
||||
# Changelog
|
||||
|
||||
> **Stato:** completa per 0.1.0 · **Ultima revisione:** 2026-11-11
|
||||
> **Stato:** completa per 0.3.0 · **Ultima revisione:** 2026-11-11
|
||||
|
||||
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,14 @@ Le novità di ogni versione sono nel file
|
||||
|
||||
| Versione | Data | Contenuto |
|
||||
|---|---|---|
|
||||
| 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 @@
|
||||
# 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
|
||||
|
||||
|
||||
@@ -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-11 · **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,8 @@ 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*.
|
||||
|
||||
**Completate:** M0 (0.0.1), M1 (0.1.0), M2 (0.2.0), M3 (0.3.0). **In corso:** M4.
|
||||
|
||||
| # | 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 |
|
||||
|
||||
|
After Width: | Height: | Size: 122 KiB |
|
After Width: | Height: | Size: 119 KiB |
|
After Width: | Height: | Size: 84 KiB |
|
After Width: | Height: | Size: 159 KiB |
|
After Width: | Height: | Size: 93 KiB |
|
After Width: | Height: | Size: 89 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: 99 KiB |
|
After Width: | Height: | Size: 93 KiB |
@@ -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,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -49,12 +49,13 @@ 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).</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),
|
||||
];
|
||||
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,446 @@
|
||||
using System.Globalization;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Querying;
|
||||
|
||||
/// <summary>
|
||||
/// The fields a list can search, filter, order and total, each bound to a property of the row. One description serves
|
||||
/// both sides: <see cref="Apply(Query{T}, ListQuery)"/> adds conditions, ordering and page to a repository query (SQL,
|
||||
/// case-insensitive LIKE for texts), <see cref="Apply(IEnumerable{T}, ListQuery)"/> runs the same request on rows in
|
||||
/// memory.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The row type.</typeparam>
|
||||
public sealed class ListFields<T>
|
||||
where T : class
|
||||
{
|
||||
private readonly Dictionary<string, ListField<T>> _fields = new(StringComparer.Ordinal);
|
||||
private readonly List<ListField<T>> _ordered = [];
|
||||
|
||||
/// <summary>The fields, in the order added.</summary>
|
||||
public IReadOnlyList<ListField<T>> Fields => _ordered;
|
||||
|
||||
/// <summary>The ordering used when the request has none, so that pages do not overlap.</summary>
|
||||
public IReadOnlyList<ListSort> DefaultSort { get; private set; } = [];
|
||||
|
||||
/// <summary>Adds a field.</summary>
|
||||
/// <typeparam name="TValue">The type of the property.</typeparam>
|
||||
/// <param name="id">The id used in filters and orderings.</param>
|
||||
/// <param name="selector">The property.</param>
|
||||
/// <param name="searchable">Whether the search box looks in it (texts only).</param>
|
||||
/// <param name="total">Whether the page carries its sum (numbers only).</param>
|
||||
/// <returns>This, to chain.</returns>
|
||||
public ListFields<T> Add<TValue>(string id, Expression<Func<T, TValue>> selector, bool searchable = false, bool total = false)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(id);
|
||||
ArgumentNullException.ThrowIfNull(selector);
|
||||
if (searchable && typeof(TValue) != typeof(string))
|
||||
{
|
||||
throw new ArgumentException($"Only text fields can be searched: {id}.", nameof(searchable));
|
||||
}
|
||||
|
||||
if (total && ListField<T, TValue>.Numeric is null)
|
||||
{
|
||||
throw new ArgumentException($"Only number fields can be totalled: {id}.", nameof(total));
|
||||
}
|
||||
|
||||
var field = new ListField<T, TValue>(id, selector, searchable, total);
|
||||
_fields.Add(id, field);
|
||||
_ordered.Add(field);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>Sets the ordering used when the request has none.</summary>
|
||||
/// <param name="sort">The ordering; the last field should be unique (the code or the id).</param>
|
||||
/// <returns>This, to chain.</returns>
|
||||
public ListFields<T> OrderByDefault(params ListSort[] sort)
|
||||
{
|
||||
foreach (var item in sort)
|
||||
{
|
||||
_ = Get(item.Field);
|
||||
}
|
||||
|
||||
DefaultSort = sort;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>A field by id.</summary>
|
||||
/// <param name="id">The id.</param>
|
||||
/// <returns>The field, or <see langword="null"/>.</returns>
|
||||
public ListField<T>? Find(string id) => _fields.GetValueOrDefault(id);
|
||||
|
||||
/// <summary>Whether a filter can be applied: known field, operator fit for its type, readable values.</summary>
|
||||
/// <param name="filter">The filter, for example one read from the saved filters.</param>
|
||||
/// <returns>Whether it is valid.</returns>
|
||||
public bool IsValid(ListFilter filter)
|
||||
{
|
||||
try
|
||||
{
|
||||
_ = Condition(Expression.Parameter(typeof(T), "x"), filter, inMemory: true);
|
||||
return true;
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Adds the conditions, the ordering and the page of a request to a repository query.</summary>
|
||||
/// <param name="query">The query, possibly with conditions of its own (the company, the state...).</param>
|
||||
/// <param name="list">The request.</param>
|
||||
/// <returns>The query.</returns>
|
||||
public Query<T> Apply(Query<T> query, ListQuery list)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(query);
|
||||
ArgumentNullException.ThrowIfNull(list);
|
||||
if (Predicate(list, inMemory: false) is { } predicate)
|
||||
{
|
||||
query = query.Where(predicate);
|
||||
}
|
||||
|
||||
foreach (var sort in SortOf(list))
|
||||
{
|
||||
query = Get(sort.Field).OrderQuery(query, sort.Descending);
|
||||
}
|
||||
|
||||
return query.Page(Math.Max(0, list.Offset), Math.Clamp(list.Limit, 1, ListQuery.MaxLimit));
|
||||
}
|
||||
|
||||
/// <summary>Runs a request on rows in memory: filters, totals, ordering and page.</summary>
|
||||
/// <param name="source">The rows.</param>
|
||||
/// <param name="list">The request.</param>
|
||||
/// <returns>The page.</returns>
|
||||
public ListPage<T> Apply(IEnumerable<T> source, ListQuery list)
|
||||
{
|
||||
var rows = Select(source, list);
|
||||
return Page(rows, list);
|
||||
}
|
||||
|
||||
/// <summary>The rows a request selects, filtered and ordered, without paging (for exports and caches).</summary>
|
||||
/// <param name="source">The rows.</param>
|
||||
/// <param name="list">The request.</param>
|
||||
/// <returns>The rows.</returns>
|
||||
public IReadOnlyList<T> Select(IEnumerable<T> source, ListQuery list)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(source);
|
||||
ArgumentNullException.ThrowIfNull(list);
|
||||
if (Predicate(list, inMemory: true) is { } predicate)
|
||||
{
|
||||
source = source.Where(predicate.Compile());
|
||||
}
|
||||
|
||||
IOrderedEnumerable<T>? ordered = null;
|
||||
foreach (var sort in SortOf(list))
|
||||
{
|
||||
ordered = Get(sort.Field).OrderMemory(source, ordered, sort.Descending);
|
||||
}
|
||||
|
||||
return [.. ordered ?? source];
|
||||
}
|
||||
|
||||
/// <summary>A page of rows already selected and ordered by <see cref="Select"/>, with the totals.</summary>
|
||||
/// <param name="rows">The rows.</param>
|
||||
/// <param name="list">The request.</param>
|
||||
/// <returns>The page.</returns>
|
||||
public ListPage<T> Page(IReadOnlyList<T> rows, ListQuery list)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(rows);
|
||||
ArgumentNullException.ThrowIfNull(list);
|
||||
var totals = _ordered.Where(f => f.Total).ToDictionary(f => f.Id, f => f.Sum(rows), StringComparer.Ordinal);
|
||||
var limit = Math.Clamp(list.Limit, 1, ListQuery.MaxLimit);
|
||||
IReadOnlyList<T> items = [.. rows.Skip(Math.Max(0, list.Offset)).Take(limit)];
|
||||
return new ListPage<T>(items, rows.Count, totals);
|
||||
}
|
||||
|
||||
/// <summary>The condition of a request (search and filters), or <see langword="null"/> when it selects everything.</summary>
|
||||
/// <param name="list">The request.</param>
|
||||
/// <param name="inMemory">Whether for rows in memory (texts compared ignoring case) or for SQL.</param>
|
||||
/// <returns>The predicate.</returns>
|
||||
public Expression<Func<T, bool>>? Predicate(ListQuery list, bool inMemory)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(list);
|
||||
var row = Expression.Parameter(typeof(T), "x");
|
||||
var parts = new List<Expression>();
|
||||
|
||||
var search = list.Search?.Trim();
|
||||
if (!string.IsNullOrEmpty(search))
|
||||
{
|
||||
// Every word must appear in some searchable field: "rossi torino" finds Rossi of Torino.
|
||||
foreach (var word in search.Split(' ', StringSplitOptions.RemoveEmptyEntries).Take(8))
|
||||
{
|
||||
var any = _ordered.Where(f => f.Searchable).Select(f => f.Search(row, word, inMemory)).Aggregate((Expression?)null, (a, b) => a is null ? b : Expression.OrElse(a, b));
|
||||
if (any is not null)
|
||||
{
|
||||
parts.Add(any);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
parts.AddRange(list.Filters.Select(filter => Condition(row, filter, inMemory)));
|
||||
return parts.Count == 0 ? null : Expression.Lambda<Func<T, bool>>(parts.Aggregate(Expression.AndAlso), row);
|
||||
}
|
||||
|
||||
private Expression Condition(ParameterExpression row, ListFilter filter, bool inMemory) =>
|
||||
(Find(filter.Field) ?? throw new ArgumentException($"Unknown field: {filter.Field}.", nameof(filter))).Condition(row, filter, inMemory);
|
||||
|
||||
private ListField<T> Get(string id) => Find(id) ?? throw new ArgumentException($"Unknown field: {id}.", nameof(id));
|
||||
|
||||
private List<ListSort> SortOf(ListQuery list)
|
||||
{
|
||||
var sort = list.Sort.Where(s => _fields.ContainsKey(s.Field)).ToList();
|
||||
foreach (var fallback in DefaultSort)
|
||||
{
|
||||
if (!sort.Any(s => s.Field == fallback.Field))
|
||||
{
|
||||
sort.Add(fallback);
|
||||
}
|
||||
}
|
||||
|
||||
return sort;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A field of a <see cref="ListFields{T}"/>.</summary>
|
||||
/// <typeparam name="T">The row type.</typeparam>
|
||||
public abstract class ListField<T>
|
||||
where T : class
|
||||
{
|
||||
private protected ListField(string id, Type valueType, bool searchable, bool total)
|
||||
{
|
||||
Id = id;
|
||||
ValueType = valueType;
|
||||
Searchable = searchable;
|
||||
Total = total;
|
||||
}
|
||||
|
||||
/// <summary>The id.</summary>
|
||||
public string Id { get; }
|
||||
|
||||
/// <summary>The type of the property (nullable included).</summary>
|
||||
public Type ValueType { get; }
|
||||
|
||||
/// <summary>Whether the search box looks in it.</summary>
|
||||
public bool Searchable { get; }
|
||||
|
||||
/// <summary>Whether the page carries its sum.</summary>
|
||||
public bool Total { get; }
|
||||
|
||||
/// <summary>The value of the field in a row.</summary>
|
||||
/// <param name="row">The row.</param>
|
||||
/// <returns>The value.</returns>
|
||||
public abstract object? ValueOf(T row);
|
||||
|
||||
internal abstract Expression Condition(ParameterExpression row, ListFilter filter, bool inMemory);
|
||||
|
||||
internal abstract Expression Search(ParameterExpression row, string text, bool inMemory);
|
||||
|
||||
internal abstract Query<T> OrderQuery(Query<T> query, bool descending);
|
||||
|
||||
internal abstract IOrderedEnumerable<T> OrderMemory(IEnumerable<T> source, IOrderedEnumerable<T>? ordered, bool descending);
|
||||
|
||||
internal abstract decimal Sum(IEnumerable<T> rows);
|
||||
}
|
||||
|
||||
/// <summary>A field bound to a property of type <typeparamref name="TValue"/>.</summary>
|
||||
/// <typeparam name="T">The row type.</typeparam>
|
||||
/// <typeparam name="TValue">The property type.</typeparam>
|
||||
internal sealed class ListField<T, TValue> : ListField<T>
|
||||
where T : class
|
||||
{
|
||||
private static readonly MethodInfo ContainsIgnoreCase = typeof(string).GetMethod(nameof(string.Contains), [typeof(string), typeof(StringComparison)])!;
|
||||
private static readonly MethodInfo StartsIgnoreCase = typeof(string).GetMethod(nameof(string.StartsWith), [typeof(string), typeof(StringComparison)])!;
|
||||
private static readonly MethodInfo ContainsText = typeof(string).GetMethod(nameof(string.Contains), [typeof(string)])!;
|
||||
private static readonly MethodInfo StartsText = typeof(string).GetMethod(nameof(string.StartsWith), [typeof(string)])!;
|
||||
private static readonly MethodInfo EnumerableContains = typeof(Enumerable).GetMethods()
|
||||
.Single(m => m.Name == nameof(Enumerable.Contains) && m.GetParameters().Length == 2).MakeGenericMethod(typeof(TValue));
|
||||
|
||||
private static readonly Type Underlying = Nullable.GetUnderlyingType(typeof(TValue)) ?? typeof(TValue);
|
||||
private readonly Expression<Func<T, TValue>> _selector;
|
||||
private readonly Func<T, TValue> _compiled;
|
||||
|
||||
public ListField(string id, Expression<Func<T, TValue>> selector, bool searchable, bool total)
|
||||
: base(id, typeof(TValue), searchable, total)
|
||||
{
|
||||
_selector = selector;
|
||||
_compiled = selector.Compile();
|
||||
}
|
||||
|
||||
/// <summary>Converts a value to decimal for the totals, or <see langword="null"/> when the type is not a number.</summary>
|
||||
public static Func<TValue, decimal?>? Numeric { get; } = Underlying switch
|
||||
{
|
||||
var t when t == typeof(decimal) => v => v is null ? null : (decimal)(object)v,
|
||||
var t when t == typeof(int) => v => v is null ? null : (int)(object)v,
|
||||
var t when t == typeof(long) => v => v is null ? null : (long)(object)v,
|
||||
var t when t == typeof(double) => v => v is null ? null : (decimal)(double)(object)v,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
private static bool IsText => typeof(TValue) == typeof(string);
|
||||
|
||||
private static bool IsOrdered => !IsText && Underlying != typeof(bool) && !Underlying.IsEnum && typeof(IComparable).IsAssignableFrom(Underlying);
|
||||
|
||||
public override object? ValueOf(T row) => _compiled(row);
|
||||
|
||||
internal override Expression Search(ParameterExpression row, string text, bool inMemory) =>
|
||||
TextCall(Member(row), inMemory ? ContainsIgnoreCase : ContainsText, text, inMemory);
|
||||
|
||||
internal override Expression Condition(ParameterExpression row, ListFilter filter, bool inMemory)
|
||||
{
|
||||
var member = Member(row);
|
||||
var values = filter.Values ?? [];
|
||||
switch (filter.Operator)
|
||||
{
|
||||
case ListFilterOperator.IsEmpty or ListFilterOperator.IsNotEmpty:
|
||||
Expression empty = IsText
|
||||
? Expression.Call(typeof(string).GetMethod(nameof(string.IsNullOrEmpty))!, member)
|
||||
: typeof(TValue).IsValueType && Nullable.GetUnderlyingType(typeof(TValue)) is null
|
||||
? Expression.Constant(false)
|
||||
: Expression.Equal(member, Expression.Constant(null, typeof(TValue)));
|
||||
return filter.Operator == ListFilterOperator.IsEmpty ? empty : Expression.Not(empty);
|
||||
|
||||
case ListFilterOperator.Contains or ListFilterOperator.StartsWith:
|
||||
Require(IsText, filter);
|
||||
var method = filter.Operator == ListFilterOperator.Contains
|
||||
? (inMemory ? ContainsIgnoreCase : ContainsText)
|
||||
: (inMemory ? StartsIgnoreCase : StartsText);
|
||||
return TextCall(member, method, Single(values, filter), inMemory);
|
||||
|
||||
case ListFilterOperator.In:
|
||||
Require(values.Count > 0, filter);
|
||||
var array = values.Select(v => Convert(v, filter)).ToArray();
|
||||
return Expression.Call(EnumerableContains, Expression.Constant(array, typeof(TValue[])), member);
|
||||
|
||||
case ListFilterOperator.Between:
|
||||
Require(IsOrdered && values.Count == 2, filter);
|
||||
return Expression.AndAlso(
|
||||
Expression.GreaterThanOrEqual(member, Value(values[0], filter)),
|
||||
Expression.LessThanOrEqual(member, Value(values[1], filter)));
|
||||
|
||||
case ListFilterOperator.Equals:
|
||||
return Equal(member, Single(values, filter), filter, inMemory);
|
||||
|
||||
case ListFilterOperator.NotEquals:
|
||||
return Expression.Not(Equal(member, Single(values, filter), filter, inMemory));
|
||||
|
||||
case ListFilterOperator.GreaterThan or ListFilterOperator.GreaterOrEqual or ListFilterOperator.LessThan or ListFilterOperator.LessOrEqual:
|
||||
Require(IsOrdered, filter);
|
||||
var value = Value(Single(values, filter), filter);
|
||||
return filter.Operator switch
|
||||
{
|
||||
ListFilterOperator.GreaterThan => Expression.GreaterThan(member, value),
|
||||
ListFilterOperator.GreaterOrEqual => Expression.GreaterThanOrEqual(member, value),
|
||||
ListFilterOperator.LessThan => Expression.LessThan(member, value),
|
||||
_ => Expression.LessThanOrEqual(member, value),
|
||||
};
|
||||
|
||||
default:
|
||||
throw new ArgumentException($"Unknown operator {filter.Operator} on {Id}.", nameof(filter));
|
||||
}
|
||||
}
|
||||
|
||||
internal override Query<T> OrderQuery(Query<T> query, bool descending) =>
|
||||
descending ? query.OrderByDescending(_selector) : query.OrderBy(_selector);
|
||||
|
||||
internal override IOrderedEnumerable<T> OrderMemory(IEnumerable<T> source, IOrderedEnumerable<T>? ordered, bool descending)
|
||||
{
|
||||
var comparer = IsText ? (IComparer<TValue>)(object)StringComparer.CurrentCultureIgnoreCase : Comparer<TValue>.Default;
|
||||
return (ordered, descending) switch
|
||||
{
|
||||
(null, false) => source.OrderBy(_compiled, comparer),
|
||||
(null, true) => source.OrderByDescending(_compiled, comparer),
|
||||
(_, false) => ordered.ThenBy(_compiled, comparer),
|
||||
_ => ordered.ThenByDescending(_compiled, comparer),
|
||||
};
|
||||
}
|
||||
|
||||
internal override decimal Sum(IEnumerable<T> rows)
|
||||
{
|
||||
var numeric = Numeric ?? throw new InvalidOperationException($"{Id} is not a number.");
|
||||
return rows.Sum(r => numeric(_compiled(r)) ?? 0m);
|
||||
}
|
||||
|
||||
private static object? ConvertText(string text)
|
||||
{
|
||||
if (IsText)
|
||||
{
|
||||
return text;
|
||||
}
|
||||
|
||||
var c = CultureInfo.InvariantCulture;
|
||||
return Underlying switch
|
||||
{
|
||||
var t when t == typeof(bool) => bool.Parse(text),
|
||||
var t when t == typeof(int) => int.Parse(text, NumberStyles.Integer, c),
|
||||
var t when t == typeof(long) => long.Parse(text, NumberStyles.Integer, c),
|
||||
var t when t == typeof(decimal) => decimal.Parse(text, NumberStyles.Number, c),
|
||||
var t when t == typeof(double) => double.Parse(text, NumberStyles.Float, c),
|
||||
var t when t == typeof(DateOnly) => DateOnly.ParseExact(text, "yyyy-MM-dd", c),
|
||||
var t when t == typeof(DateTime) => DateTime.Parse(text, c, DateTimeStyles.RoundtripKind),
|
||||
var t when t == typeof(DateTimeOffset) => DateTimeOffset.Parse(text, c, DateTimeStyles.RoundtripKind),
|
||||
var t when t == typeof(Guid) => Guid.Parse(text),
|
||||
var t when t.IsEnum => Enum.Parse(t, text, ignoreCase: false),
|
||||
_ => throw new FormatException("Unsupported type " + Underlying.Name),
|
||||
};
|
||||
}
|
||||
|
||||
private Expression Member(ParameterExpression row) => new Rebind(_selector.Parameters[0], row).Visit(_selector.Body);
|
||||
|
||||
private Expression Equal(Expression member, string text, ListFilter filter, bool inMemory)
|
||||
{
|
||||
if (IsText && inMemory)
|
||||
{
|
||||
// Texts are equal ignoring case, as LIKE without wildcards would be.
|
||||
var equals = typeof(string).GetMethod(nameof(string.Equals), [typeof(string), typeof(string), typeof(StringComparison)])!;
|
||||
return Expression.Call(equals, member, Expression.Constant(text), Expression.Constant(StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
return Expression.Equal(member, Value(text, filter));
|
||||
}
|
||||
|
||||
private static Expression TextCall(Expression member, MethodInfo method, string text, bool inMemory)
|
||||
{
|
||||
if (!inMemory)
|
||||
{
|
||||
return Expression.Call(member, method, Expression.Constant(text));
|
||||
}
|
||||
|
||||
// Null texts never match in memory, as in SQL.
|
||||
return Expression.AndAlso(
|
||||
Expression.NotEqual(member, Expression.Constant(null, typeof(string))),
|
||||
Expression.Call(member, method, Expression.Constant(text), Expression.Constant(StringComparison.OrdinalIgnoreCase)));
|
||||
}
|
||||
|
||||
private ConstantExpression Value(string text, ListFilter filter) => Expression.Constant(Convert(text, filter), typeof(TValue));
|
||||
|
||||
private TValue Convert(string text, ListFilter filter)
|
||||
{
|
||||
try
|
||||
{
|
||||
return (TValue)ConvertText(text)!;
|
||||
}
|
||||
catch (Exception e) when (e is FormatException or OverflowException or ArgumentException or InvalidCastException)
|
||||
{
|
||||
throw new ArgumentException($"Value '{text}' is not valid for {Id}.", nameof(filter), e);
|
||||
}
|
||||
}
|
||||
|
||||
private string Single(IReadOnlyList<string> values, ListFilter filter)
|
||||
{
|
||||
Require(values.Count == 1, filter);
|
||||
return values[0];
|
||||
}
|
||||
|
||||
private void Require(bool condition, ListFilter filter)
|
||||
{
|
||||
if (!condition)
|
||||
{
|
||||
throw new ArgumentException($"{filter.Operator} with {filter.Values?.Count ?? 0} values is not valid on {Id}.", nameof(filter));
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Rebind(ParameterExpression from, ParameterExpression to) : ExpressionVisitor
|
||||
{
|
||||
protected override Expression VisitParameter(ParameterExpression node) => node == from ? to : base.VisitParameter(node);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace Khaemhat.Application.Querying;
|
||||
|
||||
/// <summary>How a filter compares a field with its values (SPEC §10.7 <c>KhGrid</c>, <c>KhRadar</c>).</summary>
|
||||
public enum ListFilterOperator
|
||||
{
|
||||
/// <summary>Equal to the value.</summary>
|
||||
Equals = 0,
|
||||
|
||||
/// <summary>Different from the value.</summary>
|
||||
NotEquals = 1,
|
||||
|
||||
/// <summary>Text containing the value, ignoring case.</summary>
|
||||
Contains = 2,
|
||||
|
||||
/// <summary>Text starting with the value, ignoring case.</summary>
|
||||
StartsWith = 3,
|
||||
|
||||
/// <summary>Greater than the value.</summary>
|
||||
GreaterThan = 4,
|
||||
|
||||
/// <summary>Greater than or equal to the value.</summary>
|
||||
GreaterOrEqual = 5,
|
||||
|
||||
/// <summary>Less than the value.</summary>
|
||||
LessThan = 6,
|
||||
|
||||
/// <summary>Less than or equal to the value.</summary>
|
||||
LessOrEqual = 7,
|
||||
|
||||
/// <summary>Between the first and the second value, both included.</summary>
|
||||
Between = 8,
|
||||
|
||||
/// <summary>One of the values.</summary>
|
||||
In = 9,
|
||||
|
||||
/// <summary>Empty (null, or an empty text).</summary>
|
||||
IsEmpty = 10,
|
||||
|
||||
/// <summary>Not empty.</summary>
|
||||
IsNotEmpty = 11,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A filter on a field. The values are invariant texts (<c>2026-11-30</c>, <c>1234.5</c>, <c>true</c>, the name of an
|
||||
/// enum value), so a filter can be saved in the user settings and read back unchanged.
|
||||
/// </summary>
|
||||
/// <param name="Field">The field id.</param>
|
||||
/// <param name="Operator">The comparison.</param>
|
||||
/// <param name="Values">The values: none for the empty checks, two for <see cref="ListFilterOperator.Between"/>.</param>
|
||||
public sealed record ListFilter(string Field, ListFilterOperator Operator, IReadOnlyList<string> Values)
|
||||
{
|
||||
/// <summary>A filter with its values.</summary>
|
||||
/// <param name="field">The field id.</param>
|
||||
/// <param name="op">The comparison.</param>
|
||||
/// <param name="values">The values.</param>
|
||||
/// <returns>The filter.</returns>
|
||||
public static ListFilter Of(string field, ListFilterOperator op, params string[] values) => new(field, op, values);
|
||||
|
||||
/// <summary>The invariant text of a value, as filters keep it.</summary>
|
||||
/// <param name="value">The value.</param>
|
||||
/// <returns>The text.</returns>
|
||||
public static string Text(object? value) => value switch
|
||||
{
|
||||
null => string.Empty,
|
||||
DateOnly d => d.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
|
||||
DateTime d => d.ToString("O", CultureInfo.InvariantCulture),
|
||||
DateTimeOffset d => d.ToString("O", CultureInfo.InvariantCulture),
|
||||
bool b => b ? "true" : "false",
|
||||
IFormattable f => f.ToString(null, CultureInfo.InvariantCulture),
|
||||
_ => value.ToString() ?? string.Empty,
|
||||
};
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool Equals(ListFilter? other) =>
|
||||
other is not null && Field == other.Field && Operator == other.Operator && Values.SequenceEqual(other.Values);
|
||||
|
||||
/// <inheritdoc />
|
||||
public override int GetHashCode()
|
||||
{
|
||||
var hash = new HashCode();
|
||||
hash.Add(Field);
|
||||
hash.Add(Operator);
|
||||
foreach (var value in Values)
|
||||
{
|
||||
hash.Add(value);
|
||||
}
|
||||
|
||||
return hash.ToHashCode();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>An ordering on a field.</summary>
|
||||
/// <param name="Field">The field id.</param>
|
||||
/// <param name="Descending">Whether from the largest.</param>
|
||||
public sealed record ListSort(string Field, bool Descending = false);
|
||||
|
||||
/// <summary>
|
||||
/// What a list or radar asks its source: the text typed in the search box, the filters, the ordering and the page.
|
||||
/// The source answers with a <see cref="ListPage{T}"/>; with <see cref="ListFields{T}"/> the same request becomes SQL for
|
||||
/// a repository or runs on rows in memory.
|
||||
/// </summary>
|
||||
public sealed record ListQuery
|
||||
{
|
||||
/// <summary>The largest page a source returns.</summary>
|
||||
public const int MaxLimit = 1000;
|
||||
|
||||
/// <summary>The text of the search box: every searchable field is checked.</summary>
|
||||
public string? Search { get; init; }
|
||||
|
||||
/// <summary>The filters, all of which must hold.</summary>
|
||||
public IReadOnlyList<ListFilter> Filters { get; init; } = [];
|
||||
|
||||
/// <summary>The ordering, first field first.</summary>
|
||||
public IReadOnlyList<ListSort> Sort { get; init; } = [];
|
||||
|
||||
/// <summary>The rows to skip.</summary>
|
||||
public int Offset { get; init; }
|
||||
|
||||
/// <summary>The rows to return, at most <see cref="MaxLimit"/>.</summary>
|
||||
public int Limit { get; init; } = 50;
|
||||
|
||||
/// <summary>The same request for another page.</summary>
|
||||
/// <param name="offset">The rows to skip.</param>
|
||||
/// <param name="limit">The rows to return.</param>
|
||||
/// <returns>The request.</returns>
|
||||
public ListQuery WithPage(int offset, int limit) => this with { Offset = Math.Max(0, offset), Limit = Math.Clamp(limit, 1, MaxLimit) };
|
||||
|
||||
/// <summary>Whether two requests select and order the same rows, whatever the page.</summary>
|
||||
/// <param name="other">The other request.</param>
|
||||
/// <returns>Whether they match.</returns>
|
||||
public bool SameRows(ListQuery? other) =>
|
||||
other is not null && string.Equals(Search?.Trim(), other.Search?.Trim(), StringComparison.OrdinalIgnoreCase)
|
||||
&& Filters.SequenceEqual(other.Filters) && Sort.SequenceEqual(other.Sort);
|
||||
}
|
||||
|
||||
/// <summary>A page of rows with the count and the totals of every row the request selects (not only the page).</summary>
|
||||
/// <typeparam name="T">The row type.</typeparam>
|
||||
/// <param name="Items">The rows of the page.</param>
|
||||
/// <param name="Total">The rows selected.</param>
|
||||
/// <param name="Totals">The sums by field id, for the totals row of the grid.</param>
|
||||
public sealed record ListPage<T>(IReadOnlyList<T> Items, long Total, IReadOnlyDictionary<string, decimal> Totals)
|
||||
{
|
||||
/// <summary>No rows.</summary>
|
||||
#pragma warning disable CA1000 // An empty page of the same row type is the natural default.
|
||||
public static ListPage<T> Empty { get; } = new([], 0, new Dictionary<string, decimal>());
|
||||
#pragma warning restore CA1000
|
||||
}
|
||||
|
||||
/// <summary>Where a grid or radar reads its rows.</summary>
|
||||
/// <typeparam name="T">The row type.</typeparam>
|
||||
/// <param name="query">The request.</param>
|
||||
/// <param name="cancellationToken">Cancellation, when a newer request replaces this one.</param>
|
||||
/// <returns>The page.</returns>
|
||||
public delegate Task<ListPage<T>> ListSource<T>(ListQuery query, CancellationToken cancellationToken);
|
||||
@@ -0,0 +1,133 @@
|
||||
using Khaemhat.Application.Security;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Khaemhat.Application.Search;
|
||||
|
||||
/// <summary>What the search looks for, from the first character of the query (SPEC §10.2, mockup 009).</summary>
|
||||
public enum SearchScope
|
||||
{
|
||||
/// <summary>Everything: pages, records, help.</summary>
|
||||
All,
|
||||
|
||||
/// <summary><c>></c>: only the commands.</summary>
|
||||
Commands,
|
||||
|
||||
/// <summary><c>#</c>: only the documents.</summary>
|
||||
Documents,
|
||||
|
||||
/// <summary><c>@</c>: only the people.</summary>
|
||||
People,
|
||||
}
|
||||
|
||||
/// <summary>A search, split into scope and words.</summary>
|
||||
/// <param name="Scope">What it looks for.</param>
|
||||
/// <param name="Text">The words, without the prefix.</param>
|
||||
public sealed record SearchQuery(SearchScope Scope, string Text)
|
||||
{
|
||||
/// <summary>The fewest characters before records are searched.</summary>
|
||||
public const int MinimumLength = 2;
|
||||
|
||||
/// <summary>The words of the query.</summary>
|
||||
public IReadOnlyList<string> Words { get; } = Text.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
|
||||
/// <summary>Reads what the user typed.</summary>
|
||||
/// <param name="input">The text of the search box.</param>
|
||||
/// <returns>The query.</returns>
|
||||
public static SearchQuery Parse(string? input)
|
||||
{
|
||||
var text = (input ?? string.Empty).Trim();
|
||||
var scope = text.Length == 0 ? SearchScope.All : text[0] switch
|
||||
{
|
||||
'>' => SearchScope.Commands,
|
||||
'#' => SearchScope.Documents,
|
||||
'@' => SearchScope.People,
|
||||
_ => SearchScope.All,
|
||||
};
|
||||
return new SearchQuery(scope, scope == SearchScope.All ? text : text[1..].Trim());
|
||||
}
|
||||
|
||||
/// <summary>Whether a text contains every word, ignoring case.</summary>
|
||||
/// <param name="value">The text.</param>
|
||||
/// <returns><see langword="true"/> if it does; always for an empty query.</returns>
|
||||
public bool Matches(string? value) =>
|
||||
Words.Count == 0 || (value is not null && Words.All(w => value.Contains(w, StringComparison.CurrentCultureIgnoreCase)));
|
||||
}
|
||||
|
||||
/// <summary>A search result.</summary>
|
||||
/// <param name="Group">The text key of the group shown above it, such as <c>Shell.Search.Help</c>.</param>
|
||||
/// <param name="Icon">The icon.</param>
|
||||
/// <param name="Title">The title.</param>
|
||||
/// <param name="Detail">A second line, such as the page a heading belongs to.</param>
|
||||
/// <param name="Href">Where it opens, relative to the application.</param>
|
||||
public sealed record SearchHit(string Group, string Icon, string Title, string? Detail, string Href);
|
||||
|
||||
/// <summary>A source of search results: each module adds its own (parties, items, documents, accounts...).</summary>
|
||||
public interface ISearchProvider
|
||||
{
|
||||
/// <summary>The scopes it answers: <see cref="SearchScope.All"/> and, for example, <see cref="SearchScope.Documents"/>.</summary>
|
||||
IReadOnlyCollection<SearchScope> Scopes { get; }
|
||||
|
||||
/// <summary>Searches.</summary>
|
||||
/// <param name="actor">Who searches: results respect permissions and company.</param>
|
||||
/// <param name="query">The query, at least <see cref="SearchQuery.MinimumLength"/> characters.</param>
|
||||
/// <param name="cancellationToken">Cancellation: the user typed something else.</param>
|
||||
/// <returns>At most <see cref="GlobalSearchService.PerProvider"/> results, best first.</returns>
|
||||
Task<IReadOnlyList<SearchHit>> SearchAsync(Actor actor, SearchQuery query, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The records part of the global search (SPEC §10.2): asks every provider of the scope, in parallel, and puts the
|
||||
/// results together. A provider that fails or is slow is left out, the others are shown.
|
||||
/// </summary>
|
||||
public sealed class GlobalSearchService(IEnumerable<ISearchProvider> providers, ILogger<GlobalSearchService> logger)
|
||||
{
|
||||
/// <summary>The most results of one provider.</summary>
|
||||
public const int PerProvider = 8;
|
||||
|
||||
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(3);
|
||||
|
||||
private readonly ISearchProvider[] _providers = [.. providers];
|
||||
|
||||
/// <summary>Whether something answers a scope: without, the search says what it will find in a later version.</summary>
|
||||
/// <param name="scope">The scope.</param>
|
||||
/// <returns><see langword="true"/> if a provider does.</returns>
|
||||
public bool Covers(SearchScope scope) => _providers.Any(p => p.Scopes.Contains(scope));
|
||||
|
||||
/// <summary>Searches the records.</summary>
|
||||
/// <param name="actor">Who searches.</param>
|
||||
/// <param name="query">The query.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The results, grouped by provider in registration order.</returns>
|
||||
public async Task<IReadOnlyList<SearchHit>> SearchAsync(Actor actor, SearchQuery query, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
ArgumentNullException.ThrowIfNull(query);
|
||||
if (query.Scope == SearchScope.Commands || query.Text.Length < SearchQuery.MinimumLength)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var results = await Task.WhenAll(_providers.Where(p => p.Scopes.Contains(query.Scope)).Select(p => AskAsync(p, actor, query, cancellationToken))).ConfigureAwait(false);
|
||||
return [.. results.SelectMany(r => r)];
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<SearchHit>> AskAsync(ISearchProvider provider, Actor actor, SearchQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeout.CancelAfter(Timeout);
|
||||
try
|
||||
{
|
||||
return [.. (await provider.SearchAsync(actor, query, timeout.Token).ConfigureAwait(false)).Take(PerProvider)];
|
||||
}
|
||||
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
logger.LogWarning("Search provider {Provider} took longer than {Timeout} and was left out", provider.GetType().Name, Timeout);
|
||||
return [];
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
logger.LogError(ex, "Search provider {Provider} failed", provider.GetType().Name);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -237,11 +237,40 @@ public sealed class AccountSecurity
|
||||
}
|
||||
|
||||
account.TotpEnabled = true;
|
||||
return NewRecoveryCodes(account);
|
||||
}
|
||||
|
||||
/// <summary>Replaces the recovery codes with ten new ones; the old ones stop working.</summary>
|
||||
/// <param name="account">The account.</param>
|
||||
/// <returns>The new codes, to show once.</returns>
|
||||
public static IReadOnlyList<string> NewRecoveryCodes(IAccount account)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(account);
|
||||
var codes = Enumerable.Range(0, 10).Select(_ => SecureTokenGenerator.CreateReadableCode(2)).ToList();
|
||||
account.TotpRecoveryCodes = JsonSerializer.Serialize(codes.Select(c => SecureTokenGenerator.Hash(c)).ToList());
|
||||
return codes;
|
||||
}
|
||||
|
||||
/// <summary>How many recovery codes are still unused.</summary>
|
||||
/// <param name="account">The account.</param>
|
||||
/// <returns>The number of codes left.</returns>
|
||||
public static int RecoveryCodesLeft(IAccount account)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(account);
|
||||
return account.TotpEnabled ? Deserialize(account.TotpRecoveryCodes).Count : 0;
|
||||
}
|
||||
|
||||
/// <summary>Checks the current password without counting failures (profile changes that ask for it again).</summary>
|
||||
/// <param name="account">The account.</param>
|
||||
/// <param name="password">The password typed.</param>
|
||||
/// <returns>Whether it is right.</returns>
|
||||
public static bool IsCurrentPassword(IAccount account, string password)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(account);
|
||||
ArgumentNullException.ThrowIfNull(password);
|
||||
return account.PasswordHash is not null && PasswordHasher.Verify(account.PasswordHash, password) != PasswordVerification.Failed;
|
||||
}
|
||||
|
||||
/// <summary>Checks a TOTP code at sign-in. A code is never accepted twice.</summary>
|
||||
/// <param name="account">The account.</param>
|
||||
/// <param name="code">The code.</param>
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
using System.Net.Mail;
|
||||
using Khaemhat.Application.Audit;
|
||||
using Khaemhat.Core.Security;
|
||||
using Khaemhat.Infrastructure.Security;
|
||||
|
||||
namespace Khaemhat.Application.Security;
|
||||
|
||||
/// <summary>What the profile page shows about the signed-in account (SPEC §12, mockup 008).</summary>
|
||||
/// <param name="UserName">The sign-in name.</param>
|
||||
/// <param name="DisplayName">The name shown in the interface.</param>
|
||||
/// <param name="Email">The e-mail address.</param>
|
||||
/// <param name="IsInstanceAccount">Whether it is an instance account (super user or administrator).</param>
|
||||
/// <param name="TotpEnabled">Whether the two-step verification is active.</param>
|
||||
/// <param name="TotpRequired">Whether the two-step verification is mandatory, so it cannot be turned off.</param>
|
||||
/// <param name="RecoveryCodesLeft">Unused recovery codes.</param>
|
||||
/// <param name="HasPassword">Whether the account signs in with a password (technical users do not).</param>
|
||||
/// <param name="PasswordChangedAt">When the password was last set (UTC).</param>
|
||||
/// <param name="LastLoginAt">The last successful sign-in (UTC).</param>
|
||||
public sealed record ProfileInfo(
|
||||
string UserName,
|
||||
string DisplayName,
|
||||
string? Email,
|
||||
bool IsInstanceAccount,
|
||||
bool TotpEnabled,
|
||||
bool TotpRequired,
|
||||
int RecoveryCodesLeft,
|
||||
bool HasPassword,
|
||||
DateTime? PasswordChangedAt,
|
||||
DateTime? LastLoginAt);
|
||||
|
||||
/// <summary>
|
||||
/// The changes users make to their own account from the profile (SPEC §12, issue #31): name and e-mail, password,
|
||||
/// two-step verification and recovery codes. Unlike <see cref="SignInService"/> it works from the session owner, not
|
||||
/// from the cookie, because the profile runs in the interactive circuit where the cookie cannot be read. Every change is
|
||||
/// recorded in <c>sys_security_audit</c>; a password change closes the other sessions of the account.
|
||||
/// </summary>
|
||||
/// <param name="systemUsers">Instance accounts.</param>
|
||||
/// <param name="companyUsers">Company users.</param>
|
||||
/// <param name="security">Credential rules.</param>
|
||||
/// <param name="sessions">Sessions.</param>
|
||||
/// <param name="audit">The security audit.</param>
|
||||
public sealed class ProfileService(
|
||||
SystemUserService systemUsers,
|
||||
UserService companyUsers,
|
||||
AccountSecurity security,
|
||||
SessionStore sessions,
|
||||
ISecurityAuditLog audit)
|
||||
{
|
||||
/// <summary>The longest display name accepted.</summary>
|
||||
public const int DisplayNameMaxLength = 100;
|
||||
|
||||
/// <summary>The display name is empty or too long.</summary>
|
||||
public const string DisplayNameInvalid = "display_name_invalid";
|
||||
|
||||
/// <summary>The e-mail address is not valid.</summary>
|
||||
public const string EmailInvalid = "email_invalid";
|
||||
|
||||
/// <summary>The two-step verification is mandatory for the account and cannot be turned off.</summary>
|
||||
public const string TotpRequiredError = "totp_required";
|
||||
|
||||
/// <summary>Reads the account of a session owner.</summary>
|
||||
/// <param name="owner">The session owner.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The profile, or <see langword="null"/> when the account no longer exists or is disabled.</returns>
|
||||
public async Task<ProfileInfo?> GetAsync(SessionOwner owner, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var account = await LoadAsync(owner, cancellationToken).ConfigureAwait(false);
|
||||
return account is null ? null : InfoOf(account, owner);
|
||||
}
|
||||
|
||||
/// <summary>Changes name and e-mail.</summary>
|
||||
/// <param name="owner">The session owner.</param>
|
||||
/// <param name="displayName">The new name.</param>
|
||||
/// <param name="email">The new e-mail, or empty to remove it.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The error codes; empty when saved.</returns>
|
||||
public async Task<IReadOnlyList<string>> UpdateAsync(SessionOwner owner, string? displayName, string? email, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var name = displayName?.Trim() ?? string.Empty;
|
||||
var mail = string.IsNullOrWhiteSpace(email) ? null : email.Trim();
|
||||
var errors = new List<string>();
|
||||
if (name.Length is 0 or > DisplayNameMaxLength)
|
||||
{
|
||||
errors.Add(DisplayNameInvalid);
|
||||
}
|
||||
|
||||
if (mail is not null && !IsEmail(mail))
|
||||
{
|
||||
errors.Add(EmailInvalid);
|
||||
}
|
||||
|
||||
if (errors.Count > 0)
|
||||
{
|
||||
return errors;
|
||||
}
|
||||
|
||||
var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false);
|
||||
account.DisplayName = name;
|
||||
account.Email = mail;
|
||||
await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false);
|
||||
await AuditAsync("user.profile-updated", account, owner, cancellationToken).ConfigureAwait(false);
|
||||
return [];
|
||||
}
|
||||
|
||||
/// <summary>Changes the password, checking the current one, and closes every other session of the account.</summary>
|
||||
/// <param name="owner">The session owner.</param>
|
||||
/// <param name="currentSessionId">The session that stays open.</param>
|
||||
/// <param name="currentPassword">The current password.</param>
|
||||
/// <param name="newPassword">The new password.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The error codes (<see cref="SecurityErrors"/>); empty when changed.</returns>
|
||||
public async Task<IReadOnlyList<string>> ChangePasswordAsync(
|
||||
SessionOwner owner, long? currentSessionId, string currentPassword, string newPassword, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(currentPassword);
|
||||
ArgumentNullException.ThrowIfNull(newPassword);
|
||||
var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false);
|
||||
if (!AccountSecurity.IsCurrentPassword(account, currentPassword))
|
||||
{
|
||||
await AuditAsync("user.password-change-refused", account, owner, cancellationToken).ConfigureAwait(false);
|
||||
return [SecurityErrors.CurrentPasswordWrong];
|
||||
}
|
||||
|
||||
var errors = security.ChangePassword(account, newPassword);
|
||||
if (errors.Count > 0)
|
||||
{
|
||||
return errors;
|
||||
}
|
||||
|
||||
await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false);
|
||||
await sessions.RevokeAllAsync(owner, "password_changed", currentSessionId, cancellationToken).ConfigureAwait(false);
|
||||
await AuditAsync("user.password-changed", account, owner, cancellationToken).ConfigureAwait(false);
|
||||
return [];
|
||||
}
|
||||
|
||||
/// <summary>Starts turning on the two-step verification; reloading the page shows the same secret.</summary>
|
||||
/// <param name="owner">The session owner.</param>
|
||||
/// <param name="companyCode">The company of the session, shown in the label of the authenticator app.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The secret to show, or <see langword="null"/> when the verification is already active.</returns>
|
||||
public async Task<TotpSetup?> BeginTotpSetupAsync(SessionOwner owner, string? companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false);
|
||||
if (account.TotpEnabled)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var secret = security.PendingTotpSecret(account);
|
||||
if (secret is null)
|
||||
{
|
||||
secret = security.BeginTotpSetup(account);
|
||||
await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var label = companyCode is null ? account.UserName : account.UserName + "@" + companyCode;
|
||||
return new TotpSetup(secret, TotpGenerator.ProvisioningUri(secret, label));
|
||||
}
|
||||
|
||||
/// <summary>Completes turning on the two-step verification with the first code from the app.</summary>
|
||||
/// <param name="owner">The session owner.</param>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The ten recovery codes to show once, or <see langword="null"/> when the code is wrong.</returns>
|
||||
public async Task<IReadOnlyList<string>?> ConfirmTotpSetupAsync(SessionOwner owner, string code, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(code);
|
||||
var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false);
|
||||
if (account.TotpEnabled)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var codes = security.ConfirmTotpSetup(account, code.Trim());
|
||||
if (codes is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false);
|
||||
await AuditAsync("user.totp-enabled", account, owner, cancellationToken).ConfigureAwait(false);
|
||||
return codes;
|
||||
}
|
||||
|
||||
/// <summary>Replaces the recovery codes, asking the password again.</summary>
|
||||
/// <param name="owner">The session owner.</param>
|
||||
/// <param name="password">The current password.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The new codes, or <see langword="null"/> when the password is wrong or the verification is off.</returns>
|
||||
public async Task<IReadOnlyList<string>?> RenewRecoveryCodesAsync(SessionOwner owner, string password, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(password);
|
||||
var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false);
|
||||
if (!account.TotpEnabled || !AccountSecurity.IsCurrentPassword(account, password))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var codes = AccountSecurity.NewRecoveryCodes(account);
|
||||
await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false);
|
||||
await AuditAsync("user.recovery-codes-renewed", account, owner, cancellationToken).ConfigureAwait(false);
|
||||
return codes;
|
||||
}
|
||||
|
||||
/// <summary>Turns the two-step verification off, asking the password again; refused when it is mandatory.</summary>
|
||||
/// <param name="owner">The session owner.</param>
|
||||
/// <param name="password">The current password.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The error codes; empty when turned off.</returns>
|
||||
public async Task<IReadOnlyList<string>> DisableTotpAsync(SessionOwner owner, string password, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(password);
|
||||
var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false);
|
||||
if (IsTotpRequired(account, owner))
|
||||
{
|
||||
return [TotpRequiredError];
|
||||
}
|
||||
|
||||
if (!AccountSecurity.IsCurrentPassword(account, password))
|
||||
{
|
||||
return [SecurityErrors.CurrentPasswordWrong];
|
||||
}
|
||||
|
||||
AccountSecurity.ResetTotp(account);
|
||||
await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false);
|
||||
await AuditAsync("user.totp-disabled", account, owner, cancellationToken).ConfigureAwait(false);
|
||||
return [];
|
||||
}
|
||||
|
||||
private static bool IsEmail(string value) =>
|
||||
value.Length <= 254 && MailAddress.TryCreate(value, out var address) && address.Address == value && value.Contains('.', StringComparison.Ordinal);
|
||||
|
||||
private bool IsTotpRequired(IAccount account, SessionOwner owner) =>
|
||||
owner.IsInstanceAccount || account is CompanyUser { TotpRequired: true } || security.Options.TotpRequiredForUsers;
|
||||
|
||||
private ProfileInfo InfoOf(IAccount account, SessionOwner owner) => new(
|
||||
account.UserName,
|
||||
account.DisplayName,
|
||||
account.Email,
|
||||
owner.IsInstanceAccount,
|
||||
account.TotpEnabled,
|
||||
IsTotpRequired(account, owner),
|
||||
AccountSecurity.RecoveryCodesLeft(account),
|
||||
account.PasswordHash is not null,
|
||||
account.PasswordChangedAt,
|
||||
account.LastLoginAt);
|
||||
|
||||
private async Task<IAccount?> LoadAsync(SessionOwner owner, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(owner);
|
||||
IAccount? account = owner.IsInstanceAccount
|
||||
? await systemUsers.GetAsync(owner.UserId, cancellationToken).ConfigureAwait(false)
|
||||
: await companyUsers.GetAsync(owner.CompanyDatabase!, owner.UserId, cancellationToken).ConfigureAwait(false);
|
||||
return account is { IsActive: true } ? account : null;
|
||||
}
|
||||
|
||||
private async Task<IAccount> RequireAsync(SessionOwner owner, CancellationToken cancellationToken) =>
|
||||
await LoadAsync(owner, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new AccessDeniedException(SecurityErrors.InvalidCredentials, "The account no longer exists or is disabled.");
|
||||
|
||||
private Task SaveAsync(IAccount account, SessionOwner owner, CancellationToken cancellationToken) => account switch
|
||||
{
|
||||
SystemUser system => systemUsers.SaveAsync(system, cancellationToken),
|
||||
CompanyUser user => companyUsers.SaveAsync(owner.CompanyDatabase!, user, cancellationToken),
|
||||
_ => throw new InvalidOperationException("Unknown account type."),
|
||||
};
|
||||
|
||||
private Task AuditAsync(string action, IAccount account, SessionOwner owner, CancellationToken cancellationToken) =>
|
||||
audit.WriteAsync(new SecurityEvent(action, account.UserName, owner.CompanyDatabase), cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
using Khaemhat.Core.Entities;
|
||||
|
||||
namespace Khaemhat.Core.Files;
|
||||
|
||||
/// <summary>Where an attachment comes from (SPEC §9.4).</summary>
|
||||
public enum AttachmentKind
|
||||
{
|
||||
/// <summary>A file uploaded by a user (the customer's order, a photo, a spreadsheet).</summary>
|
||||
Uploaded = 0,
|
||||
|
||||
/// <summary>A file produced by Khaemhat (print PDF, exported rows, courtesy ZIP).</summary>
|
||||
Generated = 1,
|
||||
|
||||
/// <summary>An electronic invoice (FatturaPA XML, P7M) issued or received.</summary>
|
||||
EInvoice = 2,
|
||||
|
||||
/// <summary>A notification of the exchange system (SDI receipts).</summary>
|
||||
Notification = 3,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A file that belongs to exactly one record of the company (<c>attachments</c>, SPEC §9.4): a document, a party, an
|
||||
/// item... There are no loose attachments. The bytes live in the company folder of the file store under
|
||||
/// <see cref="StorageKey"/>; the row keeps name, type, size, SHA-256 and version.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Versions are numbered per <see cref="VersionKey"/> inside the record: a generated file counts per generator code
|
||||
/// (<see cref="GeneratedBy"/>), so "Rigenera" adds <c>v2</c>, <c>v3</c>...; an uploaded file counts per file name, so
|
||||
/// uploading a file with the same name again adds a version instead of replacing the previous one (ADR 0021).
|
||||
/// </remarks>
|
||||
public sealed class Attachment : Entity<long>
|
||||
{
|
||||
/// <summary>The entity of the owning record, for example <c>sales.invoice</c> or <c>parties.party</c>.</summary>
|
||||
public string Entity { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The identifier of the owning record.</summary>
|
||||
public long EntityId { get; set; }
|
||||
|
||||
/// <summary>Where the file comes from.</summary>
|
||||
public AttachmentKind Kind { get; set; }
|
||||
|
||||
/// <summary>The file name shown and used for downloads (without the version suffix).</summary>
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The media type, for example <c>application/pdf</c>.</summary>
|
||||
public string Mime { get; set; } = "application/octet-stream";
|
||||
|
||||
/// <summary>The size in bytes.</summary>
|
||||
public long Size { get; set; }
|
||||
|
||||
/// <summary>The SHA-256 of the content, 64 lowercase hexadecimal characters.</summary>
|
||||
public string Sha256 { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The version inside <see cref="VersionKey"/>, from 1.</summary>
|
||||
public int Version { get; set; } = 1;
|
||||
|
||||
/// <summary>
|
||||
/// The series the version counts in: <c>gen:<generator code></c> for generated files, <c>name:<lowercase
|
||||
/// name></c> otherwise. Unique with the record and <see cref="Version"/>.
|
||||
/// </summary>
|
||||
public string VersionKey { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The template or procedure that produced the file (generated files), for example <c>demo.test-pdf</c>.</summary>
|
||||
public string? GeneratedBy { get; set; }
|
||||
|
||||
/// <summary>Where the bytes are in the company folder of the file store (<c>yyyy/guid</c>).</summary>
|
||||
public string StorageKey { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Who uploaded or generated the file (the actor of the service call). The audit column <c>created_by</c> knows
|
||||
/// the user only inside an HTTP request; this one is always set.
|
||||
/// </summary>
|
||||
public string? UserName { get; set; }
|
||||
|
||||
/// <summary>A locked file (for example the XML sent to the SDI) cannot be deleted or replaced.</summary>
|
||||
public bool Locked { get; set; }
|
||||
|
||||
/// <summary>When the attachment was moved to the company trash; <see langword="null"/> while it is in use.</summary>
|
||||
public DateTime? DeletedAt { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
namespace Khaemhat.Core.Files;
|
||||
|
||||
/// <summary>A file saved in the store.</summary>
|
||||
/// <param name="Key">Where it is in the company folder (<c>yyyy/guid</c>); keep it to open or delete the file.</param>
|
||||
/// <param name="Size">The size in bytes.</param>
|
||||
/// <param name="Sha256">The SHA-256 of the content, lowercase hexadecimal.</param>
|
||||
public sealed record StoredFile(string Key, long Size, string Sha256);
|
||||
|
||||
/// <summary>The space a company uses in the store.</summary>
|
||||
/// <param name="Files">How many files.</param>
|
||||
/// <param name="Bytes">Their total size.</param>
|
||||
/// <param name="QuotaBytes">The quota of the company; 0 means no quota.</param>
|
||||
public sealed record FileUsage(long Files, long Bytes, long QuotaBytes)
|
||||
{
|
||||
/// <summary>The bytes still available; <see cref="long.MaxValue"/> without quota.</summary>
|
||||
public long RemainingBytes => QuotaBytes <= 0 ? long.MaxValue : Math.Max(0, QuotaBytes - Bytes);
|
||||
|
||||
/// <summary>Whether the company uses more than its quota.</summary>
|
||||
public bool IsOverQuota => QuotaBytes > 0 && Bytes > QuotaBytes;
|
||||
}
|
||||
|
||||
/// <summary>The limits applied while a file is written.</summary>
|
||||
/// <param name="MaxBytes">The largest file accepted; 0 means no limit.</param>
|
||||
/// <param name="QuotaBytes">The space a company may use in all; 0 means no quota.</param>
|
||||
public sealed record FileLimits(long MaxBytes, long QuotaBytes)
|
||||
{
|
||||
/// <summary>The default size limit of an uploaded file (SPEC §9.4): 25 MB.</summary>
|
||||
public const long DefaultMaxBytes = 25L * 1024 * 1024;
|
||||
|
||||
/// <summary>No limit at all (generated files are bounded by their generator).</summary>
|
||||
public static FileLimits None { get; } = new(0, 0);
|
||||
}
|
||||
|
||||
/// <summary>Why the store refused a file. <see cref="Code"/> is one of the constants of this class.</summary>
|
||||
public sealed class FileStoreException : Exception
|
||||
{
|
||||
/// <summary>The file is larger than <see cref="FileLimits.MaxBytes"/>.</summary>
|
||||
public const string TooLarge = "file_too_large";
|
||||
|
||||
/// <summary>The file would take the company over its quota.</summary>
|
||||
public const string QuotaExceeded = "file_quota_exceeded";
|
||||
|
||||
/// <summary>The scanner (<see cref="IFileScanner"/>) rejected the file.</summary>
|
||||
public const string Rejected = "file_rejected";
|
||||
|
||||
/// <summary>The file does not exist in the store.</summary>
|
||||
public const string NotFound = "file_not_found";
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
public FileStoreException()
|
||||
: this(NotFound, "File store error.")
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="message">The message.</param>
|
||||
public FileStoreException(string message)
|
||||
: this(NotFound, message)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="message">The message.</param>
|
||||
/// <param name="innerException">The cause.</param>
|
||||
public FileStoreException(string message, Exception innerException)
|
||||
: base(message, innerException) => Code = NotFound;
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="code">The error code.</param>
|
||||
/// <param name="message">The message.</param>
|
||||
public FileStoreException(string code, string message)
|
||||
: base(message) => Code = code;
|
||||
|
||||
/// <summary>The error code.</summary>
|
||||
public string Code { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A file being written to the store: write the content to <see cref="Content"/>, then call
|
||||
/// <see cref="CommitAsync"/>. Disposing without committing discards what was written.
|
||||
/// </summary>
|
||||
public interface IFileStoreWriter : IAsyncDisposable
|
||||
{
|
||||
/// <summary>The write-only, non-seekable stream that receives the content (it counts bytes and computes SHA-256).</summary>
|
||||
/// <exception cref="FileStoreException">Writing goes past <see cref="FileLimits.MaxBytes"/> (code <see cref="FileStoreException.TooLarge"/>).</exception>
|
||||
Stream Content { get; }
|
||||
|
||||
/// <summary>Completes the file: checks quota and scanner, then makes it visible under its key.</summary>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The stored file.</returns>
|
||||
/// <exception cref="FileStoreException">The file is refused.</exception>
|
||||
Task<StoredFile> CommitAsync(CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Where attachment bytes live (SPEC §9.4): one folder per company, one subfolder per year. Writes are streamed and
|
||||
/// atomic (a partial file is never visible under its key); every key belongs to one company and cannot reach outside
|
||||
/// its folder.
|
||||
/// </summary>
|
||||
public interface IFileStore
|
||||
{
|
||||
/// <summary>Saves a file read from a stream.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="content">The content, read to the end.</param>
|
||||
/// <param name="limits">The limits; <see langword="null"/> for the store defaults.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The stored file.</returns>
|
||||
/// <exception cref="FileStoreException">The file is refused (size, quota, scanner).</exception>
|
||||
Task<StoredFile> SaveAsync(string companyCode, Stream content, FileLimits? limits = null, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Starts a file that the caller writes (generators, ZIP packages).</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="limits">The limits; <see langword="null"/> for the store defaults.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The writer; dispose it in every case.</returns>
|
||||
Task<IFileStoreWriter> CreateAsync(string companyCode, FileLimits? limits = null, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Opens a file for reading.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="key">The key returned when the file was saved.</param>
|
||||
/// <returns>A read-only seekable stream; dispose it.</returns>
|
||||
/// <exception cref="FileStoreException">The file does not exist (code <see cref="FileStoreException.NotFound"/>).</exception>
|
||||
Stream OpenRead(string companyCode, string key);
|
||||
|
||||
/// <summary>Whether a file exists.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <returns><see langword="true"/> if it exists.</returns>
|
||||
bool Exists(string companyCode, string key);
|
||||
|
||||
/// <summary>Deletes a file; nothing happens when it does not exist.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <returns><see langword="true"/> if a file was deleted.</returns>
|
||||
bool Delete(string companyCode, string key);
|
||||
|
||||
/// <summary>The space the company uses, with its quota.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="quotaBytes">The quota to report; <see langword="null"/> for the store default.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The usage.</returns>
|
||||
Task<FileUsage> GetUsageAsync(string companyCode, long? quotaBytes = null, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Removes the partial files (<c>.part</c>) left by writes interrupted more than <paramref name="olderThan"/> ago.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="olderThan">How old a partial file must be.</param>
|
||||
/// <returns>How many were removed.</returns>
|
||||
int DeleteAbandonedParts(string companyCode, TimeSpan olderThan);
|
||||
}
|
||||
|
||||
/// <summary>The verdict of a scanner.</summary>
|
||||
/// <param name="Clean">Whether the file may be stored.</param>
|
||||
/// <param name="Reason">Why it was refused (for example the name of the threat).</param>
|
||||
public sealed record FileScanResult(bool Clean, string? Reason = null)
|
||||
{
|
||||
/// <summary>The file may be stored.</summary>
|
||||
public static FileScanResult Ok { get; } = new(true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The hook for an antivirus (SPEC §9.4): Khaemhat includes none, the default implementation accepts every file. It
|
||||
/// runs on the complete file before it becomes visible.
|
||||
/// </summary>
|
||||
public interface IFileScanner
|
||||
{
|
||||
/// <summary>Scans a file.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="content">The content, readable from the start.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The verdict.</returns>
|
||||
ValueTask<FileScanResult> ScanAsync(string companyCode, Stream content, CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using Khaemhat.Core.Entities;
|
||||
|
||||
namespace Khaemhat.Core.Instance;
|
||||
|
||||
/// <summary>
|
||||
/// A preference of the whole company (<c>company_settings</c>), such as the default dashboard of a role: one value per
|
||||
/// key, written by whoever holds <c>company.settings.write</c>.
|
||||
/// </summary>
|
||||
public sealed class CompanySetting : Entity<long>
|
||||
{
|
||||
/// <summary>The key, such as <c>dashboard.layout.role.SALES</c>.</summary>
|
||||
public string Key { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The value, often JSON.</summary>
|
||||
public string? Value { get; set; }
|
||||
}
|
||||
@@ -347,3 +347,23 @@ public sealed class SystemNotification : NotificationRecord;
|
||||
|
||||
/// <summary>A notification for company users (<c>notifications</c>).</summary>
|
||||
public sealed class Notification : NotificationRecord;
|
||||
|
||||
/// <summary>
|
||||
/// That a user read a notification addressed to everyone: each user reads it for themselves (<c>notification_reads</c>,
|
||||
/// <c>sys_notification_reads</c>). A notification for one user keeps its own <see cref="NotificationRecord.ReadAt"/>.
|
||||
/// The audit column <c>created_at</c> is when it was read.
|
||||
/// </summary>
|
||||
public abstract class NotificationReadRecord : Entity<long>
|
||||
{
|
||||
/// <summary>The notification.</summary>
|
||||
public long NotificationId { get; set; }
|
||||
|
||||
/// <summary>The user who read it.</summary>
|
||||
public long UserId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>An instance account read a notification for everyone (<c>sys_notification_reads</c>).</summary>
|
||||
public sealed class SystemNotificationRead : NotificationReadRecord;
|
||||
|
||||
/// <summary>A company user read a notification for everyone (<c>notification_reads</c>).</summary>
|
||||
public sealed class NotificationRead : NotificationReadRecord;
|
||||
@@ -0,0 +1,25 @@
|
||||
using Khaemhat.Core.Entities;
|
||||
|
||||
namespace Khaemhat.Core.Instance;
|
||||
|
||||
/// <summary>
|
||||
/// One preference of one user (SPEC §10.6): theme, accent, menu state, dashboard layout, grid layouts... The value is
|
||||
/// a string, usually JSON for structured preferences.
|
||||
/// </summary>
|
||||
public abstract class UserSettingRecord : Entity<long>
|
||||
{
|
||||
/// <summary>The user the preference belongs to.</summary>
|
||||
public long UserId { get; set; }
|
||||
|
||||
/// <summary>The key, for example <c>ui.theme</c> or <c>grid.parties.columns</c>.</summary>
|
||||
public string Key { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The value.</summary>
|
||||
public string? Value { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A preference of an instance account (<c>sys_user_settings</c>): it follows the account in every company.</summary>
|
||||
public sealed class SystemUserSetting : UserSettingRecord;
|
||||
|
||||
/// <summary>A preference of a company user (<c>user_settings</c>).</summary>
|
||||
public sealed class UserSetting : UserSettingRecord;
|
||||
@@ -1,3 +1,4 @@
|
||||
using Khaemhat.Core.Files;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Core.Security;
|
||||
using Khaemhat.Data.Mapping;
|
||||
@@ -95,3 +96,50 @@ public sealed class NotificationMap : EntityMap<Notification>
|
||||
NotificationColumns.Configure(this);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="NotificationRead"/> to <c>notification_reads</c>.</summary>
|
||||
public sealed class NotificationReadMap : EntityMap<NotificationRead>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public NotificationReadMap() => ToTable("notification_reads");
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="UserSetting"/> to <c>user_settings</c>.</summary>
|
||||
public sealed class UserSettingMap : EntityMap<UserSetting>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public UserSettingMap()
|
||||
{
|
||||
ToTable("user_settings");
|
||||
Map(x => x.Key).MaxLength(200);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="CompanySetting"/> to <c>company_settings</c>.</summary>
|
||||
public sealed class CompanySettingMap : EntityMap<CompanySetting>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public CompanySettingMap()
|
||||
{
|
||||
ToTable("company_settings");
|
||||
Map(x => x.Key).MaxLength(200);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="Attachment"/> to <c>attachments</c>.</summary>
|
||||
public sealed class AttachmentMap : EntityMap<Attachment>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public AttachmentMap()
|
||||
{
|
||||
ToTable("attachments");
|
||||
Map(x => x.Entity).MaxLength(100);
|
||||
Map(x => x.Name).MaxLength(255);
|
||||
Map(x => x.Mime).MaxLength(150);
|
||||
Map(x => x.Sha256).MaxLength(64);
|
||||
Map(x => x.VersionKey).MaxLength(300);
|
||||
Map(x => x.GeneratedBy).MaxLength(100);
|
||||
Map(x => x.StorageKey).MaxLength(60);
|
||||
Map(x => x.UserName).MaxLength(100);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase.Migrations;
|
||||
|
||||
/// <summary>The interface preferences of the company users (SPEC §10.6).</summary>
|
||||
[Migration(20261111_006, "create_user_settings")]
|
||||
public sealed class M20261111_006_CreateUserSettings : IMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public void Up(ISchemaBuilder schema)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(schema);
|
||||
schema.CreateTable("user_settings", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("user_id").NotNull();
|
||||
t.String("key", 200).NotNull();
|
||||
t.Text("value");
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_user_settings_user_id_key", "user_id", "key");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase.Migrations;
|
||||
|
||||
/// <summary>The attachments of the company records, uploaded and generated (SPEC §9.4, ADR 0021).</summary>
|
||||
[Migration(20261111_007, "create_attachments")]
|
||||
public sealed class M20261111_007_CreateAttachments : IMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public void Up(ISchemaBuilder schema)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(schema);
|
||||
schema.CreateTable("attachments", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("entity", 100).NotNull();
|
||||
t.Int64("entity_id").NotNull();
|
||||
t.String("kind", 40).NotNull();
|
||||
t.String("name", 255).NotNull();
|
||||
t.String("mime", 150).NotNull();
|
||||
t.Int64("size").NotNull();
|
||||
t.String("sha256", 64).NotNull();
|
||||
t.Int32("version").NotNull();
|
||||
t.String("version_key", 300).NotNull();
|
||||
t.String("generated_by", 100);
|
||||
t.String("storage_key", 60).NotNull();
|
||||
t.String("user_name", 100);
|
||||
t.Bool("locked").NotNull().Default(false);
|
||||
t.DateTimeUtc("deleted_at");
|
||||
t.AuditColumns();
|
||||
t.Index("ix_attachments_entity_entity_id", "entity", "entity_id");
|
||||
t.Unique("ux_attachments_entity_entity_id_version_key_version", "entity", "entity_id", "version_key", "version");
|
||||
t.Index("ix_attachments_deleted_at", "deleted_at");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase.Migrations;
|
||||
|
||||
/// <summary>The preferences of the company as a whole, such as the default dashboard of each role (SPEC §10.3).</summary>
|
||||
[Migration(20261111_008, "create_company_settings")]
|
||||
public sealed class M20261111_008_CreateCompanySettings : IMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public void Up(ISchemaBuilder schema)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(schema);
|
||||
schema.CreateTable("company_settings", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("key", 200).NotNull();
|
||||
t.Text("value");
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_company_settings_key", "key");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.CompanyDatabase.Migrations;
|
||||
|
||||
/// <summary>Who read a notification addressed to everyone (SPEC §9, mockup 010): each user marks it for themselves.</summary>
|
||||
[Migration(20261111_009, "create_notification_reads")]
|
||||
public sealed class M20261111_009_CreateNotificationReads : IMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public void Up(ISchemaBuilder schema)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(schema);
|
||||
schema.CreateTable("notification_reads", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("notification_id").NotNull();
|
||||
t.Int64("user_id").NotNull();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_notification_reads_notification_user", "notification_id", "user_id");
|
||||
t.Index("ix_notification_reads_user_id", "user_id");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.SystemDatabase.Migrations;
|
||||
|
||||
/// <summary>The interface preferences of the instance accounts (SPEC §10.6).</summary>
|
||||
[Migration(20261111_012, "create_sys_user_settings", Target = MigrationTarget.System)]
|
||||
public sealed class M20261111_012_CreateSysUserSettings : IMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public void Up(ISchemaBuilder schema)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(schema);
|
||||
schema.CreateTable("sys_user_settings", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("user_id").NotNull();
|
||||
t.String("key", 200).NotNull();
|
||||
t.Text("value");
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_sys_user_settings_user_id_key", "user_id", "key");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.SystemDatabase.Migrations;
|
||||
|
||||
/// <summary>Who read a notification addressed to everyone (SPEC §9, mockup 010): each user marks it for themselves.</summary>
|
||||
[Migration(20261111_013, "create_sys_notification_reads", Target = MigrationTarget.System)]
|
||||
public sealed class M20261111_013_CreateSysNotificationReads : IMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public void Up(ISchemaBuilder schema)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(schema);
|
||||
schema.CreateTable("sys_notification_reads", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.Int64("notification_id").NotNull();
|
||||
t.Int64("user_id").NotNull();
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_sys_notification_reads_notification_user", "notification_id", "user_id");
|
||||
t.Index("ix_sys_notification_reads_user_id", "user_id");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -197,6 +197,13 @@ public sealed class SystemNotificationMap : EntityMap<SystemNotification>
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="SystemNotificationRead"/> to <c>sys_notification_reads</c>.</summary>
|
||||
public sealed class SystemNotificationReadMap : EntityMap<SystemNotificationRead>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public SystemNotificationReadMap() => ToTable("sys_notification_reads");
|
||||
}
|
||||
|
||||
/// <summary>The notification columns shared by <c>sys_notifications</c> and <c>notifications</c>.</summary>
|
||||
internal static class NotificationColumns
|
||||
{
|
||||
|
||||
@@ -27,3 +27,14 @@ public sealed class SystemSettingMap : EntityMap<SystemSetting>
|
||||
Map(x => x.Key).MaxLength(200);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="SystemUserSetting"/> to <c>sys_user_settings</c>.</summary>
|
||||
public sealed class SystemUserSettingMap : EntityMap<SystemUserSetting>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public SystemUserSettingMap()
|
||||
{
|
||||
ToTable("sys_user_settings");
|
||||
Map(x => x.Key).MaxLength(200);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
namespace Khaemhat.Infrastructure.Files;
|
||||
|
||||
/// <summary>
|
||||
/// Sits between <see cref="System.IO.Compression.ZipArchive"/> and an output that refuses synchronous writes (an
|
||||
/// ASP.NET Core response). The archive still writes some parts synchronously (entry trailers on dispose, the central
|
||||
/// directory): those bytes are kept here and sent with the next asynchronous call or <see cref="DrainAsync"/>, while
|
||||
/// the bulk of the data, written asynchronously, goes straight through. Memory stays bounded by the small synchronous
|
||||
/// pieces, so archives are still streamed.
|
||||
/// </summary>
|
||||
/// <param name="output">The real output.</param>
|
||||
internal sealed class AsyncOutputBuffer(Stream output) : Stream
|
||||
{
|
||||
private readonly MemoryStream _pending = new();
|
||||
|
||||
public override bool CanRead => false;
|
||||
|
||||
public override bool CanSeek => false;
|
||||
|
||||
public override bool CanWrite => true;
|
||||
|
||||
public override long Length => throw new NotSupportedException();
|
||||
|
||||
public override long Position
|
||||
{
|
||||
get => throw new NotSupportedException();
|
||||
set => throw new NotSupportedException();
|
||||
}
|
||||
|
||||
/// <summary>Sends the bytes written synchronously to the output.</summary>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task DrainAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (_pending.Length > 0)
|
||||
{
|
||||
await output.WriteAsync(_pending.GetBuffer().AsMemory(0, (int)_pending.Length), cancellationToken).ConfigureAwait(false);
|
||||
_pending.SetLength(0);
|
||||
}
|
||||
}
|
||||
|
||||
public override void Write(byte[] buffer, int offset, int count) => _pending.Write(buffer, offset, count);
|
||||
|
||||
public override void Write(ReadOnlySpan<byte> buffer) => _pending.Write(buffer);
|
||||
|
||||
public override void WriteByte(byte value) => _pending.WriteByte(value);
|
||||
|
||||
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
|
||||
WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
|
||||
|
||||
public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await DrainAsync(cancellationToken).ConfigureAwait(false);
|
||||
await output.WriteAsync(buffer, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Does nothing: synchronous flushes would reach the output synchronously.</summary>
|
||||
public override void Flush()
|
||||
{
|
||||
}
|
||||
|
||||
public override async Task FlushAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
await DrainAsync(cancellationToken).ConfigureAwait(false);
|
||||
await output.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
|
||||
|
||||
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
|
||||
|
||||
public override void SetLength(long value) => throw new NotSupportedException();
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_pending.Dispose();
|
||||
}
|
||||
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Files;
|
||||
|
||||
/// <summary>How numbers and dates are written in a CSV file.</summary>
|
||||
public enum CsvNumberFormat
|
||||
{
|
||||
/// <summary>Italian Excel: decimal comma (<c>1234,5</c>), dates <c>dd/MM/yyyy</c>, booleans <c>VERO</c>/<c>FALSO</c>.</summary>
|
||||
Italian = 0,
|
||||
|
||||
/// <summary>Machine readable: decimal point (<c>1234.5</c>), ISO 8601 dates, booleans <c>true</c>/<c>false</c>.</summary>
|
||||
Invariant = 1,
|
||||
}
|
||||
|
||||
/// <summary>The options of a <see cref="CsvWriter"/>. The defaults suit Excel in Italian (ADR 0021).</summary>
|
||||
public sealed record CsvOptions
|
||||
{
|
||||
/// <summary>The field separator: <c>;</c> by default, because Italian Excel uses the comma for decimals.</summary>
|
||||
public char Separator { get; init; } = ';';
|
||||
|
||||
/// <summary>Whether the file starts with the UTF-8 byte order mark, which Excel needs to read accented letters.</summary>
|
||||
public bool WriteByteOrderMark { get; init; } = true;
|
||||
|
||||
/// <summary>How numbers, dates and booleans are formatted.</summary>
|
||||
public CsvNumberFormat NumberFormat { get; init; } = CsvNumberFormat.Italian;
|
||||
|
||||
/// <summary>
|
||||
/// Whether text cells that a spreadsheet would read as a formula (starting with <c>=</c>, <c>+</c>, <c>-</c>,
|
||||
/// <c>@</c>, tab or carriage return) get a leading apostrophe (CSV injection, OWASP). Numbers are never changed.
|
||||
/// </summary>
|
||||
public bool ProtectFormulas { get; init; } = true;
|
||||
|
||||
/// <summary>The line terminator: CRLF as RFC 4180 says.</summary>
|
||||
public string NewLine { get; init; } = "\r\n";
|
||||
|
||||
/// <summary>The Italian Excel defaults.</summary>
|
||||
public static CsvOptions Italian { get; } = new();
|
||||
|
||||
/// <summary>Comma separator, invariant numbers, no byte order mark: for other programs.</summary>
|
||||
public static CsvOptions Invariant { get; } = new() { Separator = ',', NumberFormat = CsvNumberFormat.Invariant, WriteByteOrderMark = false };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes CSV files (RFC 4180) row by row (SPEC §2, §9.4). Fields with separator, quotes or line breaks are quoted and
|
||||
/// quotes doubled. Rows are buffered in memory and written to the stream when the buffer grows past a few KB: use the
|
||||
/// <c>Async</c> methods when the stream is an HTTP response, where synchronous writes are not allowed.
|
||||
/// </summary>
|
||||
/// <example>
|
||||
/// <code>
|
||||
/// await using var csv = new CsvWriter(response.Body);
|
||||
/// await csv.WriteRowAsync(["Codice", "Descrizione", "Importo"]);
|
||||
/// await csv.WriteRowAsync(["A1", "Vite M4", 12.5m]);
|
||||
/// </code>
|
||||
/// </example>
|
||||
public sealed class CsvWriter : IDisposable, IAsyncDisposable
|
||||
{
|
||||
private const int FlushThreshold = 16 * 1024;
|
||||
private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT");
|
||||
private static readonly UTF8Encoding Utf8 = new(encoderShouldEmitUTF8Identifier: false);
|
||||
|
||||
private readonly Stream _output;
|
||||
private readonly bool _leaveOpen;
|
||||
private readonly StringBuilder _buffer = new();
|
||||
private bool _rowHasFields;
|
||||
private bool _preambleWritten;
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>Creates a writer.</summary>
|
||||
/// <param name="output">The stream that receives the file.</param>
|
||||
/// <param name="options">The options; <see langword="null"/> for <see cref="CsvOptions.Italian"/>.</param>
|
||||
/// <param name="leaveOpen">Whether to leave <paramref name="output"/> open on dispose.</param>
|
||||
public CsvWriter(Stream output, CsvOptions? options = null, bool leaveOpen = false)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(output);
|
||||
_output = output;
|
||||
_leaveOpen = leaveOpen;
|
||||
Options = options ?? CsvOptions.Italian;
|
||||
if (Options.Separator is '"' or '\r' or '\n')
|
||||
{
|
||||
throw new ArgumentException("The separator cannot be a quote or a line break.", nameof(options));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The options.</summary>
|
||||
public CsvOptions Options { get; }
|
||||
|
||||
/// <summary>The number of rows completed.</summary>
|
||||
public long RowCount { get; private set; }
|
||||
|
||||
/// <summary>Formats a text field: formula protection, then quoting when needed.</summary>
|
||||
/// <param name="value">The text.</param>
|
||||
/// <param name="options">The options.</param>
|
||||
/// <returns>The field as written in the file.</returns>
|
||||
public static string EscapeText(string? value, CsvOptions options)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
if (string.IsNullOrEmpty(value))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
if (options.ProtectFormulas && value[0] is '=' or '+' or '-' or '@' or '\t' or '\r')
|
||||
{
|
||||
value = "'" + value;
|
||||
}
|
||||
|
||||
return Quote(value, options.Separator);
|
||||
}
|
||||
|
||||
/// <summary>Formats a value as it would be written (numbers and dates by <see cref="CsvOptions.NumberFormat"/>).</summary>
|
||||
/// <param name="value">The value.</param>
|
||||
/// <param name="options">The options.</param>
|
||||
/// <returns>The field as written in the file.</returns>
|
||||
public static string FormatValue(object? value, CsvOptions options)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
var culture = options.NumberFormat == CsvNumberFormat.Italian ? Italian : CultureInfo.InvariantCulture;
|
||||
var italian = options.NumberFormat == CsvNumberFormat.Italian;
|
||||
var text = value switch
|
||||
{
|
||||
null => null,
|
||||
string s => s,
|
||||
bool b => italian ? (b ? "VERO" : "FALSO") : (b ? "true" : "false"),
|
||||
DateOnly d => d.ToString(italian ? "dd/MM/yyyy" : "yyyy-MM-dd", CultureInfo.InvariantCulture),
|
||||
DateTime d when d.TimeOfDay == TimeSpan.Zero => d.ToString(italian ? "dd/MM/yyyy" : "yyyy-MM-dd", CultureInfo.InvariantCulture),
|
||||
DateTime d => d.ToString(italian ? "dd/MM/yyyy HH:mm:ss" : "yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture),
|
||||
DateTimeOffset d => d.ToString(italian ? "dd/MM/yyyy HH:mm:ss" : "yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture),
|
||||
decimal m => m.ToString("0.############################", culture),
|
||||
double x when double.IsFinite(x) => x.ToString("0.###############", culture),
|
||||
float x when float.IsFinite(x) => x.ToString("0.#######", culture),
|
||||
double or float => string.Empty,
|
||||
IFormattable f => f.ToString(null, culture),
|
||||
_ => value.ToString(),
|
||||
};
|
||||
|
||||
// Only text can carry a formula: numbers, dates and booleans are written as they are.
|
||||
return value is string or char or Enum || value is not IFormattable and not bool
|
||||
? EscapeText(text, options)
|
||||
: Quote(text ?? string.Empty, options.Separator);
|
||||
}
|
||||
|
||||
/// <summary>Adds a field to the current row.</summary>
|
||||
/// <param name="value">Text, number, date, boolean or <see langword="null"/> (empty field).</param>
|
||||
/// <returns>This writer.</returns>
|
||||
public CsvWriter WriteField(object? value)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
if (_rowHasFields)
|
||||
{
|
||||
_buffer.Append(Options.Separator);
|
||||
}
|
||||
|
||||
_buffer.Append(FormatValue(value, Options));
|
||||
_rowHasFields = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>Ends the current row; writes to the stream synchronously when the buffer is large.</summary>
|
||||
public void EndRow()
|
||||
{
|
||||
CompleteRow();
|
||||
if (_buffer.Length >= FlushThreshold)
|
||||
{
|
||||
Flush();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Ends the current row; writes to the stream when the buffer is large.</summary>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async ValueTask EndRowAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
CompleteRow();
|
||||
if (_buffer.Length >= FlushThreshold)
|
||||
{
|
||||
await FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Writes a whole row (synchronous stream).</summary>
|
||||
/// <param name="values">The fields.</param>
|
||||
public void WriteRow(params IEnumerable<object?> values)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(values);
|
||||
foreach (var value in values)
|
||||
{
|
||||
WriteField(value);
|
||||
}
|
||||
|
||||
EndRow();
|
||||
}
|
||||
|
||||
/// <summary>Writes a whole row.</summary>
|
||||
/// <param name="values">The fields.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public ValueTask WriteRowAsync(IEnumerable<object?> values, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(values);
|
||||
foreach (var value in values)
|
||||
{
|
||||
WriteField(value);
|
||||
}
|
||||
|
||||
return EndRowAsync(cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Writes the buffered rows to the stream synchronously.</summary>
|
||||
public void Flush()
|
||||
{
|
||||
var bytes = TakeBytes();
|
||||
if (bytes.Length > 0)
|
||||
{
|
||||
_output.Write(bytes);
|
||||
}
|
||||
|
||||
_output.Flush();
|
||||
}
|
||||
|
||||
/// <summary>Writes the buffered rows to the stream.</summary>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task FlushAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var bytes = TakeBytes();
|
||||
if (bytes.Length > 0)
|
||||
{
|
||||
await _output.WriteAsync(bytes, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await _output.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Ends a pending row, writes the buffer synchronously and closes the stream unless left open.</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_rowHasFields)
|
||||
{
|
||||
CompleteRow();
|
||||
}
|
||||
|
||||
Flush();
|
||||
_disposed = true;
|
||||
if (!_leaveOpen)
|
||||
{
|
||||
_output.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Ends a pending row, writes the buffer and closes the stream unless left open.</summary>
|
||||
/// <returns>A task.</returns>
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_rowHasFields)
|
||||
{
|
||||
CompleteRow();
|
||||
}
|
||||
|
||||
await FlushAsync().ConfigureAwait(false);
|
||||
_disposed = true;
|
||||
if (!_leaveOpen)
|
||||
{
|
||||
await _output.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private static string Quote(string value, char separator)
|
||||
{
|
||||
var needsQuotes = value.Length > 0
|
||||
&& (value.Contains(separator, StringComparison.Ordinal) || value.AsSpan().IndexOfAny("\"\r\n") >= 0
|
||||
|| char.IsWhiteSpace(value[0]) || char.IsWhiteSpace(value[^1]));
|
||||
return needsQuotes ? "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"" : value;
|
||||
}
|
||||
|
||||
private void CompleteRow()
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
_buffer.Append(Options.NewLine);
|
||||
_rowHasFields = false;
|
||||
RowCount++;
|
||||
}
|
||||
|
||||
private byte[] TakeBytes()
|
||||
{
|
||||
var preamble = !_preambleWritten && Options.WriteByteOrderMark ? Encoding.UTF8.Preamble.ToArray() : [];
|
||||
_preambleWritten = true;
|
||||
if (_buffer.Length == 0 && preamble.Length == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var text = _buffer.ToString();
|
||||
_buffer.Clear();
|
||||
var bytes = new byte[preamble.Length + Utf8.GetByteCount(text)];
|
||||
preamble.CopyTo(bytes, 0);
|
||||
Utf8.GetBytes(text, 0, text.Length, bytes, preamble.Length);
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
using System.Text;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Files;
|
||||
|
||||
/// <summary>
|
||||
/// The standard Type1 fonts every PDF reader has (PDF 1.7 §9.6.2.2), with <c>WinAnsiEncoding</c> so that Italian
|
||||
/// letters and the euro sign print. Symbol and ZapfDingbats are not offered: they have no Latin encoding.
|
||||
/// </summary>
|
||||
public enum PdfFont
|
||||
{
|
||||
/// <summary>Helvetica.</summary>
|
||||
Helvetica = 0,
|
||||
|
||||
/// <summary>Helvetica bold.</summary>
|
||||
HelveticaBold = 1,
|
||||
|
||||
/// <summary>Helvetica oblique.</summary>
|
||||
HelveticaOblique = 2,
|
||||
|
||||
/// <summary>Helvetica bold oblique.</summary>
|
||||
HelveticaBoldOblique = 3,
|
||||
|
||||
/// <summary>Times roman.</summary>
|
||||
TimesRoman = 4,
|
||||
|
||||
/// <summary>Times bold (measured with the Times roman widths).</summary>
|
||||
TimesBold = 5,
|
||||
|
||||
/// <summary>Times italic (measured with the Times roman widths).</summary>
|
||||
TimesItalic = 6,
|
||||
|
||||
/// <summary>Times bold italic (measured with the Times roman widths).</summary>
|
||||
TimesBoldItalic = 7,
|
||||
|
||||
/// <summary>Courier: every character is 600/1000 em wide.</summary>
|
||||
Courier = 8,
|
||||
|
||||
/// <summary>Courier bold.</summary>
|
||||
CourierBold = 9,
|
||||
|
||||
/// <summary>Courier oblique.</summary>
|
||||
CourierOblique = 10,
|
||||
|
||||
/// <summary>Courier bold oblique.</summary>
|
||||
CourierBoldOblique = 11,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Text measuring and line breaking for the standard fonts, from the Adobe font metrics (AFM) widths in thousandths of
|
||||
/// an em, and the <c>WinAnsiEncoding</c> (Windows-1252) used to write text. Helvetica, Helvetica bold and Times roman
|
||||
/// widths are exact; the Times bold and italic faces reuse the roman widths (a close approximation); Courier is fixed
|
||||
/// width.
|
||||
/// </summary>
|
||||
public static class PdfTextLayout
|
||||
{
|
||||
// Widths for codes 32..126.
|
||||
private static readonly int[] HelveticaAscii =
|
||||
[
|
||||
278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278,
|
||||
556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556,
|
||||
1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778,
|
||||
667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556,
|
||||
333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556,
|
||||
556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584,
|
||||
];
|
||||
|
||||
private static readonly int[] HelveticaBoldAscii =
|
||||
[
|
||||
278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278,
|
||||
556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611,
|
||||
975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778,
|
||||
667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556,
|
||||
333, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611,
|
||||
611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584,
|
||||
];
|
||||
|
||||
private static readonly int[] TimesAscii =
|
||||
[
|
||||
250, 333, 408, 500, 500, 833, 778, 180, 333, 333, 500, 564, 250, 333, 250, 278,
|
||||
500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 278, 278, 564, 564, 564, 444,
|
||||
921, 722, 667, 667, 722, 611, 556, 722, 722, 333, 389, 722, 611, 889, 722, 722,
|
||||
556, 722, 667, 556, 611, 722, 722, 944, 722, 722, 611, 333, 278, 333, 469, 500,
|
||||
333, 444, 500, 444, 500, 444, 333, 500, 500, 278, 278, 500, 278, 778, 500, 500,
|
||||
500, 500, 333, 389, 278, 500, 500, 722, 500, 500, 444, 480, 200, 480, 541,
|
||||
];
|
||||
|
||||
// Widths for codes 128..159 (0 = not defined in WinAnsiEncoding).
|
||||
private static readonly int[] HelveticaWin =
|
||||
[
|
||||
556, 0, 222, 556, 333, 1000, 556, 556, 333, 1000, 667, 333, 1000, 0, 611, 0,
|
||||
0, 222, 222, 333, 333, 350, 556, 1000, 333, 1000, 500, 333, 944, 0, 500, 667,
|
||||
];
|
||||
|
||||
private static readonly int[] HelveticaBoldWin =
|
||||
[
|
||||
556, 0, 278, 556, 500, 1000, 556, 556, 333, 1000, 667, 333, 1000, 0, 611, 0,
|
||||
0, 278, 278, 500, 500, 350, 556, 1000, 333, 1000, 556, 333, 944, 0, 500, 667,
|
||||
];
|
||||
|
||||
private static readonly int[] TimesWin =
|
||||
[
|
||||
500, 0, 333, 500, 444, 1000, 500, 500, 333, 1000, 556, 333, 889, 0, 611, 0,
|
||||
0, 333, 333, 444, 444, 350, 500, 1000, 333, 980, 389, 333, 722, 0, 444, 722,
|
||||
];
|
||||
|
||||
// Widths for codes 160..255.
|
||||
private static readonly int[] HelveticaLatin =
|
||||
[
|
||||
278, 333, 556, 556, 556, 556, 260, 556, 333, 737, 370, 556, 584, 333, 737, 333,
|
||||
400, 584, 333, 333, 333, 556, 537, 278, 333, 333, 365, 556, 834, 834, 834, 611,
|
||||
667, 667, 667, 667, 667, 667, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278,
|
||||
722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611,
|
||||
556, 556, 556, 556, 556, 556, 889, 500, 556, 556, 556, 556, 278, 278, 278, 278,
|
||||
556, 556, 556, 556, 556, 556, 556, 584, 611, 556, 556, 556, 556, 500, 556, 500,
|
||||
];
|
||||
|
||||
private static readonly int[] HelveticaBoldLatin =
|
||||
[
|
||||
278, 333, 556, 556, 556, 556, 280, 556, 333, 737, 370, 556, 584, 333, 737, 333,
|
||||
400, 584, 333, 333, 333, 611, 556, 278, 333, 333, 365, 556, 834, 834, 834, 611,
|
||||
722, 722, 722, 722, 722, 722, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278,
|
||||
722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611,
|
||||
556, 556, 556, 556, 556, 556, 889, 556, 556, 556, 556, 556, 278, 278, 278, 278,
|
||||
611, 611, 611, 611, 611, 611, 611, 584, 611, 611, 611, 611, 611, 556, 611, 556,
|
||||
];
|
||||
|
||||
private static readonly int[] TimesLatin =
|
||||
[
|
||||
250, 333, 500, 500, 500, 500, 200, 500, 333, 760, 276, 500, 564, 333, 760, 333,
|
||||
400, 564, 300, 300, 333, 500, 453, 250, 333, 300, 310, 500, 750, 750, 750, 444,
|
||||
722, 722, 722, 722, 722, 722, 889, 667, 611, 611, 611, 611, 333, 333, 333, 333,
|
||||
722, 722, 722, 722, 722, 722, 722, 564, 722, 722, 722, 722, 722, 722, 556, 500,
|
||||
444, 444, 444, 444, 444, 444, 667, 444, 444, 444, 444, 444, 278, 278, 278, 278,
|
||||
500, 500, 500, 500, 500, 500, 500, 564, 500, 500, 500, 500, 500, 500, 500, 500,
|
||||
];
|
||||
|
||||
// Full tables for codes 0..255.
|
||||
private static readonly int[] Helvetica = Table(HelveticaAscii, HelveticaWin, HelveticaLatin);
|
||||
private static readonly int[] HelveticaBold = Table(HelveticaBoldAscii, HelveticaBoldWin, HelveticaBoldLatin);
|
||||
private static readonly int[] Times = Table(TimesAscii, TimesWin, TimesLatin);
|
||||
|
||||
// Unicode to WinAnsiEncoding for the codes 128..159 that differ from Latin-1.
|
||||
private static readonly Dictionary<char, byte> WinAnsiSpecials = new()
|
||||
{
|
||||
['€'] = 0x80, ['‚'] = 0x82, ['ƒ'] = 0x83, ['„'] = 0x84, ['…'] = 0x85, ['†'] = 0x86, ['‡'] = 0x87, ['ˆ'] = 0x88,
|
||||
['‰'] = 0x89, ['Š'] = 0x8A, ['‹'] = 0x8B, ['Œ'] = 0x8C, ['Ž'] = 0x8E, ['‘'] = 0x91, ['’'] = 0x92, ['“'] = 0x93,
|
||||
['”'] = 0x94, ['•'] = 0x95, ['–'] = 0x96, ['—'] = 0x97, ['˜'] = 0x98, ['™'] = 0x99, ['š'] = 0x9A, ['›'] = 0x9B,
|
||||
['œ'] = 0x9C, ['ž'] = 0x9E, ['Ÿ'] = 0x9F,
|
||||
};
|
||||
|
||||
/// <summary>The PostScript name of a font, as written in <c>/BaseFont</c>.</summary>
|
||||
/// <param name="font">The font.</param>
|
||||
/// <returns>The name, for example <c>Helvetica-Bold</c>.</returns>
|
||||
public static string BaseFontName(PdfFont font) => font switch
|
||||
{
|
||||
PdfFont.Helvetica => "Helvetica",
|
||||
PdfFont.HelveticaBold => "Helvetica-Bold",
|
||||
PdfFont.HelveticaOblique => "Helvetica-Oblique",
|
||||
PdfFont.HelveticaBoldOblique => "Helvetica-BoldOblique",
|
||||
PdfFont.TimesRoman => "Times-Roman",
|
||||
PdfFont.TimesBold => "Times-Bold",
|
||||
PdfFont.TimesItalic => "Times-Italic",
|
||||
PdfFont.TimesBoldItalic => "Times-BoldItalic",
|
||||
PdfFont.Courier => "Courier",
|
||||
PdfFont.CourierBold => "Courier-Bold",
|
||||
PdfFont.CourierOblique => "Courier-Oblique",
|
||||
PdfFont.CourierBoldOblique => "Courier-BoldOblique",
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(font), font, "Unknown font."),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Encodes text in <c>WinAnsiEncoding</c>: ASCII, Latin-1 letters (àèéìòù...), the euro sign and the typographic
|
||||
/// quotes and dashes. Line breaks and tabs become spaces; characters the encoding lacks become <c>?</c>.
|
||||
/// </summary>
|
||||
/// <param name="text">The text.</param>
|
||||
/// <returns>One byte per character.</returns>
|
||||
public static byte[] EncodeWinAnsi(string? text)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var bytes = new byte[text.Length];
|
||||
for (var i = 0; i < text.Length; i++)
|
||||
{
|
||||
bytes[i] = ToWinAnsi(text[i]);
|
||||
}
|
||||
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/// <summary>The width of a character code in thousandths of an em.</summary>
|
||||
/// <param name="code">The <c>WinAnsiEncoding</c> code.</param>
|
||||
/// <param name="font">The font.</param>
|
||||
/// <returns>The width.</returns>
|
||||
public static int GlyphWidth(byte code, PdfFont font) => font switch
|
||||
{
|
||||
PdfFont.Helvetica or PdfFont.HelveticaOblique => Helvetica[code],
|
||||
PdfFont.HelveticaBold or PdfFont.HelveticaBoldOblique => HelveticaBold[code],
|
||||
PdfFont.TimesRoman or PdfFont.TimesBold or PdfFont.TimesItalic or PdfFont.TimesBoldItalic => Times[code],
|
||||
_ => code >= 32 ? 600 : 0,
|
||||
};
|
||||
|
||||
/// <summary>The width of a text in points.</summary>
|
||||
/// <param name="text">The text.</param>
|
||||
/// <param name="font">The font.</param>
|
||||
/// <param name="size">The font size in points.</param>
|
||||
/// <returns>The width.</returns>
|
||||
public static double Measure(string? text, PdfFont font, double size)
|
||||
{
|
||||
var total = 0;
|
||||
foreach (var code in EncodeWinAnsi(text))
|
||||
{
|
||||
total += GlyphWidth(code, font);
|
||||
}
|
||||
|
||||
return total * size / 1000.0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Breaks a text into lines no wider than <paramref name="maxWidth"/>: at line breaks, then between words; a word
|
||||
/// longer than a line is cut.
|
||||
/// </summary>
|
||||
/// <param name="text">The text.</param>
|
||||
/// <param name="font">The font.</param>
|
||||
/// <param name="size">The font size.</param>
|
||||
/// <param name="maxWidth">The line width in points.</param>
|
||||
/// <returns>The lines (one empty line for an empty text).</returns>
|
||||
public static IReadOnlyList<string> Wrap(string? text, PdfFont font, double size, double maxWidth)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxWidth);
|
||||
var lines = new List<string>();
|
||||
foreach (var paragraph in (text ?? string.Empty).Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n'))
|
||||
{
|
||||
var line = new StringBuilder();
|
||||
foreach (var word in paragraph.Split(' ', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
var candidate = line.Length == 0 ? word : line + " " + word;
|
||||
if (Measure(candidate, font, size) <= maxWidth)
|
||||
{
|
||||
line.Clear().Append(candidate);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (line.Length > 0)
|
||||
{
|
||||
lines.Add(line.ToString());
|
||||
line.Clear();
|
||||
}
|
||||
|
||||
// A word wider than the line is cut where it no longer fits.
|
||||
var rest = word;
|
||||
while (Measure(rest, font, size) > maxWidth && rest.Length > 1)
|
||||
{
|
||||
var cut = rest.Length - 1;
|
||||
while (cut > 1 && Measure(rest[..cut], font, size) > maxWidth)
|
||||
{
|
||||
cut--;
|
||||
}
|
||||
|
||||
lines.Add(rest[..cut]);
|
||||
rest = rest[cut..];
|
||||
}
|
||||
|
||||
line.Append(rest);
|
||||
}
|
||||
|
||||
lines.Add(line.ToString());
|
||||
}
|
||||
|
||||
return lines;
|
||||
}
|
||||
|
||||
/// <summary>Shortens a text with an ellipsis so that it fits a width (table cells).</summary>
|
||||
/// <param name="text">The text.</param>
|
||||
/// <param name="font">The font.</param>
|
||||
/// <param name="size">The font size.</param>
|
||||
/// <param name="maxWidth">The width in points.</param>
|
||||
/// <returns>The text, shortened if needed.</returns>
|
||||
public static string Fit(string? text, PdfFont font, double size, double maxWidth)
|
||||
{
|
||||
text ??= string.Empty;
|
||||
if (Measure(text, font, size) <= maxWidth)
|
||||
{
|
||||
return text;
|
||||
}
|
||||
|
||||
for (var length = text.Length - 1; length > 0; length--)
|
||||
{
|
||||
var candidate = text[..length].TrimEnd() + "…";
|
||||
if (Measure(candidate, font, size) <= maxWidth)
|
||||
{
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
private static byte ToWinAnsi(char c) => c switch
|
||||
{
|
||||
'\t' or '\r' or '\n' => (byte)' ',
|
||||
>= ' ' and <= '~' => (byte)c,
|
||||
>= ' ' and <= 'ÿ' => (byte)c,
|
||||
_ => WinAnsiSpecials.TryGetValue(c, out var code) ? code : (byte)'?',
|
||||
};
|
||||
|
||||
private static int[] Table(int[] ascii, int[] win, int[] latin)
|
||||
{
|
||||
var table = new int[256];
|
||||
ascii.CopyTo(table, 32);
|
||||
win.CopyTo(table, 128);
|
||||
latin.CopyTo(table, 160);
|
||||
return table;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,679 @@
|
||||
using System.Globalization;
|
||||
using System.IO.Compression;
|
||||
using System.Text;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Files;
|
||||
|
||||
/// <summary>An RGB colour.</summary>
|
||||
/// <param name="R">Red, 0-255.</param>
|
||||
/// <param name="G">Green, 0-255.</param>
|
||||
/// <param name="B">Blue, 0-255.</param>
|
||||
public readonly record struct PdfColor(byte R, byte G, byte B)
|
||||
{
|
||||
/// <summary>Black.</summary>
|
||||
public static PdfColor Black { get; } = new(0, 0, 0);
|
||||
|
||||
/// <summary>White.</summary>
|
||||
public static PdfColor White { get; } = new(255, 255, 255);
|
||||
|
||||
/// <summary>A grey.</summary>
|
||||
/// <param name="level">0 (black) to 255 (white).</param>
|
||||
/// <returns>The colour.</returns>
|
||||
public static PdfColor Gray(byte level) => new(level, level, level);
|
||||
|
||||
/// <summary>A colour from <c>#RRGGBB</c>.</summary>
|
||||
/// <param name="hex">The colour, with or without <c>#</c>.</param>
|
||||
/// <returns>The colour.</returns>
|
||||
public static PdfColor FromHex(string hex)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(hex);
|
||||
var value = hex.TrimStart('#');
|
||||
if (value.Length != 6 || !int.TryParse(value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var rgb))
|
||||
{
|
||||
throw new FormatException("A colour is written #RRGGBB.");
|
||||
}
|
||||
|
||||
return new PdfColor((byte)(rgb >> 16), (byte)(rgb >> 8), (byte)rgb);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The document information dictionary.</summary>
|
||||
public sealed record PdfDocumentInfo
|
||||
{
|
||||
/// <summary>The title.</summary>
|
||||
public string? Title { get; init; }
|
||||
|
||||
/// <summary>The author (the company or the user).</summary>
|
||||
public string? Author { get; init; }
|
||||
|
||||
/// <summary>The subject.</summary>
|
||||
public string? Subject { get; init; }
|
||||
|
||||
/// <summary>Keywords.</summary>
|
||||
public string? Keywords { get; init; }
|
||||
|
||||
/// <summary>The program that created the content.</summary>
|
||||
public string Creator { get; init; } = "Khaemhat";
|
||||
|
||||
/// <summary>When the document was created; now when omitted.</summary>
|
||||
public DateTimeOffset? CreationDate { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>What the header of a JPEG file says.</summary>
|
||||
/// <param name="Width">Width in pixels.</param>
|
||||
/// <param name="Height">Height in pixels.</param>
|
||||
/// <param name="Components">1 (grey), 3 (RGB/YCbCr) or 4 (CMYK).</param>
|
||||
/// <param name="BitsPerComponent">Bits per component, normally 8.</param>
|
||||
/// <param name="AdobeInverted">An Adobe CMYK JPEG, whose components are stored inverted.</param>
|
||||
public sealed record JpegInfo(int Width, int Height, int Components, int BitsPerComponent, bool AdobeInverted)
|
||||
{
|
||||
/// <summary>
|
||||
/// Reads the size and components from the start-of-frame marker of a JPEG file, walking the marker segments from
|
||||
/// the start-of-image marker.
|
||||
/// </summary>
|
||||
/// <param name="jpeg">The file.</param>
|
||||
/// <returns>The header.</returns>
|
||||
/// <exception cref="InvalidDataException">The data is not a JPEG file the PDF can embed.</exception>
|
||||
public static JpegInfo Read(ReadOnlySpan<byte> jpeg)
|
||||
{
|
||||
if (jpeg.Length < 4 || jpeg[0] != 0xFF || jpeg[1] != 0xD8)
|
||||
{
|
||||
throw new InvalidDataException("Not a JPEG file (no SOI marker).");
|
||||
}
|
||||
|
||||
var adobe = false;
|
||||
var i = 2;
|
||||
while (i < jpeg.Length)
|
||||
{
|
||||
if (jpeg[i] != 0xFF)
|
||||
{
|
||||
throw new InvalidDataException("Corrupt JPEG file (marker expected).");
|
||||
}
|
||||
|
||||
while (i < jpeg.Length && jpeg[i] == 0xFF)
|
||||
{
|
||||
i++;
|
||||
}
|
||||
|
||||
if (i >= jpeg.Length)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
var marker = jpeg[i++];
|
||||
if (marker is 0x01 or 0xD8 or (>= 0xD0 and <= 0xD7))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (marker is 0xD9 or 0xDA)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (i + 2 > jpeg.Length)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
var length = (jpeg[i] << 8) | jpeg[i + 1];
|
||||
if (length < 2 || i + length > jpeg.Length)
|
||||
{
|
||||
throw new InvalidDataException("Corrupt JPEG file (segment length).");
|
||||
}
|
||||
|
||||
if (marker is >= 0xC0 and <= 0xCF and not 0xC4 and not 0xC8 and not 0xCC)
|
||||
{
|
||||
if (length < 8)
|
||||
{
|
||||
throw new InvalidDataException("Corrupt JPEG file (frame header).");
|
||||
}
|
||||
|
||||
var bits = jpeg[i + 2];
|
||||
var height = (jpeg[i + 3] << 8) | jpeg[i + 4];
|
||||
var width = (jpeg[i + 5] << 8) | jpeg[i + 6];
|
||||
var components = jpeg[i + 7];
|
||||
if (width == 0 || height == 0 || components is not (1 or 3 or 4))
|
||||
{
|
||||
throw new InvalidDataException("Unsupported JPEG file (size or components).");
|
||||
}
|
||||
|
||||
return new JpegInfo(width, height, components, bits, adobe && components == 4);
|
||||
}
|
||||
|
||||
if (marker == 0xEE && length >= 7 && jpeg.Slice(i + 2, 5).SequenceEqual("Adobe"u8))
|
||||
{
|
||||
adobe = true;
|
||||
}
|
||||
|
||||
i += length;
|
||||
}
|
||||
|
||||
throw new InvalidDataException("Not a JPEG file the PDF can embed (no frame header).");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>An image added to a document; draw it on any page with <see cref="PdfPage.DrawImage"/>.</summary>
|
||||
public sealed class PdfImage
|
||||
{
|
||||
internal PdfImage(int objectNumber, string name, JpegInfo info)
|
||||
{
|
||||
ObjectNumber = objectNumber;
|
||||
Name = name;
|
||||
Info = info;
|
||||
}
|
||||
|
||||
/// <summary>Width in pixels.</summary>
|
||||
public int Width => Info.Width;
|
||||
|
||||
/// <summary>Height in pixels.</summary>
|
||||
public int Height => Info.Height;
|
||||
|
||||
/// <summary>The JPEG header.</summary>
|
||||
public JpegInfo Info { get; }
|
||||
|
||||
internal int ObjectNumber { get; }
|
||||
|
||||
internal string Name { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A page being drawn. Coordinates are PDF points (1/72 inch) from the <b>bottom-left</b> corner; text is placed by
|
||||
/// its baseline. Use <see cref="PdfTextLayout"/> to measure and wrap text.
|
||||
/// </summary>
|
||||
public sealed class PdfPage
|
||||
{
|
||||
private readonly StringBuilder _content = new();
|
||||
|
||||
internal PdfPage(int number, double width, double height)
|
||||
{
|
||||
Number = number;
|
||||
Width = width;
|
||||
Height = height;
|
||||
}
|
||||
|
||||
/// <summary>The page number, from 1.</summary>
|
||||
public int Number { get; }
|
||||
|
||||
/// <summary>The width in points.</summary>
|
||||
public double Width { get; }
|
||||
|
||||
/// <summary>The height in points.</summary>
|
||||
public double Height { get; }
|
||||
|
||||
internal SortedSet<PdfFont> Fonts { get; } = [];
|
||||
|
||||
internal SortedDictionary<string, int> Images { get; } = new(StringComparer.Ordinal);
|
||||
|
||||
internal bool IsClosed { get; set; }
|
||||
|
||||
/// <summary>Writes a line of text.</summary>
|
||||
/// <param name="text">The text (one line; see <see cref="PdfTextLayout.Wrap"/>).</param>
|
||||
/// <param name="x">The left edge.</param>
|
||||
/// <param name="y">The baseline.</param>
|
||||
/// <param name="font">The font.</param>
|
||||
/// <param name="size">The size in points.</param>
|
||||
/// <param name="color">The colour; black when omitted.</param>
|
||||
public void DrawText(string? text, double x, double y, PdfFont font, double size, PdfColor? color = null)
|
||||
{
|
||||
Check();
|
||||
var bytes = PdfTextLayout.EncodeWinAnsi(text);
|
||||
if (bytes.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Fonts.Add(font);
|
||||
var c = color ?? PdfColor.Black;
|
||||
_content.Append("q ").Append(Color(c)).Append(" rg BT /").Append(PdfWriter.FontResource(font)).Append(' ').Append(Num(size))
|
||||
.Append(" Tf 1 0 0 1 ").Append(Num(x)).Append(' ').Append(Num(y)).Append(" Tm (");
|
||||
foreach (var b in bytes)
|
||||
{
|
||||
switch (b)
|
||||
{
|
||||
case (byte)'(' or (byte)')' or (byte)'\\':
|
||||
_content.Append('\\').Append((char)b);
|
||||
break;
|
||||
case < 0x20 or >= 0x7F:
|
||||
_content.Append('\\').Append(Convert.ToString(b, 8).PadLeft(3, '0'));
|
||||
break;
|
||||
default:
|
||||
_content.Append((char)b);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
_content.Append(") Tj ET Q\n");
|
||||
}
|
||||
|
||||
/// <summary>Writes a line of text ending at <paramref name="right"/> (amounts in a column).</summary>
|
||||
/// <param name="text">The text.</param>
|
||||
/// <param name="right">The right edge.</param>
|
||||
/// <param name="y">The baseline.</param>
|
||||
/// <param name="font">The font.</param>
|
||||
/// <param name="size">The size.</param>
|
||||
/// <param name="color">The colour.</param>
|
||||
public void DrawTextRight(string? text, double right, double y, PdfFont font, double size, PdfColor? color = null) =>
|
||||
DrawText(text, right - PdfTextLayout.Measure(text, font, size), y, font, size, color);
|
||||
|
||||
/// <summary>Writes a line of text centred on <paramref name="center"/>.</summary>
|
||||
/// <param name="text">The text.</param>
|
||||
/// <param name="center">The centre.</param>
|
||||
/// <param name="y">The baseline.</param>
|
||||
/// <param name="font">The font.</param>
|
||||
/// <param name="size">The size.</param>
|
||||
/// <param name="color">The colour.</param>
|
||||
public void DrawTextCentered(string? text, double center, double y, PdfFont font, double size, PdfColor? color = null) =>
|
||||
DrawText(text, center - (PdfTextLayout.Measure(text, font, size) / 2), y, font, size, color);
|
||||
|
||||
/// <summary>Writes a paragraph wrapped to a width, from a first baseline downwards.</summary>
|
||||
/// <param name="text">The text.</param>
|
||||
/// <param name="x">The left edge.</param>
|
||||
/// <param name="y">The first baseline.</param>
|
||||
/// <param name="width">The width.</param>
|
||||
/// <param name="font">The font.</param>
|
||||
/// <param name="size">The size.</param>
|
||||
/// <param name="lineHeight">The distance between baselines; 1.2 times the size when omitted.</param>
|
||||
/// <param name="color">The colour.</param>
|
||||
/// <returns>The baseline after the last line.</returns>
|
||||
public double DrawParagraph(string? text, double x, double y, double width, PdfFont font, double size, double? lineHeight = null, PdfColor? color = null)
|
||||
{
|
||||
var step = lineHeight ?? size * 1.2;
|
||||
foreach (var line in PdfTextLayout.Wrap(text, font, size, width))
|
||||
{
|
||||
DrawText(line, x, y, font, size, color);
|
||||
y -= step;
|
||||
}
|
||||
|
||||
return y;
|
||||
}
|
||||
|
||||
/// <summary>Draws a line.</summary>
|
||||
/// <param name="x1">Start x.</param>
|
||||
/// <param name="y1">Start y.</param>
|
||||
/// <param name="x2">End x.</param>
|
||||
/// <param name="y2">End y.</param>
|
||||
/// <param name="lineWidth">The width in points.</param>
|
||||
/// <param name="color">The colour; black when omitted.</param>
|
||||
public void DrawLine(double x1, double y1, double x2, double y2, double lineWidth = 0.5, PdfColor? color = null)
|
||||
{
|
||||
Check();
|
||||
_content.Append("q ").Append(Num(lineWidth)).Append(" w ").Append(Color(color ?? PdfColor.Black)).Append(" RG ")
|
||||
.Append(Num(x1)).Append(' ').Append(Num(y1)).Append(" m ").Append(Num(x2)).Append(' ').Append(Num(y2)).Append(" l S Q\n");
|
||||
}
|
||||
|
||||
/// <summary>Draws a rectangle, filled and/or outlined.</summary>
|
||||
/// <param name="x">The left edge.</param>
|
||||
/// <param name="y">The bottom edge.</param>
|
||||
/// <param name="width">The width.</param>
|
||||
/// <param name="height">The height.</param>
|
||||
/// <param name="stroke">The outline colour, or <see langword="null"/> for none.</param>
|
||||
/// <param name="fill">The fill colour, or <see langword="null"/> for none.</param>
|
||||
/// <param name="lineWidth">The outline width.</param>
|
||||
public void DrawRectangle(double x, double y, double width, double height, PdfColor? stroke = null, PdfColor? fill = null, double lineWidth = 0.5)
|
||||
{
|
||||
Check();
|
||||
if (stroke is null && fill is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_content.Append("q ");
|
||||
if (stroke is { } s)
|
||||
{
|
||||
_content.Append(Num(lineWidth)).Append(" w ").Append(Color(s)).Append(" RG ");
|
||||
}
|
||||
|
||||
if (fill is { } f)
|
||||
{
|
||||
_content.Append(Color(f)).Append(" rg ");
|
||||
}
|
||||
|
||||
var paint = (stroke, fill) switch
|
||||
{
|
||||
(not null, not null) => "B",
|
||||
(not null, null) => "S",
|
||||
_ => "f",
|
||||
};
|
||||
_content.Append(Num(x)).Append(' ').Append(Num(y)).Append(' ').Append(Num(width)).Append(' ').Append(Num(height)).Append(" re ").Append(paint).Append(" Q\n");
|
||||
}
|
||||
|
||||
/// <summary>Draws an image scaled to a box.</summary>
|
||||
/// <param name="image">The image, from <see cref="PdfWriter.AddJpeg"/>.</param>
|
||||
/// <param name="x">The left edge.</param>
|
||||
/// <param name="y">The bottom edge.</param>
|
||||
/// <param name="width">The width.</param>
|
||||
/// <param name="height">The height.</param>
|
||||
public void DrawImage(PdfImage image, double x, double y, double width, double height)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(image);
|
||||
Check();
|
||||
Images[image.Name] = image.ObjectNumber;
|
||||
_content.Append("q ").Append(Num(width)).Append(" 0 0 ").Append(Num(height)).Append(' ').Append(Num(x)).Append(' ').Append(Num(y))
|
||||
.Append(" cm /").Append(image.Name).Append(" Do Q\n");
|
||||
}
|
||||
|
||||
internal byte[] ContentBytes() => Encoding.ASCII.GetBytes(_content.ToString());
|
||||
|
||||
internal static string Num(double value)
|
||||
{
|
||||
if (!double.IsFinite(value))
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(value), value, "Coordinates must be finite numbers.");
|
||||
}
|
||||
|
||||
var text = Math.Round(value, 3).ToString("0.###", CultureInfo.InvariantCulture);
|
||||
return text == "-0" ? "0" : text;
|
||||
}
|
||||
|
||||
private static string Color(PdfColor c) => Num(c.R / 255.0) + " " + Num(c.G / 255.0) + " " + Num(c.B / 255.0);
|
||||
|
||||
private void Check()
|
||||
{
|
||||
if (IsClosed)
|
||||
{
|
||||
throw new InvalidOperationException($"Page {Number} is finished: draw on the current page.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes PDF 1.7 documents (SPEC §2 "PDF e file"), written in house: the 12 standard Latin Type1 fonts with
|
||||
/// <c>WinAnsiEncoding</c>, text, lines, rectangles, RGB colours, JPEG images, several pages, the information
|
||||
/// dictionary, Flate-compressed content streams and a correct cross-reference table. Pages are written to the
|
||||
/// output as soon as the next page starts, so long documents do not stay in memory; only asynchronous writes reach
|
||||
/// the output, which can therefore be an HTTP response.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// TODO (FatturaPA courtesy copies, SPEC §2): PDF/A-3 with embedded XML attachments (<c>PdfA3Embedder</c>) needs
|
||||
/// embedded fonts, an XMP metadata stream and an output intent; this first version does not produce PDF/A.
|
||||
/// </remarks>
|
||||
/// <example>
|
||||
/// <code>
|
||||
/// await using var pdf = new PdfWriter(stream, new PdfDocumentInfo { Title = "Prova" });
|
||||
/// var page = await pdf.AddPageAsync();
|
||||
/// page.DrawText("Totale € 1.234,50", 40, page.Height - 60, PdfFont.HelveticaBold, 14);
|
||||
/// await pdf.CloseAsync();
|
||||
/// </code>
|
||||
/// </example>
|
||||
public sealed class PdfWriter : IAsyncDisposable
|
||||
{
|
||||
/// <summary>The media type of a PDF file.</summary>
|
||||
public const string MediaType = "application/pdf";
|
||||
|
||||
/// <summary>The width of an A4 page in points.</summary>
|
||||
public const double A4Width = 595.28;
|
||||
|
||||
/// <summary>The height of an A4 page in points.</summary>
|
||||
public const double A4Height = 841.89;
|
||||
|
||||
private const int CatalogObject = 1;
|
||||
private const int PagesObject = 2;
|
||||
private const int InfoObject = 3;
|
||||
|
||||
private readonly Stream _output;
|
||||
private readonly bool _leaveOpen;
|
||||
private readonly PdfDocumentInfo _info;
|
||||
private readonly MemoryStream _buffer = new();
|
||||
private readonly List<long> _offsets = [0, -1, -1, -1];
|
||||
private readonly List<int> _pageObjects = [];
|
||||
private readonly Dictionary<PdfFont, int> _fontObjects = [];
|
||||
private long _flushed;
|
||||
private int _images;
|
||||
private PdfPage? _page;
|
||||
private bool _closed;
|
||||
|
||||
/// <summary>Starts a document.</summary>
|
||||
/// <param name="output">The stream that receives the file; it need not be seekable.</param>
|
||||
/// <param name="info">The document information; <see langword="null"/> for none but the creator.</param>
|
||||
/// <param name="leaveOpen">Whether to leave <paramref name="output"/> open on dispose.</param>
|
||||
public PdfWriter(Stream output, PdfDocumentInfo? info = null, bool leaveOpen = false)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(output);
|
||||
_output = output;
|
||||
_leaveOpen = leaveOpen;
|
||||
_info = info ?? new PdfDocumentInfo();
|
||||
Ascii("%PDF-1.7\n%");
|
||||
_buffer.Write([0xE2, 0xE3, 0xCF, 0xD3, (byte)'\n']);
|
||||
}
|
||||
|
||||
/// <summary>Whether content streams are Flate-compressed (turn it off only to inspect the output).</summary>
|
||||
public bool CompressContent { get; init; } = true;
|
||||
|
||||
/// <summary>The number of pages started.</summary>
|
||||
public int PageCount => _pageObjects.Count + (_page is null ? 0 : 1);
|
||||
|
||||
/// <summary>The current page, or <see langword="null"/> before the first.</summary>
|
||||
public PdfPage? CurrentPage => _page;
|
||||
|
||||
/// <summary>Finishes the current page (writing it to the output) and starts a new one.</summary>
|
||||
/// <param name="width">The width in points; A4 when omitted.</param>
|
||||
/// <param name="height">The height in points; A4 when omitted.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The new page.</returns>
|
||||
public async Task<PdfPage> AddPageAsync(double width = A4Width, double height = A4Height, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_closed, this);
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width);
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height);
|
||||
FinishPage();
|
||||
await FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
_page = new PdfPage(_pageObjects.Count + 1, width, height);
|
||||
return _page;
|
||||
}
|
||||
|
||||
/// <summary>Adds a JPEG image to the document (embedded as is, <c>DCTDecode</c>).</summary>
|
||||
/// <param name="jpeg">The JPEG file.</param>
|
||||
/// <returns>The image, to draw on any page.</returns>
|
||||
/// <exception cref="InvalidDataException">The data is not a JPEG file the PDF can embed.</exception>
|
||||
public PdfImage AddJpeg(ReadOnlySpan<byte> jpeg)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_closed, this);
|
||||
var info = JpegInfo.Read(jpeg);
|
||||
var number = Allocate();
|
||||
var colorSpace = info.Components switch { 1 => "/DeviceGray", 4 => "/DeviceCMYK", _ => "/DeviceRGB" };
|
||||
var decode = info.AdobeInverted ? " /Decode [1 0 1 0 1 0 1 0]" : string.Empty;
|
||||
BeginObject(number);
|
||||
Ascii(string.Create(
|
||||
CultureInfo.InvariantCulture,
|
||||
$"<< /Type /XObject /Subtype /Image /Width {info.Width} /Height {info.Height} /ColorSpace {colorSpace} /BitsPerComponent {info.BitsPerComponent}{decode} /Filter /DCTDecode /Length {jpeg.Length} >>\nstream\n"));
|
||||
_buffer.Write(jpeg);
|
||||
Ascii("\nendstream\nendobj\n");
|
||||
_images++;
|
||||
return new PdfImage(number, "Im" + _images.ToString(CultureInfo.InvariantCulture), info);
|
||||
}
|
||||
|
||||
/// <summary>Writes what is buffered to the output.</summary>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task FlushAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (_buffer.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await _output.WriteAsync(_buffer.GetBuffer().AsMemory(0, (int)_buffer.Length), cancellationToken).ConfigureAwait(false);
|
||||
_flushed += _buffer.Length;
|
||||
_buffer.SetLength(0);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finishes the document: the last page, fonts, page tree, catalogue, information, cross-reference table and
|
||||
/// trailer. A document without pages gets one blank page.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task CloseAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (_closed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_page is null && _pageObjects.Count == 0)
|
||||
{
|
||||
_page = new PdfPage(1, A4Width, A4Height);
|
||||
}
|
||||
|
||||
FinishPage();
|
||||
foreach (var (font, number) in _fontObjects.OrderBy(f => f.Value))
|
||||
{
|
||||
BeginObject(number);
|
||||
Ascii($"<< /Type /Font /Subtype /Type1 /BaseFont /{PdfTextLayout.BaseFontName(font)} /Encoding /WinAnsiEncoding >>\nendobj\n");
|
||||
}
|
||||
|
||||
BeginObject(PagesObject);
|
||||
Ascii("<< /Type /Pages /Kids [" + string.Join(' ', _pageObjects.Select(p => Ref(p))) + "] /Count "
|
||||
+ _pageObjects.Count.ToString(CultureInfo.InvariantCulture) + " >>\nendobj\n");
|
||||
BeginObject(CatalogObject);
|
||||
Ascii("<< /Type /Catalog /Pages " + Ref(PagesObject) + " >>\nendobj\n");
|
||||
BeginObject(InfoObject);
|
||||
Ascii("<< " + InfoEntries() + ">>\nendobj\n");
|
||||
|
||||
var xref = Position;
|
||||
var size = _offsets.Count.ToString(CultureInfo.InvariantCulture);
|
||||
var table = new StringBuilder();
|
||||
table.Append("xref\n0 ").Append(size).Append('\n').Append("0000000000 65535 f\r\n");
|
||||
for (var i = 1; i < _offsets.Count; i++)
|
||||
{
|
||||
if (_offsets[i] < 0)
|
||||
{
|
||||
throw new InvalidOperationException($"Object {i} was allocated but never written.");
|
||||
}
|
||||
|
||||
table.Append(_offsets[i].ToString("D10", CultureInfo.InvariantCulture)).Append(" 00000 n\r\n");
|
||||
}
|
||||
|
||||
var id = Convert.ToHexString(Guid.NewGuid().ToByteArray());
|
||||
table.Append("trailer\n<< /Size ").Append(size).Append(" /Root ").Append(Ref(CatalogObject)).Append(" /Info ").Append(Ref(InfoObject))
|
||||
.Append(" /ID [<").Append(id).Append("> <").Append(id).Append(">] >>\nstartxref\n")
|
||||
.Append(xref.ToString(CultureInfo.InvariantCulture)).Append("\n%%EOF\n");
|
||||
Ascii(table.ToString());
|
||||
_closed = true;
|
||||
await FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
await _output.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (!_leaveOpen)
|
||||
{
|
||||
await _output.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Closes the document if it is still open.</summary>
|
||||
/// <returns>A task.</returns>
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await CloseAsync().ConfigureAwait(false);
|
||||
await _buffer.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal static string FontResource(PdfFont font) => "F" + ((int)font + 1).ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
private long Position => _flushed + _buffer.Length;
|
||||
|
||||
private static string Ref(int number) => number.ToString(CultureInfo.InvariantCulture) + " 0 R";
|
||||
|
||||
private static string PdfDate(DateTimeOffset value) =>
|
||||
"D:" + value.UtcDateTime.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture) + "Z";
|
||||
|
||||
/// <summary>A text string: ASCII as a literal, anything else as UTF-16BE with byte order mark.</summary>
|
||||
private static string TextString(string value)
|
||||
{
|
||||
if (value.All(c => c is >= ' ' and <= '~'))
|
||||
{
|
||||
return "(" + value.Replace("\\", "\\\\", StringComparison.Ordinal).Replace("(", "\\(", StringComparison.Ordinal).Replace(")", "\\)", StringComparison.Ordinal) + ")";
|
||||
}
|
||||
|
||||
return "<FEFF" + Convert.ToHexString(Encoding.BigEndianUnicode.GetBytes(value)) + ">";
|
||||
}
|
||||
|
||||
private string InfoEntries()
|
||||
{
|
||||
var entries = new StringBuilder();
|
||||
void Add(string key, string? value)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(value))
|
||||
{
|
||||
entries.Append('/').Append(key).Append(' ').Append(TextString(value)).Append(' ');
|
||||
}
|
||||
}
|
||||
|
||||
Add("Title", _info.Title);
|
||||
Add("Author", _info.Author);
|
||||
Add("Subject", _info.Subject);
|
||||
Add("Keywords", _info.Keywords);
|
||||
Add("Creator", _info.Creator);
|
||||
Add("Producer", "Khaemhat PdfWriter");
|
||||
var created = PdfDate(_info.CreationDate ?? DateTimeOffset.UtcNow);
|
||||
entries.Append("/CreationDate (").Append(created).Append(") /ModDate (").Append(created).Append(") ");
|
||||
return entries.ToString();
|
||||
}
|
||||
|
||||
private int Allocate()
|
||||
{
|
||||
_offsets.Add(-1);
|
||||
return _offsets.Count - 1;
|
||||
}
|
||||
|
||||
private void BeginObject(int number)
|
||||
{
|
||||
_offsets[number] = Position;
|
||||
Ascii(number.ToString(CultureInfo.InvariantCulture) + " 0 obj\n");
|
||||
}
|
||||
|
||||
private void Ascii(string text) => _buffer.Write(Encoding.ASCII.GetBytes(text));
|
||||
|
||||
private void FinishPage()
|
||||
{
|
||||
if (_page is not { } page)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
page.IsClosed = true;
|
||||
_page = null;
|
||||
|
||||
var content = page.ContentBytes();
|
||||
var filter = string.Empty;
|
||||
if (CompressContent)
|
||||
{
|
||||
using var compressed = new MemoryStream();
|
||||
using (var zlib = new ZLibStream(compressed, CompressionLevel.Optimal, leaveOpen: true))
|
||||
{
|
||||
zlib.Write(content);
|
||||
}
|
||||
|
||||
content = compressed.ToArray();
|
||||
filter = " /Filter /FlateDecode";
|
||||
}
|
||||
|
||||
var contentObject = Allocate();
|
||||
BeginObject(contentObject);
|
||||
Ascii("<< /Length " + content.Length.ToString(CultureInfo.InvariantCulture) + filter + " >>\nstream\n");
|
||||
_buffer.Write(content);
|
||||
Ascii("\nendstream\nendobj\n");
|
||||
|
||||
var fonts = new StringBuilder();
|
||||
foreach (var font in page.Fonts)
|
||||
{
|
||||
if (!_fontObjects.TryGetValue(font, out var number))
|
||||
{
|
||||
number = Allocate();
|
||||
_fontObjects[font] = number;
|
||||
}
|
||||
|
||||
fonts.Append('/').Append(FontResource(font)).Append(' ').Append(Ref(number)).Append(' ');
|
||||
}
|
||||
|
||||
var images = string.Concat(page.Images.Select(i => "/" + i.Key + " " + Ref(i.Value) + " "));
|
||||
var resources = "/ProcSet [/PDF /Text /ImageB /ImageC]"
|
||||
+ (fonts.Length > 0 ? " /Font << " + fonts + ">>" : string.Empty)
|
||||
+ (images.Length > 0 ? " /XObject << " + images + ">>" : string.Empty);
|
||||
|
||||
var pageObject = Allocate();
|
||||
BeginObject(pageObject);
|
||||
Ascii("<< /Type /Page /Parent " + Ref(PagesObject) + " /MediaBox [0 0 " + PdfPage.Num(page.Width) + " " + PdfPage.Num(page.Height)
|
||||
+ "] /Resources << " + resources + " >> /Contents " + Ref(contentObject) + " >>\nendobj\n");
|
||||
_pageObjects.Add(pageObject);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.RegularExpressions;
|
||||
using Khaemhat.Core.Files;
|
||||
using Khaemhat.Data;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Files;
|
||||
|
||||
/// <summary>Where the store keeps files and the default limits.</summary>
|
||||
/// <param name="RootDirectory">The root folder, <c><KHAEMHAT_DATA_DIR>/files</c>.</param>
|
||||
public sealed record FileStoreOptions(string RootDirectory)
|
||||
{
|
||||
/// <summary>The largest file accepted when the caller gives no limit (25 MB).</summary>
|
||||
public long MaxFileBytes { get; init; } = FileLimits.DefaultMaxBytes;
|
||||
|
||||
/// <summary>The space each company may use when the caller gives no quota; 0 means no quota.</summary>
|
||||
public long CompanyQuotaBytes { get; init; }
|
||||
|
||||
/// <summary>The options for a data folder: files in <c><dataDir>/files</c>.</summary>
|
||||
/// <param name="dataDirectory">The value of <c>KHAEMHAT_DATA_DIR</c>.</param>
|
||||
/// <returns>The options.</returns>
|
||||
public static FileStoreOptions ForDataDirectory(string dataDirectory)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(dataDirectory);
|
||||
return new FileStoreOptions(Path.Combine(dataDirectory, "files"));
|
||||
}
|
||||
|
||||
/// <summary>The limits used when the caller gives none.</summary>
|
||||
public FileLimits DefaultLimits => new(MaxFileBytes, CompanyQuotaBytes);
|
||||
}
|
||||
|
||||
/// <summary>The scanner used when no antivirus is plugged in: every file is accepted.</summary>
|
||||
public sealed class NoOpFileScanner : IFileScanner
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public ValueTask<FileScanResult> ScanAsync(string companyCode, Stream content, CancellationToken cancellationToken = default) =>
|
||||
ValueTask.FromResult(FileScanResult.Ok);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The file store on the data volume (SPEC §9.4): <c><root>/<COMPANY>/<yyyy>/<guid></c>. A file is
|
||||
/// written to <c><guid>.part</c> in the same folder while its size is checked and its SHA-256 computed, then
|
||||
/// renamed: nothing is ever written outside the data folder and a partial file never appears under a key.
|
||||
/// </summary>
|
||||
public sealed partial class VolumeFileStore : IFileStore
|
||||
{
|
||||
private const string PartExtension = ".part";
|
||||
private const int BufferSize = 81920;
|
||||
|
||||
private readonly FileStoreOptions _options;
|
||||
private readonly IFileScanner _scanner;
|
||||
private readonly TimeProvider _clock;
|
||||
|
||||
/// <summary>Creates the store.</summary>
|
||||
/// <param name="options">The root folder and the default limits.</param>
|
||||
/// <param name="scanner">The antivirus hook.</param>
|
||||
/// <param name="clock">The clock (the year folder).</param>
|
||||
public VolumeFileStore(FileStoreOptions options, IFileScanner scanner, TimeProvider clock)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
ArgumentNullException.ThrowIfNull(scanner);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
if (!Path.IsPathFullyQualified(options.RootDirectory))
|
||||
{
|
||||
throw new ArgumentException("The root of the file store must be an absolute path.", nameof(options));
|
||||
}
|
||||
|
||||
_options = options;
|
||||
_scanner = scanner;
|
||||
_clock = clock;
|
||||
}
|
||||
|
||||
/// <summary>The root folder.</summary>
|
||||
public string RootDirectory => _options.RootDirectory;
|
||||
|
||||
/// <summary>Whether a key has the form the store produces (<c>yyyy/guid</c>).</summary>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <returns><see langword="true"/> if valid.</returns>
|
||||
public static bool IsValidKey(string? key) => key is not null && KeyPattern().IsMatch(key);
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<StoredFile> SaveAsync(string companyCode, Stream content, FileLimits? limits = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(content);
|
||||
await using var writer = await CreateAsync(companyCode, limits, cancellationToken).ConfigureAwait(false);
|
||||
await content.CopyToAsync(writer.Content, BufferSize, cancellationToken).ConfigureAwait(false);
|
||||
return await writer.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<IFileStoreWriter> CreateAsync(string companyCode, FileLimits? limits = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var company = CompanyFolder(companyCode);
|
||||
var year = _clock.GetUtcNow().Year.ToString("D4", CultureInfo.InvariantCulture);
|
||||
var folder = Path.Combine(company, year);
|
||||
Directory.CreateDirectory(folder);
|
||||
var name = Guid.NewGuid().ToString("N");
|
||||
var writer = new Writer(this, CompanyCodes.Normalize(companyCode), year + "/" + name, Path.Combine(folder, name), limits ?? _options.DefaultLimits);
|
||||
return Task.FromResult<IFileStoreWriter>(writer);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Stream OpenRead(string companyCode, string key)
|
||||
{
|
||||
var path = PathOf(companyCode, key);
|
||||
try
|
||||
{
|
||||
return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, BufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan);
|
||||
}
|
||||
catch (Exception ex) when (ex is FileNotFoundException or DirectoryNotFoundException)
|
||||
{
|
||||
throw new FileStoreException(FileStoreException.NotFound, $"The file {key} does not exist in the store of {companyCode}.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool Exists(string companyCode, string key) => File.Exists(PathOf(companyCode, key));
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool Delete(string companyCode, string key)
|
||||
{
|
||||
var path = PathOf(companyCode, key);
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
File.Delete(path);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<FileUsage> GetUsageAsync(string companyCode, long? quotaBytes = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var quota = quotaBytes ?? _options.CompanyQuotaBytes;
|
||||
var folder = CompanyFolder(companyCode);
|
||||
long files = 0, bytes = 0;
|
||||
if (Directory.Exists(folder))
|
||||
{
|
||||
foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", SearchOption.AllDirectories))
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (!file.Name.EndsWith(PartExtension, StringComparison.Ordinal))
|
||||
{
|
||||
files++;
|
||||
bytes += file.Length;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Task.FromResult(new FileUsage(files, bytes, quota));
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public int DeleteAbandonedParts(string companyCode, TimeSpan olderThan)
|
||||
{
|
||||
var folder = CompanyFolder(companyCode);
|
||||
if (!Directory.Exists(folder))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var limit = _clock.GetUtcNow().UtcDateTime - olderThan;
|
||||
var deleted = 0;
|
||||
foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*" + PartExtension, SearchOption.AllDirectories))
|
||||
{
|
||||
if (file.LastWriteTimeUtc < limit)
|
||||
{
|
||||
try
|
||||
{
|
||||
file.Delete();
|
||||
deleted++;
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// Still being written by another process: it will be removed next time.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return deleted;
|
||||
}
|
||||
|
||||
private string CompanyFolder(string companyCode) => Path.Combine(_options.RootDirectory, CompanyCodes.Normalize(companyCode));
|
||||
|
||||
private string PathOf(string companyCode, string key)
|
||||
{
|
||||
if (!IsValidKey(key))
|
||||
{
|
||||
throw new ArgumentException("Not a key of the file store.", nameof(key));
|
||||
}
|
||||
|
||||
return Path.Combine(CompanyFolder(companyCode), key.Replace('/', Path.DirectorySeparatorChar));
|
||||
}
|
||||
|
||||
[GeneratedRegex("^[0-9]{4}/[0-9a-f]{32}$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex KeyPattern();
|
||||
|
||||
/// <summary>A file being written: the <c>.part</c> file and the counting stream over it.</summary>
|
||||
private sealed class Writer : IFileStoreWriter
|
||||
{
|
||||
private readonly VolumeFileStore _store;
|
||||
private readonly string _company;
|
||||
private readonly string _key;
|
||||
private readonly string _finalPath;
|
||||
private readonly string _partPath;
|
||||
private readonly FileLimits _limits;
|
||||
private readonly FileStream _file;
|
||||
private readonly HashingStream _content;
|
||||
private bool _committed;
|
||||
private bool _disposed;
|
||||
|
||||
public Writer(VolumeFileStore store, string company, string key, string finalPath, FileLimits limits)
|
||||
{
|
||||
_store = store;
|
||||
_company = company;
|
||||
_key = key;
|
||||
_finalPath = finalPath;
|
||||
_partPath = finalPath + PartExtension;
|
||||
_limits = limits;
|
||||
_file = new FileStream(_partPath, FileMode.CreateNew, FileAccess.Write, FileShare.Read, BufferSize, FileOptions.Asynchronous);
|
||||
_content = new HashingStream(_file, limits.MaxBytes);
|
||||
}
|
||||
|
||||
public Stream Content => _content;
|
||||
|
||||
public async Task<StoredFile> CommitAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
if (_committed)
|
||||
{
|
||||
throw new InvalidOperationException("The file is already committed.");
|
||||
}
|
||||
|
||||
await _file.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
var size = _content.Length;
|
||||
if (_limits.QuotaBytes > 0)
|
||||
{
|
||||
var usage = await _store.GetUsageAsync(_company, _limits.QuotaBytes, cancellationToken).ConfigureAwait(false);
|
||||
if (usage.Bytes + size > _limits.QuotaBytes)
|
||||
{
|
||||
throw new FileStoreException(FileStoreException.QuotaExceeded, $"The company {_company} has no space left for {size} bytes.");
|
||||
}
|
||||
}
|
||||
|
||||
await using (var scan = new FileStream(_partPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, BufferSize, FileOptions.Asynchronous))
|
||||
{
|
||||
var verdict = await _store._scanner.ScanAsync(_company, scan, cancellationToken).ConfigureAwait(false);
|
||||
if (!verdict.Clean)
|
||||
{
|
||||
throw new FileStoreException(FileStoreException.Rejected, "The file was rejected by the scanner: " + (verdict.Reason ?? "no reason given") + ".");
|
||||
}
|
||||
}
|
||||
|
||||
var hash = _content.HashHex();
|
||||
await _file.DisposeAsync().ConfigureAwait(false);
|
||||
File.Move(_partPath, _finalPath);
|
||||
_committed = true;
|
||||
return new StoredFile(_key, size, hash);
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
_content.ReleaseHash();
|
||||
await _file.DisposeAsync().ConfigureAwait(false);
|
||||
if (!_committed && File.Exists(_partPath))
|
||||
{
|
||||
File.Delete(_partPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A write-only stream that enforces the size limit and computes SHA-256 on the way.</summary>
|
||||
private sealed class HashingStream(Stream inner, long maxBytes) : Stream
|
||||
{
|
||||
private readonly IncrementalHash _hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
||||
private long _length;
|
||||
|
||||
public override bool CanRead => false;
|
||||
|
||||
public override bool CanSeek => false;
|
||||
|
||||
public override bool CanWrite => true;
|
||||
|
||||
public override long Length => _length;
|
||||
|
||||
public override long Position
|
||||
{
|
||||
get => _length;
|
||||
set => throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public string HashHex() => Convert.ToHexStringLower(_hash.GetCurrentHash());
|
||||
|
||||
public void ReleaseHash() => _hash.Dispose();
|
||||
|
||||
public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count));
|
||||
|
||||
public override void Write(ReadOnlySpan<byte> buffer)
|
||||
{
|
||||
Account(buffer);
|
||||
inner.Write(buffer);
|
||||
}
|
||||
|
||||
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
|
||||
WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
|
||||
|
||||
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Account(buffer.Span);
|
||||
return inner.WriteAsync(buffer, cancellationToken);
|
||||
}
|
||||
|
||||
public override void Flush() => inner.Flush();
|
||||
|
||||
public override Task FlushAsync(CancellationToken cancellationToken) => inner.FlushAsync(cancellationToken);
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
|
||||
|
||||
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
|
||||
|
||||
public override void SetLength(long value) => throw new NotSupportedException();
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
// The writer owns the file stream and the hash.
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private void Account(ReadOnlySpan<byte> buffer)
|
||||
{
|
||||
if (maxBytes > 0 && _length + buffer.Length > maxBytes)
|
||||
{
|
||||
throw new FileStoreException(FileStoreException.TooLarge, $"The file is larger than {maxBytes} bytes.");
|
||||
}
|
||||
|
||||
_length += buffer.Length;
|
||||
_hash.AppendData(buffer);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,753 @@
|
||||
using System.Globalization;
|
||||
using System.IO.Compression;
|
||||
using System.Text;
|
||||
using System.Xml;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Files;
|
||||
|
||||
/// <summary>The number format of a spreadsheet column.</summary>
|
||||
public enum XlsxFormat
|
||||
{
|
||||
/// <summary>By value: dates get a date format, everything else the general one.</summary>
|
||||
General = 0,
|
||||
|
||||
/// <summary>Whole numbers with thousands separator (<c>#,##0</c>).</summary>
|
||||
WholeNumber = 1,
|
||||
|
||||
/// <summary>Two decimals with thousands separator (<c>#,##0.00</c>).</summary>
|
||||
TwoDecimals = 2,
|
||||
|
||||
/// <summary>Euro amounts (<c>#,##0.00 €</c>).</summary>
|
||||
Euro = 3,
|
||||
|
||||
/// <summary>Percentages with two decimals; the value 0.22 shows as 22,00%.</summary>
|
||||
Percent = 4,
|
||||
|
||||
/// <summary>Dates.</summary>
|
||||
Date = 5,
|
||||
|
||||
/// <summary>Dates with time.</summary>
|
||||
DateTime = 6,
|
||||
|
||||
/// <summary>Text: numbers typed later in the cell stay text.</summary>
|
||||
Text = 7,
|
||||
}
|
||||
|
||||
/// <summary>A column of a sheet.</summary>
|
||||
/// <param name="Header">The header, written in bold in the first row; <see langword="null"/> for no header.</param>
|
||||
/// <param name="Width">The width in characters; <see langword="null"/> for the spreadsheet default.</param>
|
||||
/// <param name="Format">The number format of the cells.</param>
|
||||
public sealed record XlsxColumn(string? Header, double? Width = null, XlsxFormat Format = XlsxFormat.General);
|
||||
|
||||
/// <summary>The options of an <see cref="XlsxWriter"/>.</summary>
|
||||
public sealed record XlsxOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Whether text goes to the shared strings table (smaller files with repeated text, but every distinct string is
|
||||
/// kept in memory until the end) instead of inline in each cell (the default, fully streaming).
|
||||
/// </summary>
|
||||
public bool UseSharedStrings { get; init; }
|
||||
|
||||
/// <summary>Whether the header row stays visible while scrolling.</summary>
|
||||
public bool FreezeHeaderRow { get; init; } = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes Office Open XML spreadsheets (<c>.xlsx</c>, SPEC §2, §9.4) with <see cref="ZipArchive"/> and
|
||||
/// <see cref="XmlWriter"/>, row by row, without holding the sheet in memory: text (inline or shared strings), numbers,
|
||||
/// dates as serial numbers with a date format, booleans, a bold header row, column widths and a frozen header.
|
||||
/// Only asynchronous writes reach the output, so it can be an HTTP response.
|
||||
/// </summary>
|
||||
/// <example>
|
||||
/// <code>
|
||||
/// await using var xlsx = await XlsxWriter.CreateAsync(stream);
|
||||
/// await xlsx.StartSheetAsync("Righe", [new("Codice", 12), new("Importo", 14, XlsxFormat.Euro)]);
|
||||
/// await xlsx.WriteRowAsync(["A1", 12.5m]);
|
||||
/// await xlsx.CompleteAsync();
|
||||
/// </code>
|
||||
/// </example>
|
||||
public sealed class XlsxWriter : IAsyncDisposable
|
||||
{
|
||||
/// <summary>The media type of an <c>.xlsx</c> file.</summary>
|
||||
public const string MediaType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
|
||||
|
||||
/// <summary>The longest sheet name Excel accepts.</summary>
|
||||
public const int MaxSheetNameLength = 31;
|
||||
|
||||
/// <summary>The longest text a cell holds.</summary>
|
||||
public const int MaxCellTextLength = 32767;
|
||||
|
||||
private const string MainNs = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
|
||||
private const string RelNs = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
|
||||
private const string PackageRelNs = "http://schemas.openxmlformats.org/package/2006/relationships";
|
||||
private const string ContentTypesNs = "http://schemas.openxmlformats.org/package/2006/content-types";
|
||||
private const string WorksheetType = "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml";
|
||||
|
||||
// Indexes in cellXfs of styles.xml.
|
||||
private const int StyleGeneral = 0;
|
||||
private const int StyleHeader = 1;
|
||||
private const int StyleDate = 2;
|
||||
private const int StyleDateTime = 3;
|
||||
private const int StyleInteger = 4;
|
||||
private const int StyleDecimal = 5;
|
||||
private const int StyleEuro = 6;
|
||||
private const int StylePercent = 7;
|
||||
private const int StyleText = 8;
|
||||
|
||||
private static readonly DateTime Epoch = new(1899, 12, 30, 0, 0, 0, DateTimeKind.Unspecified);
|
||||
|
||||
private readonly ZipArchive _archive;
|
||||
private readonly AsyncOutputBuffer _buffer;
|
||||
private readonly Stream _output;
|
||||
private readonly bool _leaveOpen;
|
||||
private readonly XlsxOptions _options;
|
||||
private readonly List<string> _sheetNames = [];
|
||||
private readonly Dictionary<string, int> _sharedIndex = new(StringComparer.Ordinal);
|
||||
private readonly List<string> _shared = [];
|
||||
private Stream? _sheetStream;
|
||||
private XmlWriter? _sheet;
|
||||
private IReadOnlyList<XlsxColumn> _columns = [];
|
||||
private int _row;
|
||||
private bool _completed;
|
||||
|
||||
private XlsxWriter(ZipArchive archive, AsyncOutputBuffer buffer, Stream output, bool leaveOpen, XlsxOptions options)
|
||||
{
|
||||
_archive = archive;
|
||||
_buffer = buffer;
|
||||
_output = output;
|
||||
_leaveOpen = leaveOpen;
|
||||
_options = options;
|
||||
}
|
||||
|
||||
/// <summary>The names of the sheets started so far (after cleaning).</summary>
|
||||
public IReadOnlyList<string> SheetNames => _sheetNames;
|
||||
|
||||
/// <summary>Starts a workbook.</summary>
|
||||
/// <param name="output">The stream that receives the file; it need not be seekable.</param>
|
||||
/// <param name="options">The options.</param>
|
||||
/// <param name="leaveOpen">Whether to leave <paramref name="output"/> open on dispose.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The writer; complete or dispose it.</returns>
|
||||
public static async Task<XlsxWriter> CreateAsync(Stream output, XlsxOptions? options = null, bool leaveOpen = false, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(output);
|
||||
var buffer = new AsyncOutputBuffer(output);
|
||||
var archive = await ZipArchive.CreateAsync(buffer, ZipArchiveMode.Create, leaveOpen: true, Encoding.UTF8, cancellationToken).ConfigureAwait(false);
|
||||
return new XlsxWriter(archive, buffer, output, leaveOpen, options ?? new XlsxOptions());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Makes a valid sheet name: without <c>[ ] : * ? / \</c>, without apostrophes at the ends, at most 31 characters,
|
||||
/// different (ignoring case) from the names already used.
|
||||
/// </summary>
|
||||
/// <param name="name">The wanted name.</param>
|
||||
/// <param name="used">The names already in the workbook.</param>
|
||||
/// <returns>The name.</returns>
|
||||
public static string CleanSheetName(string? name, IReadOnlyCollection<string> used)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(used);
|
||||
var builder = new StringBuilder();
|
||||
foreach (var c in name ?? string.Empty)
|
||||
{
|
||||
if (c is not ('[' or ']' or ':' or '*' or '?' or '/' or '\\') && !char.IsControl(c))
|
||||
{
|
||||
builder.Append(c);
|
||||
}
|
||||
}
|
||||
|
||||
var clean = builder.ToString().Trim().Trim('\'').Trim();
|
||||
if (clean.Length == 0)
|
||||
{
|
||||
clean = "Foglio" + (used.Count + 1).ToString(CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
clean = clean.Length > MaxSheetNameLength ? clean[..MaxSheetNameLength] : clean;
|
||||
var candidate = clean;
|
||||
for (var i = 2; used.Contains(candidate, StringComparer.OrdinalIgnoreCase); i++)
|
||||
{
|
||||
var suffix = " (" + i.ToString(CultureInfo.InvariantCulture) + ")";
|
||||
candidate = clean[..Math.Min(clean.Length, MaxSheetNameLength - suffix.Length)] + suffix;
|
||||
}
|
||||
|
||||
return candidate;
|
||||
}
|
||||
|
||||
/// <summary>The spreadsheet serial number of a date (days since 1899-12-30, time as fraction).</summary>
|
||||
/// <param name="value">The date.</param>
|
||||
/// <returns>The serial number.</returns>
|
||||
public static double ToSerialDate(DateTime value) => (value - Epoch).TotalDays;
|
||||
|
||||
/// <summary>The letters of a column: 0 is <c>A</c>, 26 is <c>AA</c>.</summary>
|
||||
/// <param name="index">The zero-based column.</param>
|
||||
/// <returns>The letters.</returns>
|
||||
public static string ColumnName(int index)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(index);
|
||||
var name = string.Empty;
|
||||
for (var n = index + 1; n > 0; n = (n - 1) / 26)
|
||||
{
|
||||
name = (char)('A' + ((n - 1) % 26)) + name;
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
|
||||
/// <summary>Starts a sheet (ending the previous one); with column headers the first row is the bold header.</summary>
|
||||
/// <param name="name">The sheet name, cleaned by <see cref="CleanSheetName"/>.</param>
|
||||
/// <param name="columns">The columns, or <see langword="null"/>.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task StartSheetAsync(string name, IReadOnlyList<XlsxColumn>? columns = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_completed, this);
|
||||
await EndSheetAsync(cancellationToken).ConfigureAwait(false);
|
||||
var clean = CleanSheetName(name, _sheetNames);
|
||||
_sheetNames.Add(clean);
|
||||
_columns = columns ?? [];
|
||||
_row = 0;
|
||||
|
||||
var entry = _archive.CreateEntry($"xl/worksheets/sheet{_sheetNames.Count.ToString(CultureInfo.InvariantCulture)}.xml", CompressionLevel.Optimal);
|
||||
_sheetStream = await entry.OpenAsync(cancellationToken).ConfigureAwait(false);
|
||||
_sheet = XmlWriter.Create(_sheetStream, XmlSettings());
|
||||
var w = _sheet;
|
||||
await w.WriteStartDocumentAsync(true).ConfigureAwait(false);
|
||||
await w.WriteStartElementAsync(null, "worksheet", MainNs).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync("xmlns", "r", null, RelNs).ConfigureAwait(false);
|
||||
|
||||
var hasHeader = _columns.Any(c => c.Header is not null);
|
||||
await w.WriteStartElementAsync(null, "sheetViews", MainNs).ConfigureAwait(false);
|
||||
await w.WriteStartElementAsync(null, "sheetView", MainNs).ConfigureAwait(false);
|
||||
if (_sheetNames.Count == 1)
|
||||
{
|
||||
await w.WriteAttributeStringAsync(null, "tabSelected", null, "1").ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await w.WriteAttributeStringAsync(null, "workbookViewId", null, "0").ConfigureAwait(false);
|
||||
if (hasHeader && _options.FreezeHeaderRow)
|
||||
{
|
||||
await w.WriteStartElementAsync(null, "pane", MainNs).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "ySplit", null, "1").ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "topLeftCell", null, "A2").ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "activePane", null, "bottomLeft").ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "state", null, "frozen").ConfigureAwait(false);
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
await w.WriteStartElementAsync(null, "selection", MainNs).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "pane", null, "bottomLeft").ConfigureAwait(false);
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
|
||||
await w.WriteStartElementAsync(null, "sheetFormatPr", MainNs).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "defaultRowHeight", null, "15").ConfigureAwait(false);
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
|
||||
if (_columns.Any(c => c.Width is not null))
|
||||
{
|
||||
await w.WriteStartElementAsync(null, "cols", MainNs).ConfigureAwait(false);
|
||||
for (var i = 0; i < _columns.Count; i++)
|
||||
{
|
||||
if (_columns[i].Width is { } width)
|
||||
{
|
||||
var index = (i + 1).ToString(CultureInfo.InvariantCulture);
|
||||
await w.WriteStartElementAsync(null, "col", MainNs).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "min", null, index).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "max", null, index).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "width", null, Math.Clamp(width, 1, 255).ToString("0.##", CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "customWidth", null, "1").ConfigureAwait(false);
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await w.WriteStartElementAsync(null, "sheetData", MainNs).ConfigureAwait(false);
|
||||
if (hasHeader)
|
||||
{
|
||||
await WriteRowCoreAsync(_columns.Select(c => (object?)c.Header), header: true).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Writes a row in the current sheet (a sheet <c>Foglio1</c> is started if none is).</summary>
|
||||
/// <param name="values">
|
||||
/// The cells: <see cref="string"/>, numbers, <see cref="DateTime"/>, <see cref="DateOnly"/>, <see cref="bool"/>;
|
||||
/// <see langword="null"/> leaves the cell empty; anything else is written as text.
|
||||
/// </param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task WriteRowAsync(IEnumerable<object?> values, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(values);
|
||||
ObjectDisposedException.ThrowIf(_completed, this);
|
||||
if (_sheet is null)
|
||||
{
|
||||
await StartSheetAsync("Foglio1", null, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await WriteRowCoreAsync(values, header: false).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Ends the last sheet and writes workbook, styles, shared strings, relationships and content types.</summary>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task CompleteAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (_completed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_sheetNames.Count == 0)
|
||||
{
|
||||
await StartSheetAsync("Foglio1", null, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await EndSheetAsync(cancellationToken).ConfigureAwait(false);
|
||||
await WritePartAsync("xl/workbook.xml", WriteWorkbookAsync, cancellationToken).ConfigureAwait(false);
|
||||
await WritePartAsync("xl/styles.xml", WriteStylesAsync, cancellationToken).ConfigureAwait(false);
|
||||
if (_options.UseSharedStrings)
|
||||
{
|
||||
await WritePartAsync("xl/sharedStrings.xml", WriteSharedStringsAsync, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await WritePartAsync("xl/_rels/workbook.xml.rels", WriteWorkbookRelationshipsAsync, cancellationToken).ConfigureAwait(false);
|
||||
await WritePartAsync("_rels/.rels", WritePackageRelationshipsAsync, cancellationToken).ConfigureAwait(false);
|
||||
await WritePartAsync("[Content_Types].xml", WriteContentTypesAsync, cancellationToken).ConfigureAwait(false);
|
||||
_completed = true;
|
||||
await _archive.DisposeAsync().ConfigureAwait(false);
|
||||
await _buffer.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
await _buffer.DisposeAsync().ConfigureAwait(false);
|
||||
if (!_leaveOpen)
|
||||
{
|
||||
await _output.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Completes the workbook if needed and closes the stream unless left open.</summary>
|
||||
/// <returns>A task.</returns>
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (!_completed)
|
||||
{
|
||||
await CompleteAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private static XmlWriterSettings XmlSettings() => new()
|
||||
{
|
||||
Async = true,
|
||||
Encoding = new UTF8Encoding(false),
|
||||
Indent = false,
|
||||
CloseOutput = false,
|
||||
};
|
||||
|
||||
private static string CleanText(string value)
|
||||
{
|
||||
var builder = new StringBuilder(Math.Min(value.Length, MaxCellTextLength));
|
||||
for (var i = 0; i < value.Length && builder.Length < MaxCellTextLength; i++)
|
||||
{
|
||||
var c = value[i];
|
||||
if (char.IsHighSurrogate(c) && i + 1 < value.Length && char.IsLowSurrogate(value[i + 1]))
|
||||
{
|
||||
if (builder.Length + 2 > MaxCellTextLength)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
builder.Append(c).Append(value[i + 1]);
|
||||
i++;
|
||||
}
|
||||
else if (XmlConvert.IsXmlChar(c))
|
||||
{
|
||||
builder.Append(c);
|
||||
}
|
||||
}
|
||||
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
private static int StyleOf(XlsxFormat format) => format switch
|
||||
{
|
||||
XlsxFormat.WholeNumber => StyleInteger,
|
||||
XlsxFormat.TwoDecimals => StyleDecimal,
|
||||
XlsxFormat.Euro => StyleEuro,
|
||||
XlsxFormat.Percent => StylePercent,
|
||||
XlsxFormat.Date => StyleDate,
|
||||
XlsxFormat.DateTime => StyleDateTime,
|
||||
XlsxFormat.Text => StyleText,
|
||||
_ => StyleGeneral,
|
||||
};
|
||||
|
||||
private static string? NumberText(object value) => value switch
|
||||
{
|
||||
byte or sbyte or short or ushort or int or uint or long or ulong => Convert.ToString(value, CultureInfo.InvariantCulture),
|
||||
decimal m => m.ToString(CultureInfo.InvariantCulture),
|
||||
double d when double.IsFinite(d) => d.ToString("R", CultureInfo.InvariantCulture),
|
||||
float f when float.IsFinite(f) => ((double)f).ToString("R", CultureInfo.InvariantCulture),
|
||||
_ => null,
|
||||
};
|
||||
|
||||
private async Task WriteRowCoreAsync(IEnumerable<object?> values, bool header)
|
||||
{
|
||||
var w = _sheet!;
|
||||
_row++;
|
||||
var rowNumber = _row.ToString(CultureInfo.InvariantCulture);
|
||||
await w.WriteStartElementAsync(null, "row", MainNs).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "r", null, rowNumber).ConfigureAwait(false);
|
||||
var column = 0;
|
||||
foreach (var value in values)
|
||||
{
|
||||
if (value is not null)
|
||||
{
|
||||
var format = !header && column < _columns.Count ? _columns[column].Format : XlsxFormat.General;
|
||||
await WriteCellAsync(w, ColumnName(column) + rowNumber, value, header ? StyleHeader : StyleOf(format), format).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
column++;
|
||||
}
|
||||
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task WriteCellAsync(XmlWriter w, string reference, object value, int style, XlsxFormat format)
|
||||
{
|
||||
switch (value)
|
||||
{
|
||||
case bool b:
|
||||
await StartCellAsync(w, reference, style, "b").ConfigureAwait(false);
|
||||
await w.WriteElementStringAsync(null, "v", MainNs, b ? "1" : "0").ConfigureAwait(false);
|
||||
break;
|
||||
case DateTime date:
|
||||
var dateStyle = style == StyleGeneral ? (date.TimeOfDay == TimeSpan.Zero ? StyleDate : StyleDateTime) : style;
|
||||
await StartCellAsync(w, reference, dateStyle, null).ConfigureAwait(false);
|
||||
await w.WriteElementStringAsync(null, "v", MainNs, ToSerialDate(date).ToString("R", CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
||||
break;
|
||||
case DateOnly day:
|
||||
await StartCellAsync(w, reference, style == StyleGeneral ? StyleDate : style, null).ConfigureAwait(false);
|
||||
await w.WriteElementStringAsync(null, "v", MainNs, ToSerialDate(day.ToDateTime(TimeOnly.MinValue)).ToString("R", CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
||||
break;
|
||||
default:
|
||||
if (format != XlsxFormat.Text && NumberText(value) is { } number)
|
||||
{
|
||||
await StartCellAsync(w, reference, style, null).ConfigureAwait(false);
|
||||
await w.WriteElementStringAsync(null, "v", MainNs, number).ConfigureAwait(false);
|
||||
break;
|
||||
}
|
||||
|
||||
if (value is double or float)
|
||||
{
|
||||
// NaN and infinity have no spreadsheet value: the cell stays empty.
|
||||
return;
|
||||
}
|
||||
|
||||
var text = CleanText(Convert.ToString(value, CultureInfo.InvariantCulture) ?? string.Empty);
|
||||
if (_options.UseSharedStrings)
|
||||
{
|
||||
if (!_sharedIndex.TryGetValue(text, out var index))
|
||||
{
|
||||
index = _shared.Count;
|
||||
_shared.Add(text);
|
||||
_sharedIndex[text] = index;
|
||||
}
|
||||
|
||||
await StartCellAsync(w, reference, style, "s").ConfigureAwait(false);
|
||||
await w.WriteElementStringAsync(null, "v", MainNs, index.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await StartCellAsync(w, reference, style, "inlineStr").ConfigureAwait(false);
|
||||
await w.WriteStartElementAsync(null, "is", MainNs).ConfigureAwait(false);
|
||||
await WriteTextElementAsync(w, text).ConfigureAwait(false);
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static async Task StartCellAsync(XmlWriter w, string reference, int style, string? type)
|
||||
{
|
||||
await w.WriteStartElementAsync(null, "c", MainNs).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "r", null, reference).ConfigureAwait(false);
|
||||
if (style != StyleGeneral)
|
||||
{
|
||||
await w.WriteAttributeStringAsync(null, "s", null, style.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (type is not null)
|
||||
{
|
||||
await w.WriteAttributeStringAsync(null, "t", null, type).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task WriteTextElementAsync(XmlWriter w, string text)
|
||||
{
|
||||
await w.WriteStartElementAsync(null, "t", MainNs).ConfigureAwait(false);
|
||||
if (text.Length > 0 && (char.IsWhiteSpace(text[0]) || char.IsWhiteSpace(text[^1])))
|
||||
{
|
||||
await w.WriteAttributeStringAsync("xml", "space", null, "preserve").ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await w.WriteStringAsync(text).ConfigureAwait(false);
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task EndSheetAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (_sheet is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await _sheet.WriteEndElementAsync().ConfigureAwait(false);
|
||||
await _sheet.WriteEndElementAsync().ConfigureAwait(false);
|
||||
await _sheet.WriteEndDocumentAsync().ConfigureAwait(false);
|
||||
await _sheet.FlushAsync().ConfigureAwait(false);
|
||||
await _sheet.DisposeAsync().ConfigureAwait(false);
|
||||
_sheet = null;
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
await _sheetStream!.DisposeAsync().ConfigureAwait(false);
|
||||
_sheetStream = null;
|
||||
await _buffer.DrainAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task WritePartAsync(string name, Func<XmlWriter, Task> write, CancellationToken cancellationToken)
|
||||
{
|
||||
var entry = _archive.CreateEntry(name, CompressionLevel.Optimal);
|
||||
var stream = await entry.OpenAsync(cancellationToken).ConfigureAwait(false);
|
||||
await using (stream.ConfigureAwait(false))
|
||||
{
|
||||
var w = XmlWriter.Create(stream, XmlSettings());
|
||||
await using var writerScope = w.ConfigureAwait(false);
|
||||
await w.WriteStartDocumentAsync(true).ConfigureAwait(false);
|
||||
await write(w).ConfigureAwait(false);
|
||||
await w.WriteEndDocumentAsync().ConfigureAwait(false);
|
||||
await w.FlushAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await _buffer.DrainAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task WriteWorkbookAsync(XmlWriter w)
|
||||
{
|
||||
await w.WriteStartElementAsync(null, "workbook", MainNs).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync("xmlns", "r", null, RelNs).ConfigureAwait(false);
|
||||
await w.WriteStartElementAsync(null, "sheets", MainNs).ConfigureAwait(false);
|
||||
for (var i = 0; i < _sheetNames.Count; i++)
|
||||
{
|
||||
var id = (i + 1).ToString(CultureInfo.InvariantCulture);
|
||||
await w.WriteStartElementAsync(null, "sheet", MainNs).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "name", null, _sheetNames[i]).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "sheetId", null, id).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync("r", "id", RelNs, "rId" + id).ConfigureAwait(false);
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task WriteSharedStringsAsync(XmlWriter w)
|
||||
{
|
||||
var count = _shared.Count.ToString(CultureInfo.InvariantCulture);
|
||||
await w.WriteStartElementAsync(null, "sst", MainNs).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "count", null, count).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "uniqueCount", null, count).ConfigureAwait(false);
|
||||
foreach (var text in _shared)
|
||||
{
|
||||
await w.WriteStartElementAsync(null, "si", MainNs).ConfigureAwait(false);
|
||||
await WriteTextElementAsync(w, text).ConfigureAwait(false);
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static async Task WriteStylesAsync(XmlWriter w)
|
||||
{
|
||||
await w.WriteStartElementAsync(null, "styleSheet", MainNs).ConfigureAwait(false);
|
||||
|
||||
await w.WriteStartElementAsync(null, "numFmts", MainNs).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "count", null, "1").ConfigureAwait(false);
|
||||
await w.WriteStartElementAsync(null, "numFmt", MainNs).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "numFmtId", null, "164").ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "formatCode", null, "#,##0.00\\ \"€\"").ConfigureAwait(false);
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
|
||||
await w.WriteStartElementAsync(null, "fonts", MainNs).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "count", null, "2").ConfigureAwait(false);
|
||||
foreach (var bold in new[] { false, true })
|
||||
{
|
||||
await w.WriteStartElementAsync(null, "font", MainNs).ConfigureAwait(false);
|
||||
if (bold)
|
||||
{
|
||||
await w.WriteElementStringAsync(null, "b", MainNs, string.Empty).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await WriteValElementAsync(w, "sz", "11").ConfigureAwait(false);
|
||||
await WriteValElementAsync(w, "name", "Calibri").ConfigureAwait(false);
|
||||
await WriteValElementAsync(w, "family", "2").ConfigureAwait(false);
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
|
||||
await w.WriteStartElementAsync(null, "fills", MainNs).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "count", null, "2").ConfigureAwait(false);
|
||||
foreach (var pattern in new[] { "none", "gray125" })
|
||||
{
|
||||
await w.WriteStartElementAsync(null, "fill", MainNs).ConfigureAwait(false);
|
||||
await w.WriteStartElementAsync(null, "patternFill", MainNs).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "patternType", null, pattern).ConfigureAwait(false);
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
|
||||
await w.WriteStartElementAsync(null, "borders", MainNs).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "count", null, "1").ConfigureAwait(false);
|
||||
await w.WriteStartElementAsync(null, "border", MainNs).ConfigureAwait(false);
|
||||
foreach (var side in new[] { "left", "right", "top", "bottom", "diagonal" })
|
||||
{
|
||||
await w.WriteElementStringAsync(null, side, MainNs, string.Empty).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
|
||||
await w.WriteStartElementAsync(null, "cellStyleXfs", MainNs).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "count", null, "1").ConfigureAwait(false);
|
||||
await WriteXfAsync(w, numberFormat: 0, font: 0, cellXf: false).ConfigureAwait(false);
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
|
||||
// The order matches the Style* constants.
|
||||
(int NumberFormat, int Font)[] cellXfs = [(0, 0), (0, 1), (14, 0), (22, 0), (3, 0), (4, 0), (164, 0), (10, 0), (49, 0)];
|
||||
await w.WriteStartElementAsync(null, "cellXfs", MainNs).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "count", null, cellXfs.Length.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
||||
foreach (var (numberFormat, font) in cellXfs)
|
||||
{
|
||||
await WriteXfAsync(w, numberFormat, font, cellXf: true).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
|
||||
await w.WriteStartElementAsync(null, "cellStyles", MainNs).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "count", null, "1").ConfigureAwait(false);
|
||||
await w.WriteStartElementAsync(null, "cellStyle", MainNs).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "name", null, "Normal").ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "xfId", null, "0").ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "builtinId", null, "0").ConfigureAwait(false);
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static async Task WriteValElementAsync(XmlWriter w, string name, string value)
|
||||
{
|
||||
await w.WriteStartElementAsync(null, name, MainNs).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "val", null, value).ConfigureAwait(false);
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static async Task WriteXfAsync(XmlWriter w, int numberFormat, int font, bool cellXf)
|
||||
{
|
||||
await w.WriteStartElementAsync(null, "xf", MainNs).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "numFmtId", null, numberFormat.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "fontId", null, font.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "fillId", null, "0").ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "borderId", null, "0").ConfigureAwait(false);
|
||||
if (cellXf)
|
||||
{
|
||||
await w.WriteAttributeStringAsync(null, "xfId", null, "0").ConfigureAwait(false);
|
||||
if (numberFormat != 0)
|
||||
{
|
||||
await w.WriteAttributeStringAsync(null, "applyNumberFormat", null, "1").ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (font != 0)
|
||||
{
|
||||
await w.WriteAttributeStringAsync(null, "applyFont", null, "1").ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task WriteWorkbookRelationshipsAsync(XmlWriter w)
|
||||
{
|
||||
await w.WriteStartElementAsync(null, "Relationships", PackageRelNs).ConfigureAwait(false);
|
||||
for (var i = 1; i <= _sheetNames.Count; i++)
|
||||
{
|
||||
var id = i.ToString(CultureInfo.InvariantCulture);
|
||||
await WriteRelationshipAsync(w, "rId" + id, RelNs + "/worksheet", "worksheets/sheet" + id + ".xml").ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var next = _sheetNames.Count + 1;
|
||||
await WriteRelationshipAsync(w, "rId" + next.ToString(CultureInfo.InvariantCulture), RelNs + "/styles", "styles.xml").ConfigureAwait(false);
|
||||
if (_options.UseSharedStrings)
|
||||
{
|
||||
await WriteRelationshipAsync(w, "rId" + (next + 1).ToString(CultureInfo.InvariantCulture), RelNs + "/sharedStrings", "sharedStrings.xml").ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static async Task WritePackageRelationshipsAsync(XmlWriter w)
|
||||
{
|
||||
await w.WriteStartElementAsync(null, "Relationships", PackageRelNs).ConfigureAwait(false);
|
||||
await WriteRelationshipAsync(w, "rId1", RelNs + "/officeDocument", "xl/workbook.xml").ConfigureAwait(false);
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static async Task WriteRelationshipAsync(XmlWriter w, string id, string type, string target)
|
||||
{
|
||||
await w.WriteStartElementAsync(null, "Relationship", PackageRelNs).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "Id", null, id).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "Type", null, type).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "Target", null, target).ConfigureAwait(false);
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task WriteContentTypesAsync(XmlWriter w)
|
||||
{
|
||||
await w.WriteStartElementAsync(null, "Types", ContentTypesNs).ConfigureAwait(false);
|
||||
await WriteDefaultTypeAsync(w, "rels", "application/vnd.openxmlformats-package.relationships+xml").ConfigureAwait(false);
|
||||
await WriteDefaultTypeAsync(w, "xml", "application/xml").ConfigureAwait(false);
|
||||
await WriteOverrideAsync(w, "/xl/workbook.xml", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml").ConfigureAwait(false);
|
||||
for (var i = 1; i <= _sheetNames.Count; i++)
|
||||
{
|
||||
await WriteOverrideAsync(w, "/xl/worksheets/sheet" + i.ToString(CultureInfo.InvariantCulture) + ".xml", WorksheetType).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await WriteOverrideAsync(w, "/xl/styles.xml", "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml").ConfigureAwait(false);
|
||||
if (_options.UseSharedStrings)
|
||||
{
|
||||
await WriteOverrideAsync(w, "/xl/sharedStrings.xml", "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml").ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static async Task WriteDefaultTypeAsync(XmlWriter w, string extension, string contentType)
|
||||
{
|
||||
await w.WriteStartElementAsync(null, "Default", ContentTypesNs).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "Extension", null, extension).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "ContentType", null, contentType).ConfigureAwait(false);
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static async Task WriteOverrideAsync(XmlWriter w, string part, string contentType)
|
||||
{
|
||||
await w.WriteStartElementAsync(null, "Override", ContentTypesNs).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "PartName", null, part).ConfigureAwait(false);
|
||||
await w.WriteAttributeStringAsync(null, "ContentType", null, contentType).ConfigureAwait(false);
|
||||
await w.WriteEndElementAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
using System.Globalization;
|
||||
using System.IO.Compression;
|
||||
using System.Text;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Files;
|
||||
|
||||
/// <summary>
|
||||
/// Writes a ZIP archive straight to a stream that need not be seekable, such as an HTTP response (SPEC §9.4: mass
|
||||
/// prints and "Scarica tutto" are streamed, never staged in temporary files). A thin wrapper over
|
||||
/// <see cref="ZipArchive"/> in <see cref="ZipArchiveMode.Create"/> mode that only uses its asynchronous API, cleans
|
||||
/// entry names and makes duplicates unique (<c>fattura.pdf</c>, <c>fattura (2).pdf</c>).
|
||||
/// </summary>
|
||||
/// <example>
|
||||
/// <code>
|
||||
/// await using var zip = await ZipStreamWriter.CreateAsync(response.Body, leaveOpen: true, cancellationToken);
|
||||
/// await zip.AddAsync("fattura.pdf", pdfStream, cancellationToken: cancellationToken);
|
||||
/// await zip.AddAsync("fattura.xml", xmlBytes, cancellationToken: cancellationToken);
|
||||
/// </code>
|
||||
/// </example>
|
||||
public sealed class ZipStreamWriter : IAsyncDisposable
|
||||
{
|
||||
private const int MaxNameLength = 200;
|
||||
private readonly ZipArchive _archive;
|
||||
private readonly AsyncOutputBuffer _buffer;
|
||||
private readonly Stream _output;
|
||||
private readonly bool _leaveOpen;
|
||||
private readonly HashSet<string> _names = new(StringComparer.OrdinalIgnoreCase);
|
||||
private bool _disposed;
|
||||
|
||||
private ZipStreamWriter(ZipArchive archive, AsyncOutputBuffer buffer, Stream output, bool leaveOpen)
|
||||
{
|
||||
_archive = archive;
|
||||
_buffer = buffer;
|
||||
_output = output;
|
||||
_leaveOpen = leaveOpen;
|
||||
}
|
||||
|
||||
/// <summary>The number of entries written.</summary>
|
||||
public int Count => _names.Count;
|
||||
|
||||
/// <summary>Starts an archive.</summary>
|
||||
/// <param name="output">The stream that receives the archive.</param>
|
||||
/// <param name="leaveOpen">Whether to leave <paramref name="output"/> open on dispose.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The writer; dispose it to write the central directory.</returns>
|
||||
public static async Task<ZipStreamWriter> CreateAsync(Stream output, bool leaveOpen = false, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(output);
|
||||
var buffer = new AsyncOutputBuffer(output);
|
||||
var archive = await ZipArchive.CreateAsync(buffer, ZipArchiveMode.Create, leaveOpen: true, Encoding.UTF8, cancellationToken).ConfigureAwait(false);
|
||||
return new ZipStreamWriter(archive, buffer, output, leaveOpen);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cleans an entry name: forward slashes for folders, no drive, no <c>..</c>, no leading slash, no characters that
|
||||
/// Windows refuses, at most 200 characters.
|
||||
/// </summary>
|
||||
/// <param name="name">The name.</param>
|
||||
/// <returns>The clean name (<c>file</c> when nothing is left).</returns>
|
||||
public static string CleanEntryName(string name)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(name);
|
||||
var parts = name.Replace('\\', '/').Split('/', StringSplitOptions.RemoveEmptyEntries)
|
||||
.Select(CleanSegment)
|
||||
.Where(p => p.Length > 0 && p != "." && p != "..")
|
||||
.ToArray();
|
||||
var clean = string.Join('/', parts);
|
||||
if (clean.Length > MaxNameLength)
|
||||
{
|
||||
var extension = Path.GetExtension(clean);
|
||||
clean = clean[..(MaxNameLength - extension.Length)] + extension;
|
||||
}
|
||||
|
||||
return clean.Length == 0 ? "file" : clean;
|
||||
}
|
||||
|
||||
/// <summary>Adds an entry with the content of a stream, read to the end.</summary>
|
||||
/// <param name="entryName">The entry name.</param>
|
||||
/// <param name="content">The content.</param>
|
||||
/// <param name="lastWrite">The date shown for the entry; now when omitted.</param>
|
||||
/// <param name="level">The compression: <see cref="CompressionLevel.NoCompression"/> suits files already compressed (JPEG, ZIP, P7M).</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The name actually used (made unique).</returns>
|
||||
public async Task<string> AddAsync(
|
||||
string entryName, Stream content, DateTimeOffset? lastWrite = null, CompressionLevel level = CompressionLevel.Optimal, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(content);
|
||||
var (name, target) = await OpenEntryAsync(entryName, lastWrite, level, cancellationToken).ConfigureAwait(false);
|
||||
await using (target.ConfigureAwait(false))
|
||||
{
|
||||
await content.CopyToAsync(target, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await _buffer.DrainAsync(cancellationToken).ConfigureAwait(false);
|
||||
return name;
|
||||
}
|
||||
|
||||
/// <summary>Adds an entry with the given bytes.</summary>
|
||||
/// <param name="entryName">The entry name.</param>
|
||||
/// <param name="content">The content.</param>
|
||||
/// <param name="lastWrite">The date shown for the entry; now when omitted.</param>
|
||||
/// <param name="level">The compression.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The name actually used (made unique).</returns>
|
||||
public async Task<string> AddAsync(
|
||||
string entryName, ReadOnlyMemory<byte> content, DateTimeOffset? lastWrite = null, CompressionLevel level = CompressionLevel.Optimal, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var (name, target) = await OpenEntryAsync(entryName, lastWrite, level, cancellationToken).ConfigureAwait(false);
|
||||
await using (target.ConfigureAwait(false))
|
||||
{
|
||||
await target.WriteAsync(content, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await _buffer.DrainAsync(cancellationToken).ConfigureAwait(false);
|
||||
return name;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens an entry for the caller to write (for example a generator writing a PDF directly into the archive). Write
|
||||
/// to the stream with asynchronous calls and dispose it before adding the next entry (the few bytes written when it
|
||||
/// is disposed are sent with the next call).
|
||||
/// </summary>
|
||||
/// <param name="entryName">The entry name.</param>
|
||||
/// <param name="lastWrite">The date shown for the entry; now when omitted.</param>
|
||||
/// <param name="level">The compression.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The name actually used and the entry stream.</returns>
|
||||
public async Task<(string Name, Stream Content)> OpenEntryAsync(
|
||||
string entryName, DateTimeOffset? lastWrite = null, CompressionLevel level = CompressionLevel.Optimal, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
await _buffer.DrainAsync(cancellationToken).ConfigureAwait(false);
|
||||
var name = Unique(CleanEntryName(entryName));
|
||||
var entry = _archive.CreateEntry(name, level);
|
||||
entry.LastWriteTime = lastWrite ?? DateTimeOffset.Now;
|
||||
var stream = await entry.OpenAsync(cancellationToken).ConfigureAwait(false);
|
||||
return (name, stream);
|
||||
}
|
||||
|
||||
/// <summary>Writes the central directory and closes the stream unless left open.</summary>
|
||||
/// <returns>A task.</returns>
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
await _archive.DisposeAsync().ConfigureAwait(false);
|
||||
await _buffer.FlushAsync().ConfigureAwait(false);
|
||||
await _buffer.DisposeAsync().ConfigureAwait(false);
|
||||
if (!_leaveOpen)
|
||||
{
|
||||
await _output.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private static string CleanSegment(string segment)
|
||||
{
|
||||
var builder = new StringBuilder(segment.Length);
|
||||
foreach (var c in segment)
|
||||
{
|
||||
builder.Append(char.IsControl(c) || c is ':' or '*' or '?' or '"' or '<' or '>' or '|' ? '_' : c);
|
||||
}
|
||||
|
||||
return builder.ToString().Trim().TrimEnd('.');
|
||||
}
|
||||
|
||||
private string Unique(string name)
|
||||
{
|
||||
if (_names.Add(name))
|
||||
{
|
||||
return name;
|
||||
}
|
||||
|
||||
var extension = Path.GetExtension(name);
|
||||
var stem = name[..^extension.Length];
|
||||
for (var i = 2; ; i++)
|
||||
{
|
||||
var candidate = string.Create(CultureInfo.InvariantCulture, $"{stem} ({i}){extension}");
|
||||
if (_names.Add(candidate))
|
||||
{
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="it">
|
||||
<html lang="it" @attributes="RootAttributes">
|
||||
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
@@ -10,6 +10,10 @@
|
||||
<link rel="icon" href="icon.svg" type="image/svg+xml" />
|
||||
<link rel="apple-touch-icon" href="icon-256.png" />
|
||||
<ResourcePreloader />
|
||||
<link rel="stylesheet" href="@Assets["css/tokens.css"]" />
|
||||
<link rel="stylesheet" href="@Assets["css/components.css"]" />
|
||||
<link rel="stylesheet" href="@Assets["css/interactive.css"]" />
|
||||
<link rel="stylesheet" href="@Assets["css/print.css"]" />
|
||||
<link rel="stylesheet" href="@Assets["app.css"]" />
|
||||
<link rel="stylesheet" href="@Assets["Khaemhat.Web.styles.css"]" />
|
||||
@* No <ImportMap />: it is an inline script, and the content security policy allows none (no JS modules yet). *@
|
||||
@@ -20,6 +24,7 @@
|
||||
<Routes @rendermode="PageRenderMode" />
|
||||
<ReconnectModal />
|
||||
<script src="@Assets["_framework/blazor.web.js"]"></script>
|
||||
<script src="@Assets["js/khaemhat.js"]"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -28,6 +33,21 @@
|
||||
[CascadingParameter]
|
||||
private HttpContext HttpContext { get; set; } = default!;
|
||||
|
||||
private IReadOnlyDictionary<string, object> RootAttributes { get; set; } = new Dictionary<string, object>();
|
||||
|
||||
// The sign-in pages are static server-rendered forms (they set the cookie); everything else is interactive.
|
||||
private IComponentRenderMode? PageRenderMode => HttpContext.AcceptsInteractiveRouting() ? InteractiveServer : null;
|
||||
|
||||
[Inject]
|
||||
private UserSettingsService Settings { get; set; } = default!;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
// The theme of the signed-in user is written on the server, so the first paint already has the right colours;
|
||||
// before sign-in the system theme applies (data-theme="auto").
|
||||
var actor = SessionCookie.ActorOf(HttpContext.User);
|
||||
var preferences = actor is null ? null : await Settings.GetPreferencesAsync(actor, HttpContext.RequestAborted);
|
||||
RootAttributes = ThemeService.RootAttributes(preferences).ToDictionary(a => a.Key, a => (object)a.Value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
@* A widget whose data comes from a module still to come (SPEC §10.3): it can already be placed and sized, and says
|
||||
which milestone fills it. *@
|
||||
<KhWidget Id="@Definition.Id" Title="@T[Definition.TitleKey]" Icon="@Definition.Icon">
|
||||
<div class="kh-wcoming">
|
||||
<KhIcon Name="clock" />
|
||||
<p class="muted">@T[Definition.DescriptionKey]</p>
|
||||
@if (Definition.Milestone is { } milestone)
|
||||
{
|
||||
<p class="s">@T.Format("Dashboard.Coming.Text", T["Dashboard.Coming." + milestone], milestone)</p>
|
||||
}
|
||||
</div>
|
||||
</KhWidget>
|
||||
|
||||
@code {
|
||||
/// <summary>The widget.</summary>
|
||||
[Parameter, EditorRequired]
|
||||
public WidgetDefinition Definition { get; set; } = default!;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
@* Picks the component of a widget of the layout. *@
|
||||
@switch (Definition.Id)
|
||||
{
|
||||
case WidgetIds.Todo:
|
||||
<FeedWidget Definition="Definition" Kind="FeedKind.Todo" />
|
||||
break;
|
||||
case WidgetIds.Done:
|
||||
<FeedWidget Definition="Definition" Kind="FeedKind.Done" />
|
||||
break;
|
||||
case WidgetIds.Deadlines:
|
||||
<FeedWidget Definition="Definition" Kind="FeedKind.Deadlines" />
|
||||
break;
|
||||
case WidgetIds.Notes:
|
||||
<NotesWidget Definition="Definition" />
|
||||
break;
|
||||
case WidgetIds.Shortcuts:
|
||||
<ShortcutsWidget Definition="Definition" />
|
||||
break;
|
||||
case WidgetIds.SystemStatus:
|
||||
<SystemStatusWidget Definition="Definition" />
|
||||
break;
|
||||
default:
|
||||
<ComingWidget Definition="Definition" />
|
||||
break;
|
||||
}
|
||||
|
||||
@code {
|
||||
/// <summary>The widget.</summary>
|
||||
[Parameter, EditorRequired]
|
||||
public WidgetDefinition Definition { get; set; } = default!;
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
@inject ShellSession Session
|
||||
@inject TodoAggregator Todos
|
||||
@inject DoneAggregator Dones
|
||||
@inject DeadlineAggregator Deadlines
|
||||
@inject TimeProvider Clock
|
||||
|
||||
@* Da fare oggi, Fatto oggi and Scadenze 30 giorni (SPEC §10.3): the lines the sources of the modules give, with the
|
||||
area at the side. Mockup 004. *@
|
||||
<KhWidget Id="@Definition.Id" Title="@T[Definition.TitleKey]" Icon="@Definition.Icon" Tight="true">
|
||||
<Actions>
|
||||
@if (_items is { Count: > 0 })
|
||||
{
|
||||
<span class="badge @(Kind == FeedKind.Todo && _items.Any(i => i.Tone >= FeedTone.Warning) ? "red" : "gray")">@T.Number(_items.Count)</span>
|
||||
}
|
||||
</Actions>
|
||||
<ChildContent>
|
||||
@if (_failed)
|
||||
{
|
||||
<p class="kh-wempty"><KhIcon Name="alert" /> @T["Dashboard.Feed.Error"]</p>
|
||||
}
|
||||
else if (_items is null)
|
||||
{
|
||||
<p class="kh-wempty muted">@T["Dashboard.Feed.Loading"]</p>
|
||||
}
|
||||
else if (_items.Count == 0)
|
||||
{
|
||||
<p class="kh-wempty"><KhIcon Name="check-circle" /> @T[EmptyKey]</p>
|
||||
}
|
||||
else if (Kind == FeedKind.Deadlines)
|
||||
{
|
||||
<div class="kh-wlist">
|
||||
@foreach (var item in _items)
|
||||
{
|
||||
<a class="deadline" href="@HrefOf(item)" aria-disabled="@(item.Href is null ? "true" : null)">
|
||||
<div class="dd @DayClass(item)">
|
||||
<b>@item.When!.Value.ToString("dd", T.Culture)</b>
|
||||
<span>@item.When!.Value.ToString("MMM", T.Culture)</span>
|
||||
</div>
|
||||
<div>
|
||||
<div class="dt">@item.Text</div>
|
||||
<div class="ds">@Relative(item)@(item.Detail is null ? null : " · " + item.Detail)</div>
|
||||
</div>
|
||||
<span class="badge gray">@T[item.AreaKey]</span>
|
||||
</a>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="list kh-wlist">
|
||||
@foreach (var item in _items)
|
||||
{
|
||||
<a class="li" href="@HrefOf(item)" aria-disabled="@(item.Href is null ? "true" : null)">
|
||||
<span class="kh-tone @ToneClass(item.Tone)" aria-hidden="true"></span>
|
||||
<div class="grow">
|
||||
<div class="t">@item.Text</div>
|
||||
@if (item.Detail is not null)
|
||||
{
|
||||
<div class="s">@item.Detail</div>
|
||||
}
|
||||
</div>
|
||||
<span class="badge gray">@T[item.AreaKey]</span>
|
||||
@if (Kind == FeedKind.Done && item.When is { } when)
|
||||
{
|
||||
<span class="s num">@when.ToString("HH:mm", T.Culture)</span>
|
||||
}
|
||||
</a>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</ChildContent>
|
||||
</KhWidget>
|
||||
|
||||
@code {
|
||||
private IReadOnlyList<FeedItem>? _items;
|
||||
private bool _failed;
|
||||
|
||||
/// <summary>The widget.</summary>
|
||||
[Parameter, EditorRequired]
|
||||
public WidgetDefinition Definition { get; set; } = default!;
|
||||
|
||||
/// <summary>Which list.</summary>
|
||||
[Parameter]
|
||||
public FeedKind Kind { get; set; }
|
||||
|
||||
private string EmptyKey => Definition.TitleKey[..Definition.TitleKey.LastIndexOf('.')] + ".Empty";
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await Session.EnsureLoadedAsync();
|
||||
if (Session.Actor is not { } actor)
|
||||
{
|
||||
_items = [];
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_items = Kind switch
|
||||
{
|
||||
FeedKind.Todo => await Todos.GetAsync(actor),
|
||||
FeedKind.Done => await Dones.GetAsync(actor),
|
||||
_ => await Deadlines.GetAsync(actor),
|
||||
};
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_failed = true;
|
||||
}
|
||||
}
|
||||
|
||||
private static string? HrefOf(FeedItem item) => item.Href?.TrimStart('/') is { } href ? (href.Length == 0 ? "./" : href) : null;
|
||||
|
||||
private static string ToneClass(FeedTone tone) => tone switch
|
||||
{
|
||||
FeedTone.Ok => "ok",
|
||||
FeedTone.Info => "info",
|
||||
FeedTone.Warning => "warn",
|
||||
FeedTone.Error => "err",
|
||||
_ => "neutral",
|
||||
};
|
||||
|
||||
private int DaysTo(FeedItem item) =>
|
||||
DateOnly.FromDateTime(item.When!.Value.DateTime).DayNumber - DateOnly.FromDateTime(Clock.GetLocalNow().DateTime).DayNumber;
|
||||
|
||||
private string? DayClass(FeedItem item) => DaysTo(item) switch
|
||||
{
|
||||
<= 1 => "hot",
|
||||
<= 7 => "warm",
|
||||
_ => null,
|
||||
};
|
||||
|
||||
private string Relative(FeedItem item) => DaysTo(item) switch
|
||||
{
|
||||
<= 0 => T["Dashboard.Feed.Today"],
|
||||
1 => T["Dashboard.Feed.Tomorrow"],
|
||||
var days => T.Format("Dashboard.Feed.InDays", days),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
@inject ShellSession Session
|
||||
@inject DashboardService Dashboard
|
||||
@inject ToastService Toasts
|
||||
|
||||
@* Promemoria personali (SPEC §10.3): free notes of the user, ticked when done, saved as they change. *@
|
||||
<KhWidget Id="@Definition.Id" Title="@T[Definition.TitleKey]" Icon="@Definition.Icon" Tight="true">
|
||||
<Actions>
|
||||
@if (_notes.Any(n => n.Done))
|
||||
{
|
||||
<button type="button" class="ib" title="@T["Dashboard.Widgets.Notes.ClearDone"]" aria-label="@T["Dashboard.Widgets.Notes.ClearDone"]"
|
||||
@onclick="ClearDoneAsync"><KhIcon Name="trash" /></button>
|
||||
}
|
||||
</Actions>
|
||||
<ChildContent>
|
||||
<div class="kh-wlist">
|
||||
@for (var i = 0; i < _notes.Count; i++)
|
||||
{
|
||||
var index = i;
|
||||
var note = _notes[i];
|
||||
<div class="chk-row @(note.Done ? "done" : null)">
|
||||
<input type="checkbox" checked="@note.Done" aria-label="@T.Format("Dashboard.Widgets.Notes.Toggle", note.Text)"
|
||||
@onchange="() => ToggleAsync(index)" />
|
||||
<div class="t">@note.Text</div>
|
||||
<button type="button" class="ib kh-rowx" title="@T.Format("Dashboard.Widgets.Notes.Remove", note.Text)"
|
||||
aria-label="@T.Format("Dashboard.Widgets.Notes.Remove", note.Text)" @onclick="() => RemoveAsync(index)"><KhIcon Name="x" /></button>
|
||||
</div>
|
||||
}
|
||||
@if (_loaded && _notes.Count == 0)
|
||||
{
|
||||
<p class="kh-wempty muted">@T["Dashboard.Widgets.Notes.Empty"]</p>
|
||||
}
|
||||
</div>
|
||||
<div class="kh-wadd">
|
||||
<KhIcon Name="plus" Class="sm" />
|
||||
<input class="kh-input" value="@_text" maxlength="@DashboardService.MaxNoteLength" aria-label="@T["Dashboard.Widgets.Notes.Add"]"
|
||||
placeholder="@T["Dashboard.Widgets.Notes.Placeholder"]" @oninput="e => _text = e.Value as string" @onkeydown="OnKeyDownAsync" />
|
||||
</div>
|
||||
</ChildContent>
|
||||
</KhWidget>
|
||||
|
||||
@code {
|
||||
private List<PersonalNote> _notes = [];
|
||||
private string? _text;
|
||||
private bool _loaded;
|
||||
|
||||
/// <summary>The widget.</summary>
|
||||
[Parameter, EditorRequired]
|
||||
public WidgetDefinition Definition { get; set; } = default!;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await Session.EnsureLoadedAsync();
|
||||
if (Session.Actor is { } actor)
|
||||
{
|
||||
_notes = [.. await Dashboard.GetNotesAsync(actor)];
|
||||
}
|
||||
|
||||
_loaded = true;
|
||||
}
|
||||
|
||||
private async Task OnKeyDownAsync(KeyboardEventArgs e)
|
||||
{
|
||||
if (e.Key != "Enter" || string.IsNullOrWhiteSpace(_text))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_notes.Count >= DashboardService.MaxNotes)
|
||||
{
|
||||
Toasts.Show(ToastKind.Warning, T.Format("Dashboard.Widgets.Notes.Full", DashboardService.MaxNotes));
|
||||
return;
|
||||
}
|
||||
|
||||
// Show the text just typed before clearing, or Blazor would not see the field change and keep it.
|
||||
_notes.Add(new PersonalNote(_text.Trim(), false));
|
||||
var typed = _text;
|
||||
_text = typed;
|
||||
StateHasChanged();
|
||||
await Task.Yield();
|
||||
_text = null;
|
||||
await SaveAsync();
|
||||
}
|
||||
|
||||
private Task ToggleAsync(int index)
|
||||
{
|
||||
_notes[index] = _notes[index] with { Done = !_notes[index].Done };
|
||||
return SaveAsync();
|
||||
}
|
||||
|
||||
private Task RemoveAsync(int index)
|
||||
{
|
||||
_notes.RemoveAt(index);
|
||||
return SaveAsync();
|
||||
}
|
||||
|
||||
private Task ClearDoneAsync()
|
||||
{
|
||||
_notes.RemoveAll(n => n.Done);
|
||||
return SaveAsync();
|
||||
}
|
||||
|
||||
private async Task SaveAsync()
|
||||
{
|
||||
if (Session.Actor is { } actor)
|
||||
{
|
||||
await Dashboard.SaveNotesAsync(actor, _notes);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
@inject ShellSession Session
|
||||
@inject DashboardService Dashboard
|
||||
|
||||
@* Scorciatoie (SPEC §10.3): buttons to the pages the user opens most, chosen among the menu entries they can see.
|
||||
Until chosen, the first areas of the menu. *@
|
||||
<KhWidget Id="@Definition.Id" Title="@T[Definition.TitleKey]" Icon="@Definition.Icon">
|
||||
<Actions>
|
||||
<button type="button" class="ib" title="@T["Dashboard.Widgets.Shortcuts.Edit"]" aria-label="@T["Dashboard.Widgets.Shortcuts.Edit"]"
|
||||
@onclick="Edit"><KhIcon Name="edit" /></button>
|
||||
</Actions>
|
||||
<ChildContent>
|
||||
@if (Shortcuts.Count == 0)
|
||||
{
|
||||
<p class="kh-wempty muted">@T["Dashboard.Widgets.Shortcuts.Empty"]</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="kh-shortcuts">
|
||||
@foreach (var item in Shortcuts)
|
||||
{
|
||||
<a class="kh-shortcut" href="@(item.Href == "/" ? "./" : item.Href.TrimStart('/'))">
|
||||
<span class="ico-box"><KhIcon Name="@item.Icon" /></span>
|
||||
<span>@T[item.Key]</span>
|
||||
</a>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</ChildContent>
|
||||
</KhWidget>
|
||||
|
||||
<KhDialog Open="_editing" Title="@T["Dashboard.Widgets.Shortcuts.Edit"]" Icon="zap" Size="sm" OnClose="() => _editing = false">
|
||||
<ChildContent>
|
||||
<p class="muted">@T.Format("Dashboard.Widgets.Shortcuts.Hint", DashboardService.MaxShortcuts)</p>
|
||||
<div class="kh-picklist">
|
||||
@foreach (var item in Choices)
|
||||
{
|
||||
var chosen = _draft.Contains(item.Href);
|
||||
<label class="chk">
|
||||
<input type="checkbox" checked="@chosen" disabled="@(!chosen && _draft.Count >= DashboardService.MaxShortcuts)"
|
||||
@onchange="() => Toggle(item.Href)" />
|
||||
<KhIcon Name="@item.Icon" Class="sm" /> @T[item.Key]
|
||||
</label>
|
||||
}
|
||||
</div>
|
||||
</ChildContent>
|
||||
<Footer>
|
||||
<button type="button" class="btn" @onclick="() => _editing = false">@T["Common.Cancel"]</button>
|
||||
<button type="button" class="btn primary" @onclick="SaveAsync"><KhIcon Name="check" /> @T["Common.Save"]</button>
|
||||
</Footer>
|
||||
</KhDialog>
|
||||
|
||||
@code {
|
||||
private IReadOnlyList<string>? _paths;
|
||||
private List<string> _draft = [];
|
||||
private bool _editing;
|
||||
|
||||
/// <summary>The widget.</summary>
|
||||
[Parameter, EditorRequired]
|
||||
public WidgetDefinition Definition { get; set; } = default!;
|
||||
|
||||
private IEnumerable<MenuItem> Choices => MenuCatalog.All.Where(i => i.Href != "/" && Session.CanSee(i));
|
||||
|
||||
private IReadOnlyList<MenuItem> Shortcuts =>
|
||||
_paths is null
|
||||
? [.. MenuCatalog.Sections.SelectMany(s => s.Items).Where(i => i.Href != "/" && Session.CanSee(i)).Take(6)]
|
||||
: [.. _paths.Select(p => Choices.FirstOrDefault(i => string.Equals(i.Href, p, StringComparison.OrdinalIgnoreCase))).OfType<MenuItem>()];
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await Session.EnsureLoadedAsync();
|
||||
if (Session.Actor is { } actor)
|
||||
{
|
||||
_paths = await Dashboard.GetShortcutsAsync(actor);
|
||||
}
|
||||
}
|
||||
|
||||
private void Edit()
|
||||
{
|
||||
_draft = [.. Shortcuts.Select(i => i.Href)];
|
||||
_editing = true;
|
||||
}
|
||||
|
||||
private void Toggle(string href)
|
||||
{
|
||||
if (!_draft.Remove(href) && _draft.Count < DashboardService.MaxShortcuts)
|
||||
{
|
||||
_draft.Add(href);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SaveAsync()
|
||||
{
|
||||
// Keep the menu order: the buttons read like the menu.
|
||||
var order = Choices.Select(i => i.Href).ToList();
|
||||
var chosen = _draft.OrderBy(order.IndexOf).ToList();
|
||||
if (Session.Actor is { } actor)
|
||||
{
|
||||
await Dashboard.SaveShortcutsAsync(actor, chosen);
|
||||
}
|
||||
|
||||
_paths = chosen;
|
||||
_editing = false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
@using Khaemhat.Application.Licensing
|
||||
@using Khaemhat.Core.Caching
|
||||
@using Khaemhat.Core.Common
|
||||
@using Khaemhat.Data
|
||||
@inject SystemStatusService Status
|
||||
@inject ProductVersion Version
|
||||
@inject ICacheProvider Cache
|
||||
@inject ILicenseGate Licenses
|
||||
@inject TimeProvider Clock
|
||||
|
||||
@* Stato del sistema (SPEC §10.3, administrators only): version, database, cache, licence, companies and the scheduled
|
||||
tasks of today, each with a dot that turns yellow or red when something needs a look. *@
|
||||
<KhWidget Id="@Definition.Id" Title="@T[Definition.TitleKey]" Icon="@Definition.Icon" Tight="true">
|
||||
<div class="list kh-wlist kh-status">
|
||||
<div class="li">
|
||||
<span class="kh-tone ok" aria-hidden="true"></span>
|
||||
<span class="grow">@T["Dashboard.Widgets.System.Version"]</span>
|
||||
<span class="s num" title="@Version.Full">@Version.Version@(ShortRevision.Length == 0 ? null : " (" + ShortRevision + ")")</span>
|
||||
</div>
|
||||
<div class="li">
|
||||
<span class="kh-tone ok" aria-hidden="true"></span>
|
||||
<span class="grow">@T["Dashboard.Widgets.System.Database"]</span>
|
||||
<span class="s">@(_status?.Engine == DbEngine.PostgreSql ? "PostgreSQL" : "SQLite")</span>
|
||||
</div>
|
||||
<div class="li">
|
||||
<span class="kh-tone ok" aria-hidden="true"></span>
|
||||
<span class="grow">@T["Dashboard.Widgets.System.Cache"]</span>
|
||||
<span class="s">@(Cache.IsDistributed ? T["Dashboard.Widgets.System.Redis"] : T["Dashboard.Widgets.System.LocalCache"])</span>
|
||||
</div>
|
||||
<div class="li">
|
||||
<span class="kh-tone @LicenseTone" aria-hidden="true"></span>
|
||||
<span class="grow">@T["Dashboard.Widgets.System.License"]</span>
|
||||
<span class="s">@LicenseText</span>
|
||||
</div>
|
||||
@if (_status is { } status)
|
||||
{
|
||||
<div class="li">
|
||||
<span class="kh-tone @(status.FailedCompanies > 0 ? "err" : "ok")" aria-hidden="true"></span>
|
||||
<span class="grow">@T["Dashboard.Widgets.System.Companies"]</span>
|
||||
<span class="s">@(status.FailedCompanies > 0
|
||||
? T.Format("Dashboard.Widgets.System.CompaniesFailed", status.Companies, status.FailedCompanies)
|
||||
: T.Format("Dashboard.Widgets.System.CompaniesOk", status.Companies))</span>
|
||||
</div>
|
||||
<div class="li">
|
||||
<span class="kh-tone @(status.JobsFailed > 0 ? "err" : "ok")" aria-hidden="true"></span>
|
||||
<span class="grow">@T["Dashboard.Widgets.System.Jobs"]</span>
|
||||
<span class="s">@T.Format("Dashboard.Widgets.System.JobsSummary", status.JobsSucceeded, status.JobsFailed)</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</KhWidget>
|
||||
|
||||
@code {
|
||||
private SystemStatus? _status;
|
||||
|
||||
/// <summary>The widget.</summary>
|
||||
[Parameter, EditorRequired]
|
||||
public WidgetDefinition Definition { get; set; } = default!;
|
||||
|
||||
private string ShortRevision => Version.Revision.Length > 7 ? Version.Revision[..7] : Version.Revision;
|
||||
|
||||
private LicenseState License => Licenses.Current;
|
||||
|
||||
private int? DaysLeft => License.DaysLeft(Clock.GetUtcNow().UtcDateTime);
|
||||
|
||||
private string LicenseTone => License.Status switch
|
||||
{
|
||||
LicenseStatus.Expired => "err",
|
||||
LicenseStatus.Grace => "err",
|
||||
_ when DaysLeft <= LicenseFeedSource.RenewDays => "warn",
|
||||
_ => "ok",
|
||||
};
|
||||
|
||||
private string LicenseText => License switch
|
||||
{
|
||||
{ IsTestMode: true } => T["Dashboard.Widgets.System.LicenseTest"],
|
||||
{ Status: LicenseStatus.Expired } => T["Dashboard.Widgets.System.LicenseExpired"],
|
||||
{ Status: LicenseStatus.Grace } => T["Dashboard.Widgets.System.LicenseGrace"],
|
||||
{ Kind: LicenseKind.Trial } => T.Format("Dashboard.Widgets.System.LicenseTrial", DaysLeft ?? 0),
|
||||
_ when DaysLeft is { } days => T.Format("Dashboard.Widgets.System.LicenseDays", days),
|
||||
_ => T["Dashboard.Widgets.System.LicenseUnlimited"],
|
||||
};
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnInitializedAsync() => _status = await Status.GetAsync();
|
||||
}
|
||||
@@ -2,25 +2,25 @@
|
||||
@using Khaemhat.Core.Common
|
||||
@inject ProductVersion Version
|
||||
|
||||
@* Mockups 001-003: brand panel on the left, the form on the right. Texts move to the it-IT resources in M3. *@
|
||||
@* Mockups 001-003: brand panel on the left, the form on the right. *@
|
||||
<div class="kh-auth">
|
||||
<aside class="brand">
|
||||
<aside class="side">
|
||||
<div class="brand-top">
|
||||
<img class="mark" src="icon.svg" alt="" width="56" height="56" />
|
||||
<h2>Khaemhat</h2>
|
||||
<p>Gestionale ERP + CRM per PMI italiane: documenti, magazzino, contabilità e fatturazione elettronica in un'unica applicazione web.</p>
|
||||
<h2>@T["Common.ProductName"]</h2>
|
||||
<p>@T["Auth.Brand.Tagline"]</p>
|
||||
</div>
|
||||
<ul class="features">
|
||||
<li><strong>Contabilità italiana completa</strong> prima nota, IVA, registri, bilancio CEE</li>
|
||||
<li><strong>Fatturazione elettronica</strong> SDI, conservazione, bollo, autofatture</li>
|
||||
<li><strong>CRM</strong> lead, opportunità, attività, campagne</li>
|
||||
<li><strong>Più aziende</strong> un database per azienda, backup integrati</li>
|
||||
<li><strong>@T["Auth.Brand.Feature1Title"]</strong> @T["Auth.Brand.Feature1Text"]</li>
|
||||
<li><strong>@T["Auth.Brand.Feature2Title"]</strong> @T["Auth.Brand.Feature2Text"]</li>
|
||||
<li><strong>@T["Auth.Brand.Feature3Title"]</strong> @T["Auth.Brand.Feature3Text"]</li>
|
||||
<li><strong>@T["Auth.Brand.Feature4Title"]</strong> @T["Auth.Brand.Feature4Text"]</li>
|
||||
</ul>
|
||||
</aside>
|
||||
<main class="panel">
|
||||
<main class="form-side">
|
||||
<section class="card">
|
||||
@Body
|
||||
</section>
|
||||
<footer>Khaemhat @Version.Version · <a href="https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki">Documentazione</a></footer>
|
||||
<footer>@T.Format("Auth.Brand.Footer", Version.Version) · <a href="@HelpLinks.DefaultBaseUrl">@T["Common.Documentation"]</a></footer>
|
||||
</main>
|
||||
</div>
|
||||
@@ -1,9 +1,288 @@
|
||||
@inherits LayoutComponentBase
|
||||
@using System.Text.Json
|
||||
@using Khaemhat.Application.Preferences
|
||||
@implements IAsyncDisposable
|
||||
@inject ShellSession Session
|
||||
@inject TabService Tabs
|
||||
@inject ThemeService Theme
|
||||
@inject KeyboardShortcutService Shortcuts
|
||||
@inject ToastService Toasts
|
||||
@inject DialogService Dialogs
|
||||
@inject NavigationManager Navigation
|
||||
@inject IJSRuntime Js
|
||||
|
||||
@Body
|
||||
@* The shell of SPEC §10.2 (mockups 004, 007, 013): top bar, collapsible menu, tab area, status bar. Every page opened
|
||||
becomes a tab; its component stays alive while the tab is open (hidden when another tab is active), so going back
|
||||
to a tab finds it as it was left. *@
|
||||
<PageTitle>@ActiveTitle · @T["Common.ProductName"]</PageTitle>
|
||||
<a class="skip" href="#kh-main">@T["Shell.SkipToContent"]</a>
|
||||
<div class="app @(_collapsed ? "collapsed" : null)">
|
||||
<TopBar OnSearch="() => _searchOpen = true" OnHelp="OpenHelpAsync" />
|
||||
<KhSideMenu Collapsed="_collapsed" OnToggle="ToggleMenuAsync" />
|
||||
<main class="main" id="kh-main">
|
||||
<div class="tabs-strip" role="tablist" aria-label="@T["Shell.Tabs.Label"]">
|
||||
@foreach (var tab in Tabs.Tabs)
|
||||
{
|
||||
var active = tab == Tabs.Active;
|
||||
var item = MenuCatalog.Find(tab.Path);
|
||||
var title = TitleOf(tab, item);
|
||||
<div class="wtab @(active ? "active" : null)" @key="tab.Id" role="presentation">
|
||||
<a class="tt" role="tab" href="@tab.Url.TrimStart('/')" aria-selected="@active" aria-controls="@("pane-" + tab.Id)" title="@title">
|
||||
@title
|
||||
</a>
|
||||
@if (tab.IsModified)
|
||||
{
|
||||
<span class="mod" title="@T["Shell.Tabs.Modified"]" aria-label="@T["Shell.Tabs.Modified"]">●</span>
|
||||
}
|
||||
<button type="button" class="x" aria-label="@T.Format("Shell.Tabs.Close", title)" title="@T["Shell.Tabs.CloseHint"]"
|
||||
@onclick="() => CloseTabAsync(tab)"><KhIcon Name="x" Class="sm" /></button>
|
||||
</div>
|
||||
}
|
||||
<button type="button" class="wtab add" aria-label="@T["Shell.Tabs.New"]" title="@T["Shell.Tabs.New"]" @onclick="() => _searchOpen = true">
|
||||
<KhIcon Name="plus" Class="sm" />
|
||||
</button>
|
||||
</div>
|
||||
@foreach (var tab in Tabs.Tabs)
|
||||
{
|
||||
<div class="tabpane" id="@("pane-" + tab.Id)" role="tabpanel" hidden="@(tab != Tabs.Active)" @key="tab.Id">
|
||||
<CascadingValue Value="tab" IsFixed="true">
|
||||
<div class="content">@tab.Content</div>
|
||||
</CascadingValue>
|
||||
</div>
|
||||
}
|
||||
</main>
|
||||
<KhStatusBar />
|
||||
</div>
|
||||
<KhCommandPalette Open="_searchOpen" OpenChanged="open => _searchOpen = open" OnToggleMenu="ToggleMenuAsync" />
|
||||
<KhToastHost />
|
||||
<KhDialogHost />
|
||||
<KhDrawerHost />
|
||||
|
||||
<div id="blazor-error-ui" data-nosnippet>
|
||||
Si è verificato un errore imprevisto.
|
||||
<a href="." class="reload">Ricarica</a>
|
||||
@T["Shell.Error.Unexpected"]
|
||||
<a href="." class="reload">@T["Shell.Error.Reload"]</a>
|
||||
<span class="dismiss">×</span>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
private bool _collapsed;
|
||||
private bool _searchOpen;
|
||||
private bool _unloadGuard;
|
||||
private string _savedTabs = string.Empty;
|
||||
private bool _startHandled;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await Session.EnsureLoadedAsync();
|
||||
_collapsed = Session.Preferences.MenuCollapsed ?? false;
|
||||
Tabs.Changed += OnTabsChanged;
|
||||
Session.Changed += OnSessionChanged;
|
||||
Shortcuts.ShellPressed += OnShortcutAsync;
|
||||
}
|
||||
|
||||
/// <summary>The page being shown and its route values, given by <c>Routes.razor</c>.</summary>
|
||||
[CascadingParameter]
|
||||
public RouteData? Route { get; set; }
|
||||
|
||||
private string ActiveTitle => Tabs.Active is { } tab ? TitleOf(tab, MenuCatalog.Find(tab.Path)) : T["Shell.Tabs.Untitled"];
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void OnParametersSet()
|
||||
{
|
||||
var url = "/" + Navigation.ToBaseRelativePath(Navigation.Uri);
|
||||
if (Tabs.Open(url, Route is null ? Body : PageOf(Route)) == TabOpenResult.Refused)
|
||||
{
|
||||
Toasts.Show(ToastKind.Warning, T["Shell.Tabs.LimitTitle"], T.Format("Shell.Tabs.LimitText", TabService.MaxTabs));
|
||||
if (Tabs.Active is { } active)
|
||||
{
|
||||
Navigation.NavigateTo(active.Url.TrimStart('/'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnAfterRenderAsync(bool firstRender)
|
||||
{
|
||||
if (!firstRender)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await Shortcuts.StartAsync();
|
||||
if (Session.Preferences.MenuCollapsed is null && await Js.InvokeAsync<int>("khaemhat.viewportWidth") < 1100)
|
||||
{
|
||||
_collapsed = true;
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
await ApplyStartPageAsync();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
Tabs.Changed -= OnTabsChanged;
|
||||
Session.Changed -= OnSessionChanged;
|
||||
Shortcuts.ShellPressed -= OnShortcutAsync;
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
// Body always draws the current page; a tab needs its own page, so it keeps the page type and a copy of the route values.
|
||||
private static RenderFragment PageOf(RouteData route)
|
||||
{
|
||||
var type = route.PageType;
|
||||
var values = route.RouteValues.ToArray();
|
||||
return builder =>
|
||||
{
|
||||
builder.OpenComponent(0, type);
|
||||
foreach (var (name, value) in values)
|
||||
{
|
||||
builder.AddComponentParameter(1, name, value);
|
||||
}
|
||||
|
||||
builder.CloseComponent();
|
||||
};
|
||||
}
|
||||
|
||||
private string TitleOf(KhTab tab, MenuItem? item) =>
|
||||
tab.Title ?? (item is not null && item.Href.Equals(tab.Path, StringComparison.OrdinalIgnoreCase) ? T[item.Key] : T["Shell.Tabs.Untitled"]);
|
||||
|
||||
// After sign-in the home page may give way to the start page chosen in the preferences (SPEC §10.3).
|
||||
private async Task ApplyStartPageAsync()
|
||||
{
|
||||
if (_startHandled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_startHandled = true;
|
||||
if (Tabs.Tabs.Count != 1 || Tabs.Active?.Path != "/")
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var preferences = Session.Preferences;
|
||||
string? target = null;
|
||||
if (preferences.StartPage == StartPage.Page && preferences.StartPath is { } path)
|
||||
{
|
||||
target = path;
|
||||
}
|
||||
else if (preferences.StartPage == StartPage.LastTab && await Session.ReadSettingAsync(PreferenceKeys.OpenTabs) is { } json)
|
||||
{
|
||||
target = ReadActiveTab(json);
|
||||
}
|
||||
|
||||
if (target is not null && UserPreferences.IsLocalPath(target) && TabService.PathOf(target) != "/")
|
||||
{
|
||||
Navigation.NavigateTo(target.TrimStart('/'));
|
||||
}
|
||||
}
|
||||
|
||||
private static string? ReadActiveTab(string json)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(json);
|
||||
return document.RootElement.TryGetProperty("active", out var active) ? active.GetString() : null;
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ToggleMenuAsync()
|
||||
{
|
||||
_collapsed = !_collapsed;
|
||||
await Session.SavePreferencesAsync(Session.Preferences with { MenuCollapsed = _collapsed });
|
||||
}
|
||||
|
||||
private async Task CloseTabAsync(KhTab tab)
|
||||
{
|
||||
if (tab.IsModified)
|
||||
{
|
||||
var title = TitleOf(tab, MenuCatalog.Find(tab.Path));
|
||||
var confirmed = await Dialogs.ConfirmAsync(new ConfirmRequest(
|
||||
T["Shell.Tabs.CloseModifiedTitle"], T.Format("Shell.Tabs.CloseModifiedText", title), T["Shell.Tabs.CloseModifiedConfirm"], T["Common.Cancel"], Danger: true));
|
||||
if (!confirmed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (Tabs.Close(tab) is { } next)
|
||||
{
|
||||
Navigation.NavigateTo(next.TrimStart('/'));
|
||||
}
|
||||
}
|
||||
|
||||
// F1 and the "?" open the help of the screen in a tab of its own (mockup 011); on a help page they stay there.
|
||||
private Task OpenHelpAsync()
|
||||
{
|
||||
var path = TabService.PathOf("/" + Navigation.ToBaseRelativePath(Navigation.Uri));
|
||||
if (!path.StartsWith(Khaemhat.Web.Help.WikiLibrary.BasePath, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Navigation.NavigateTo(HelpLinks.LocalFor(path));
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private async Task OnShortcutAsync(string command)
|
||||
{
|
||||
await InvokeAsync(async () =>
|
||||
{
|
||||
switch (command)
|
||||
{
|
||||
case KeyboardShortcuts.Commands.ToggleMenu:
|
||||
await ToggleMenuAsync();
|
||||
break;
|
||||
case KeyboardShortcuts.Commands.Search:
|
||||
_searchOpen = true;
|
||||
break;
|
||||
case KeyboardShortcuts.Commands.Help:
|
||||
await OpenHelpAsync();
|
||||
break;
|
||||
case KeyboardShortcuts.Commands.CloseTab when Tabs.Active is { } active:
|
||||
await CloseTabAsync(active);
|
||||
break;
|
||||
case KeyboardShortcuts.Commands.NextTab when Tabs.Neighbour(1) is { } next:
|
||||
Navigation.NavigateTo(next.Url.TrimStart('/'));
|
||||
break;
|
||||
case KeyboardShortcuts.Commands.PreviousTab when Tabs.Neighbour(-1) is { } previous:
|
||||
Navigation.NavigateTo(previous.Url.TrimStart('/'));
|
||||
break;
|
||||
}
|
||||
|
||||
StateHasChanged();
|
||||
});
|
||||
}
|
||||
|
||||
private void OnSessionChanged() => _ = InvokeAsync(StateHasChanged);
|
||||
|
||||
private void OnTabsChanged() => _ = InvokeAsync(async () =>
|
||||
{
|
||||
StateHasChanged();
|
||||
if (Tabs.HasModified != _unloadGuard)
|
||||
{
|
||||
_unloadGuard = Tabs.HasModified;
|
||||
await Js.InvokeVoidAsync("khaemhat.setUnloadGuard", _unloadGuard);
|
||||
}
|
||||
|
||||
await SaveTabsAsync();
|
||||
});
|
||||
|
||||
// The open tabs and the active one, for the "last tab" start page.
|
||||
private async Task SaveTabsAsync()
|
||||
{
|
||||
var json = JsonSerializer.Serialize(new { active = Tabs.Active?.Url, tabs = Tabs.Tabs.Select(t => t.Url).ToArray() });
|
||||
if (json == _savedTabs)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_savedTabs = json;
|
||||
await Session.SaveSettingAsync(PreferenceKeys.OpenTabs, json);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
#blazor-error-ui {
|
||||
color-scheme: light only;
|
||||
background: lightyellow;
|
||||
background: #FADEDC;
|
||||
color: #1E2733;
|
||||
bottom: 0;
|
||||
box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2);
|
||||
box-sizing: border-box;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<script type="module" src="@Assets["Components/Layout/ReconnectModal.razor.js"]"></script>
|
||||
<script type="module" src="@Assets["Components/Layout/ReconnectModal.razor.js"]"></script>
|
||||
|
||||
<dialog id="components-reconnect-modal" data-nosnippet>
|
||||
<div class="components-reconnect-container">
|
||||
@@ -7,25 +7,25 @@
|
||||
<div></div>
|
||||
</div>
|
||||
<p class="components-reconnect-first-attempt-visible">
|
||||
Rejoining the server...
|
||||
@T["Shell.Reconnect.First"]
|
||||
</p>
|
||||
<p class="components-reconnect-repeated-attempt-visible">
|
||||
Rejoin failed... trying again in <span id="components-seconds-to-next-attempt"></span> seconds.
|
||||
@T["Shell.Reconnect.Repeated"] <span id="components-seconds-to-next-attempt"></span> @T["Shell.Reconnect.Seconds"]
|
||||
</p>
|
||||
<p class="components-reconnect-failed-visible">
|
||||
Failed to rejoin.<br />Please retry or reload the page.
|
||||
@T["Shell.Reconnect.Failed"]<br />@T["Shell.Reconnect.FailedHint"]
|
||||
</p>
|
||||
<button id="components-reconnect-button" class="components-reconnect-failed-visible">
|
||||
Retry
|
||||
@T["Shell.Reconnect.Retry"]
|
||||
</button>
|
||||
<p class="components-pause-visible">
|
||||
The session has been paused by the server.
|
||||
@T["Shell.Reconnect.Paused"]
|
||||
</p>
|
||||
<p class="components-resume-failed-visible">
|
||||
Failed to resume the session.<br />Please retry or reload the page.
|
||||
@T["Shell.Reconnect.ResumeFailed"]<br />@T["Shell.Reconnect.FailedHint"]
|
||||
</p>
|
||||
<button id="components-resume-button" class="components-pause-visible components-resume-failed-visible">
|
||||
Resume
|
||||
@T["Shell.Reconnect.Resume"]
|
||||
</button>
|
||||
</div>
|
||||
</dialog>
|
||||
@@ -1,12 +1,11 @@
|
||||
@page "/accesso-negato"
|
||||
@attribute [ExcludeFromInteractiveRouting]
|
||||
@layout AuthLayout
|
||||
<KhPageTitle Text="@T["Pages.AccessDenied.PageTitle"]" />
|
||||
|
||||
<PageTitle>Khaemhat · accesso negato</PageTitle>
|
||||
|
||||
<main class="kh-construction">
|
||||
<section class="hero">
|
||||
<h1>Accesso negato</h1>
|
||||
<p class="lead">Il tuo profilo non ha il permesso per questa pagina, oppure il modulo non è compreso nella licenza.</p>
|
||||
<ul class="links"><li><a href="/">Torna alla pagina iniziale</a></li></ul>
|
||||
</section>
|
||||
</main>
|
||||
<div class="kh-message">
|
||||
<KhIcon Name="lock" Class="lg" />
|
||||
<h1>@T["Pages.AccessDenied.Title"]</h1>
|
||||
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
|
||||
<a class="btn" href="./">@T["Common.BackHome"]</a>
|
||||
</div>
|
||||
@@ -0,0 +1,76 @@
|
||||
@page "/anagrafiche/{*Rest}"
|
||||
@page "/crm/{*Rest}"
|
||||
@page "/vendite/{*Rest}"
|
||||
@page "/acquisti/{*Rest}"
|
||||
@page "/magazzino/{*Rest}"
|
||||
@page "/contabilita/{*Rest}"
|
||||
@page "/scadenzario/{*Rest}"
|
||||
@page "/fatturazione-elettronica/{*Rest}"
|
||||
@page "/cespiti/{*Rest}"
|
||||
@page "/servizi/{*Rest}"
|
||||
@page "/canali/{*Rest}"
|
||||
@page "/report/{*Rest}"
|
||||
@page "/tabelle/{*Rest}"
|
||||
@page "/automazioni/{*Rest}"
|
||||
@page "/amministrazione/{*Rest}"
|
||||
@attribute [Authorize]
|
||||
@inject ShellSession Session
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
@* The menu shows every area the licence and the permissions allow (SPEC §10.2); the areas of later milestones land
|
||||
here, which says when they arrive and what they will hold. Each real page replaces its route as it is built. *@
|
||||
<KhPageTitle Text="@Title" Icon="@(Area?.Icon)" />
|
||||
|
||||
@if (Area is null || !Session.CanSee(Area))
|
||||
{
|
||||
<div class="kh-message">
|
||||
<KhIcon Name="lock" Class="lg" />
|
||||
<h1>@T["Pages.AccessDenied.Title"]</h1>
|
||||
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
|
||||
<a class="btn" href="./">@T["Common.BackHome"]</a>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="kh-message">
|
||||
<KhIcon Name="@Area.Icon" Class="lg" />
|
||||
<h1>@Title</h1>
|
||||
<p class="lead">@(Area.Milestone is { } milestone ? T.Format("Pages.ComingSoon.Lead", milestone) : T["Pages.ComingSoon.LeadUnknown"])</p>
|
||||
@if (Area.Children.Count > 0)
|
||||
{
|
||||
<p class="muted">@T["Pages.ComingSoon.Areas"]</p>
|
||||
<ul class="kh-chips">
|
||||
@foreach (var child in Area.Children)
|
||||
{
|
||||
<li class="chip">@T[child.Key]</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
<div class="kh-actions">
|
||||
<a class="btn" href="./">@T["Common.BackHome"]</a>
|
||||
<a class="btn ghost" href="@Khaemhat.Web.Help.WikiLibrary.Href("Roadmap")">@T["Pages.ComingSoon.Roadmap"]</a>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@code {
|
||||
/// <summary>The rest of the address, after the area.</summary>
|
||||
[Parameter]
|
||||
public string? Rest { get; set; }
|
||||
|
||||
private MenuItem? Area { get; set; }
|
||||
|
||||
private MenuItem? Entry { get; set; }
|
||||
|
||||
private string Title => Entry is null ? T["Pages.ComingSoon.Title"] : T[Entry.Key];
|
||||
|
||||
// A tab keeps its page alive and has one address, so the address is read once.
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await Session.EnsureLoadedAsync();
|
||||
var path = "/" + Navigation.ToBaseRelativePath(Navigation.Uri).Split('?', '#')[0];
|
||||
Area = MenuCatalog.FindArea(path);
|
||||
Entry = MenuCatalog.Find(path);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,413 @@
|
||||
@page "/sviluppo/componenti"
|
||||
@attribute [Authorize]
|
||||
@inject IWebHostEnvironment Environment
|
||||
@inject ToastService Toasts
|
||||
@inject DialogService Dialogs
|
||||
@inject DrawerService Drawers
|
||||
@inject TimeProvider Clock
|
||||
|
||||
@* The catalog of the Kh components with all their states (issue #27): development only. *@
|
||||
<KhPageTitle Text="@T["Pages.Catalog.Title"]" Icon="grid" />
|
||||
|
||||
@if (!Environment.IsDevelopment())
|
||||
{
|
||||
<div class="kh-message">
|
||||
<h1>@T["Pages.Catalog.DevOnly"]</h1>
|
||||
<a class="btn" href="/">@T["Common.BackHome"]</a>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="phead">
|
||||
<div>
|
||||
<h1>@T["Pages.Catalog.Title"]</h1>
|
||||
<div class="sub">@T["Pages.Catalog.Subtitle"]</div>
|
||||
</div>
|
||||
<div class="grow"></div>
|
||||
<a class="btn" href="sviluppo/documento"><KhIcon Name="file" /> @T["Pages.Catalog.OpenDocument"]</a>
|
||||
</div>
|
||||
|
||||
<KhTabs Items="Sections" Active="@_section" ActiveChanged="s => _section = s" Label="@T["Pages.Catalog.Title"]" />
|
||||
|
||||
@switch (_section)
|
||||
{
|
||||
case "campi":
|
||||
<KhForm Validation="_validation" ReadOnly="_readOnly" Layout="KhFormLayout.Groups" OnValidSubmit="OnValid" @ref="_form">
|
||||
<KhFieldGroup Title="@T["Pages.Catalog.Fields.Document"]" Icon="file">
|
||||
<KhTextBox Label="@T["Pages.Catalog.Fields.Number"]" Name="number" @bind-Value="_document.Number" Required="true" Span="6" Mono="true" />
|
||||
<KhDateBox Label="@T["Pages.Catalog.Fields.Date"]" Name="date" @bind-Value="_document.Date" Required="true" Span="6" Hint="@T["Pages.Catalog.Fields.DateHint"]" />
|
||||
<KhSelect TValue="string" Label="@T["Pages.Catalog.Fields.Kind"]" Name="kind" @bind-Value="_kind" Options="Kinds" Required="true" Empty="" Span="12" />
|
||||
<KhHotlink TItem="SampleParty" Label="@T["Pages.Catalog.Fields.Party"]" Name="party" @bind-Value="_document.Party" Required="true" Span="12"
|
||||
Search="CatalogSamples.SearchAsync" CodeOf="p => p.Code" DescriptionOf="p => p.Name"
|
||||
OnRadar="Radar" OnOpen="OpenParty" OnCreate="CreateParty" Hint="@T["Pages.Catalog.Fields.PartyHint"]" />
|
||||
</KhFieldGroup>
|
||||
<KhFieldGroup Title="@T["Pages.Catalog.Fields.Conditions"]" Icon="coins">
|
||||
<KhNumberBox Label="@T["Pages.Catalog.Fields.Discount"]" Name="discount" @bind-Value="_document.Discount" Min="0" Max="100" Span="6" Hint="@T["Pages.Catalog.Fields.DiscountHint"]" />
|
||||
<KhNumberBox Label="@T["Pages.Catalog.Fields.Amount"]" Name="amount" @bind-Value="_amount" Span="6" Hint="@T["Pages.Catalog.Fields.AmountHint"]" />
|
||||
<KhTextBox Label="@T["Pages.Catalog.Fields.Email"]" Name="email" Type="email" @bind-Value="_email" Span="12" Rule="EmailRule" />
|
||||
<KhCheck Label="@T["Pages.Catalog.Fields.Split"]" Name="split" @bind-Value="_split" Span="6" />
|
||||
<KhSwitch Label="@T["Pages.Catalog.Fields.Stamp"]" Name="stamp" @bind-Value="_stamp" Span="6" />
|
||||
<KhTextArea Label="@T["Pages.Catalog.Fields.Notes"]" Name="notes" @bind-Value="_document.Notes" Span="12" Rows="2" />
|
||||
<KhTextBox Label="@T["Pages.Catalog.Fields.Disabled"]" Value="@T["Pages.Catalog.Fields.DisabledValue"]" Disabled="true" Span="12" />
|
||||
</KhFieldGroup>
|
||||
<section class="fgroup wide">
|
||||
<div class="fgh"><KhIcon Name="check-circle" /> @T["Pages.Catalog.Fields.States"]</div>
|
||||
<div class="kh-catalogbar">
|
||||
<button type="submit" class="btn primary"><KhIcon Name="check" /> @T["Pages.Catalog.Fields.Validate"]</button>
|
||||
<button type="button" class="btn" @onclick="ServerError"><KhIcon Name="alert" /> @T["Pages.Catalog.Fields.ServerError"]</button>
|
||||
<button type="button" class="btn" @onclick="() => _validation.Clear()">@T["Pages.Catalog.Fields.ClearMessages"]</button>
|
||||
<KhSwitch Label="@T["Pages.Catalog.Fields.ReadOnly"]" Value="_readOnly" ValueChanged="v => _readOnly = v" Span="0" />
|
||||
</div>
|
||||
</section>
|
||||
</KhForm>
|
||||
break;
|
||||
|
||||
case "pannelli":
|
||||
<div class="kh-catalog">
|
||||
<div class="cols cols-4">
|
||||
<KhTile Title="@T["Pages.Catalog.Panels.Revenue"]" Icon="euro" Value="@T.Money(128_450.30m)" Tone="KhTone.Accent">
|
||||
<Detail>@T["Pages.Catalog.Panels.RevenueDetail"]</Detail>
|
||||
</KhTile>
|
||||
<KhTile Title="@T["Pages.Catalog.Panels.Collected"]" Icon="check-circle" Value="@T.Money(96_120m)" Tone="KhTone.Ok" />
|
||||
<KhTile Title="@T["Pages.Catalog.Panels.Expiring"]" Icon="clock" Value="@T.Money(12_300m)" Tone="KhTone.Warning" />
|
||||
<KhTile Title="@T["Pages.Catalog.Panels.Overdue"]" Icon="alert" Value="@T.Money(4_870.55m)" Tone="KhTone.Error" Href="sviluppo/componenti" />
|
||||
</div>
|
||||
<KhStrip Items="Stats" Label="@T["Pages.Catalog.Panels.Strip"]" />
|
||||
<KhPanel Title="@T["Pages.Catalog.Panels.Panel"]" Icon="layers" LinkHref="sviluppo/componenti" LinkText="@T["Pages.Catalog.Panels.Link"]">
|
||||
<div class="kh-catalogrow">
|
||||
<KhBadge Tone="KhTone.Neutral">@T["Pages.Catalog.Panels.Draft"]</KhBadge>
|
||||
<KhBadge Tone="KhTone.Info">@T["Pages.Catalog.Panels.Sent"]</KhBadge>
|
||||
<KhBadge Tone="KhTone.Ok">@T["Pages.Catalog.Panels.Paid"]</KhBadge>
|
||||
<KhBadge Tone="KhTone.Warning">@T["Pages.Catalog.Panels.Expiring"]</KhBadge>
|
||||
<KhBadge Tone="KhTone.Error">@T["Pages.Catalog.Panels.Overdue"]</KhBadge>
|
||||
<KhBadge Tone="KhTone.Accent">@T["Pages.Catalog.Panels.Issued"]</KhBadge>
|
||||
</div>
|
||||
<div class="kh-catalogrow">
|
||||
<KhChip Icon="coins" Text="@T["Pages.Catalog.Panels.Payment"]" Value="@T["Pages.Catalog.Panels.PaymentValue"]" />
|
||||
<KhChip Icon="tag" Text="@T["Pages.Catalog.Panels.PriceList"]" Value="@T["Pages.Catalog.Panels.PriceListValue"]" Tone="KhTone.Accent" />
|
||||
<KhChip Icon="alert" Text="@T["Pages.Catalog.Panels.Credit"]" Tone="KhTone.Warning" />
|
||||
<KhChip Icon="x-circle" Text="@T["Pages.Catalog.Panels.Blocked"]" Tone="KhTone.Error" />
|
||||
@if (_filter)
|
||||
{
|
||||
<KhChip Text="@T["Pages.Catalog.Panels.Filter"]" Value="@T["Pages.Catalog.Panels.FilterValue"]" OnRemove="() => _filter = false" />
|
||||
}
|
||||
</div>
|
||||
<div class="kh-catalogrow">
|
||||
<KhMoney Value="1234.5m" /> <KhMoney Value="-87.2m" RedWhenNegative="true" /> <KhMoney Value="null" Empty="-" />
|
||||
</div>
|
||||
</KhPanel>
|
||||
</div>
|
||||
break;
|
||||
|
||||
case "navigazione":
|
||||
<div class="kh-catalog">
|
||||
<KhPanel Title="@T["Pages.Catalog.Navigation.Tabs"]" Icon="columns" Tight="true">
|
||||
<KhTabs Items="DemoTabs" Active="@_demoTab" ActiveChanged="t => _demoTab = t" Shortcuts="false" />
|
||||
<div class="pb">@T.Format("Pages.Catalog.Navigation.TabShown", DemoTabs.First(t => t.Id == _demoTab).Text)</div>
|
||||
</KhPanel>
|
||||
<KhPanel Title="@T["Pages.Catalog.Navigation.Steps"]" Icon="activity">
|
||||
<KhSteps Items="Steps" Current="_step" Label="@T["Pages.Catalog.Navigation.Steps"]" />
|
||||
<div class="cols cols-2">
|
||||
<KhVSteps Items="Steps" Current="_step" Label="@T["Pages.Catalog.Navigation.Steps"]" />
|
||||
<div class="kh-catalogrow">
|
||||
<button type="button" class="btn" disabled="@(_step == 0)" @onclick="() => _step--"><KhIcon Name="chevron-left" /> @T["Common.Back"]</button>
|
||||
<button type="button" class="btn primary" disabled="@(_step >= Steps.Count)" @onclick="() => _step++">@T["Common.Continue"] <KhIcon Name="chevron-right" /></button>
|
||||
</div>
|
||||
</div>
|
||||
</KhPanel>
|
||||
</div>
|
||||
break;
|
||||
|
||||
case "finestre":
|
||||
<div class="kh-catalog">
|
||||
<KhPanel Title="@T["Pages.Catalog.Windows.Title"]" Icon="layout">
|
||||
<div class="kh-catalogrow">
|
||||
<button type="button" class="btn" @onclick="() => _dialog = true"><KhIcon Name="layout" /> @T["Pages.Catalog.Windows.Dialog"]</button>
|
||||
<button type="button" class="btn" @onclick="() => _drawer = true"><KhIcon Name="sidebar" /> @T["Pages.Catalog.Windows.Drawer"]</button>
|
||||
<button type="button" class="btn" @onclick="ServiceDrawerAsync"><KhIcon Name="sidebar" /> @T["Pages.Catalog.Windows.DrawerService"]</button>
|
||||
<button type="button" class="btn danger" @onclick="ConfirmAsync"><KhIcon Name="trash" /> @T["Pages.Catalog.Windows.Confirm"]</button>
|
||||
</div>
|
||||
<div class="kh-catalogrow">
|
||||
@foreach (var kind in Enum.GetValues<ToastKind>())
|
||||
{
|
||||
<button type="button" class="btn" @onclick="() => ShowToast(kind)">@T[KindKey(kind)]</button>
|
||||
}
|
||||
</div>
|
||||
</KhPanel>
|
||||
</div>
|
||||
<KhDialog Open="_dialog" Title="@T["Pages.Catalog.Windows.Dialog"]" Icon="layout" OnClose="() => _dialog = false">
|
||||
<ChildContent>
|
||||
<p>@T["Pages.Catalog.Windows.DialogText"]</p>
|
||||
<KhForm Layout="KhFormLayout.Plain">
|
||||
<KhTextBox Label="@T["Pages.Catalog.Fields.Number"]" @bind-Value="_dialogText" Span="12" />
|
||||
</KhForm>
|
||||
</ChildContent>
|
||||
<Footer>
|
||||
<button type="button" class="btn" @onclick="() => _dialog = false">@T["Common.Cancel"]</button>
|
||||
<button type="button" class="btn primary" @onclick="() => _dialog = false">@T["Common.Save"]</button>
|
||||
</Footer>
|
||||
</KhDialog>
|
||||
<KhDrawer Open="_drawer" Title="@T["Pages.Catalog.Windows.Drawer"]" Icon="sidebar" OnClose="() => _drawer = false">
|
||||
<p>@T["Pages.Catalog.Windows.DrawerText"]</p>
|
||||
<KhStrip Items="Stats" />
|
||||
</KhDrawer>
|
||||
break;
|
||||
|
||||
case "griglie":
|
||||
<div class="kh-catalog">
|
||||
<KhRadar TItem="SampleCustomer" Id="catalog.customers" Columns="CustomerColumns" Source="CatalogSamples.CustomersAsync" KeyOf="c => c.Id"
|
||||
QuickFilters="CustomerQuickFilters" RowClass="CustomerRowClass" RowMenu="CustomerMenu" OnOpen="OpenCustomer"
|
||||
ExportName="clienti-di-prova" Label="@T["Pages.Catalog.Grids.Radar"]">
|
||||
<Toolbar>
|
||||
<div>
|
||||
<h2 class="kh-h2">@T["Pages.Catalog.Grids.Radar"]</h2>
|
||||
<p class="muted">@T["Pages.Catalog.Grids.RadarIntro"]</p>
|
||||
</div>
|
||||
</Toolbar>
|
||||
</KhRadar>
|
||||
<KhPanel Title="@T["Pages.Catalog.Grids.Pager"]" Icon="grid">
|
||||
<p class="muted kh-pad">@T["Pages.Catalog.Grids.PagerIntro"]</p>
|
||||
<KhGrid TItem="SampleCustomer" Columns="PagedColumns" Source="CatalogSamples.CustomersAsync" Virtual="false" PageSize="10" KeyOf="c => c.Id"
|
||||
Filters="VipOnly" Label="@T["Pages.Catalog.Grids.Pager"]" />
|
||||
</KhPanel>
|
||||
</div>
|
||||
break;
|
||||
|
||||
case "toolbar":
|
||||
<div class="kh-catalog">
|
||||
<p class="muted">@T["Pages.Catalog.Toolbar.Intro"]</p>
|
||||
<div class="kh-resizable">
|
||||
<KhIconToolbar Items="DemoToolbar" Label="@T["Ui.Toolbar.Label"]" />
|
||||
</div>
|
||||
<KhDocHead KindIcon="file" KindLabel="@T["Pages.Catalog.Head.Kind"]" Number="@_document.Number"
|
||||
PartyName="@_document.Party?.Name" PartyCode="@_document.Party?.Code" PartyLines="PartyLines"
|
||||
TotalLabel="@T["Pages.Catalog.Head.Total"]" TotalValue="@T.Money(_document.Total)" SubValues="SubValues">
|
||||
<Facts>
|
||||
<span>@T["Pages.Catalog.Fields.Date"] <b>@(_document.Date is { } d ? T.Date(d) : null)</b></span>
|
||||
<span>@T["Pages.Catalog.Head.Section"] <b>A</b></span>
|
||||
</Facts>
|
||||
<State><KhBadge Tone="KhTone.Info">@T["Pages.Catalog.Panels.Draft"]</KhBadge></State>
|
||||
<Chips>
|
||||
<KhChip Icon="coins" Text="@T["Pages.Catalog.Panels.Payment"]" Value="@T["Pages.Catalog.Panels.PaymentValue"]" />
|
||||
<KhChip Icon="tag" Text="@T["Pages.Catalog.Panels.PriceList"]" Value="@T["Pages.Catalog.Panels.PriceListValue"]" Tone="KhTone.Accent" />
|
||||
<KhChip Icon="alert" Text="@T["Pages.Catalog.Panels.Credit"]" Tone="KhTone.Warning" />
|
||||
</Chips>
|
||||
</KhDocHead>
|
||||
</div>
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@code {
|
||||
private readonly KhValidation _validation = new();
|
||||
private SampleDocument _document = default!;
|
||||
private KhForm? _form;
|
||||
private string _section = "campi";
|
||||
private string _demoTab = "righe";
|
||||
private string? _kind;
|
||||
private string? _email;
|
||||
private string? _dialogText;
|
||||
private decimal? _amount;
|
||||
private bool _split;
|
||||
private bool _stamp = true;
|
||||
private bool _readOnly;
|
||||
private bool _filter = true;
|
||||
private bool _dialog;
|
||||
private bool _drawer;
|
||||
private int _step = 1;
|
||||
|
||||
private IReadOnlyList<KhTabItem> Sections =>
|
||||
[
|
||||
new("campi", "edit", T["Pages.Catalog.Sections.Fields"]),
|
||||
new("pannelli", "layers", T["Pages.Catalog.Sections.Panels"]),
|
||||
new("navigazione", "columns", T["Pages.Catalog.Sections.Navigation"]),
|
||||
new("finestre", "layout", T["Pages.Catalog.Sections.Windows"]),
|
||||
new("griglie", "list", T["Pages.Catalog.Sections.Grids"]),
|
||||
new("toolbar", "settings", T["Pages.Catalog.Sections.Toolbar"]),
|
||||
];
|
||||
|
||||
private IReadOnlyList<KhOption<string>> Kinds =>
|
||||
[
|
||||
new("TD01", T["Pages.Catalog.Fields.KindInvoice"]),
|
||||
new("TD04", T["Pages.Catalog.Fields.KindCredit"]),
|
||||
new("TD24", T["Pages.Catalog.Fields.KindDeferred"]),
|
||||
];
|
||||
|
||||
private IReadOnlyList<KhStat> Stats =>
|
||||
[
|
||||
new(T["Pages.Catalog.Panels.Documents"], "128"),
|
||||
new(T["Pages.Catalog.Panels.Taxable"], T.Money(104_000m)),
|
||||
new(T["Pages.Catalog.Panels.Collected"], T.Money(96_120m), KhTone.Ok),
|
||||
new(T["Pages.Catalog.Panels.Overdue"], T.Money(4_870.55m), KhTone.Error),
|
||||
];
|
||||
|
||||
private IReadOnlyList<KhTabItem> DemoTabs =>
|
||||
[
|
||||
new("righe", "list", T["Ui.Record.Tabs.Lines"], 3),
|
||||
new("testata", "file", T["Ui.Record.Tabs.Header"]),
|
||||
new("allegati", "paperclip", T["Ui.Record.Tabs.Attachments"], 2),
|
||||
new("storico", "history", T["Ui.Record.Tabs.History"]),
|
||||
];
|
||||
|
||||
private IReadOnlyList<KhStep> Steps =>
|
||||
[
|
||||
new(T["Pages.Catalog.Navigation.Step1"], T["Pages.Catalog.Navigation.Step1Detail"]),
|
||||
new(T["Pages.Catalog.Navigation.Step2"], T["Pages.Catalog.Navigation.Step2Detail"]),
|
||||
new(T["Pages.Catalog.Navigation.Step3"], T["Pages.Catalog.Navigation.Step3Detail"]),
|
||||
];
|
||||
|
||||
private IReadOnlyList<string> PartyLines => [T["Pages.Catalog.Head.Address"], T["Pages.Catalog.Head.Vat"]];
|
||||
|
||||
private IReadOnlyList<KhStat> SubValues =>
|
||||
[
|
||||
new(T["Pages.Catalog.Panels.Taxable"], T.Money(_document.Taxable)),
|
||||
new(T["Pages.Catalog.Head.VatAmount"], T.Money(_document.Vat)),
|
||||
new(T["Pages.Catalog.Head.Stamp"], T.Money(2m)),
|
||||
];
|
||||
|
||||
private IReadOnlyList<ToolbarItem> DemoToolbar =>
|
||||
[
|
||||
Item("new", "plus", "Ui.Toolbar.New", "Ctrl+N") with { Priority = 0 },
|
||||
Item("save", "save", "Ui.Toolbar.Save", "Ctrl+S") with { Primary = true, Priority = 0 },
|
||||
Item("cancel", "undo", "Ui.Toolbar.Cancel", null) with { Priority = 2 },
|
||||
Item("delete", "trash", "Ui.Toolbar.Delete", "Ctrl+Delete") with { Danger = true, Priority = 3 },
|
||||
Item("copy", "copy", "Ui.Toolbar.Duplicate", null) with { Group = 1, Priority = 4 },
|
||||
Item("print", "printer", "Ui.Toolbar.Print", "Ctrl+P") with { Group = 1, Priority = 4 },
|
||||
Item("mail", "mail", "Ui.Toolbar.Email", null) with { Group = 1, Priority = 5 },
|
||||
Item("export", "download", "Ui.Toolbar.Export", null) with { Group = 1, Priority = 5 },
|
||||
Item("attachments", "paperclip", "Ui.Toolbar.Attachments", null) with { Group = 2, Count = 2, Priority = 5 },
|
||||
Item("history", "history", "Ui.Toolbar.History", null) with { Group = 2, Priority = 6 },
|
||||
Item("links", "link", "Ui.Toolbar.Links", null) with { Group = 2, Count = 1, Priority = 6 },
|
||||
Item("issue", "send", "Pages.Catalog.Toolbar.Issue", null) with { Kind = ToolbarKind.Action, Primary = true, Priority = 1 },
|
||||
Item("xml", "file-check", "Pages.Catalog.Toolbar.Xml", null) with { Kind = ToolbarKind.Action, Priority = 3 },
|
||||
Item("post", "book", "Pages.Catalog.Toolbar.Post", null) with { Kind = ToolbarKind.Action, Tone = KhTone.Ok, Priority = 3 },
|
||||
Item("ddt", "truck", "Pages.Catalog.Toolbar.Ddt", null) with { Kind = ToolbarKind.Action, Priority = 4 },
|
||||
Item("final", "lock", "Pages.Catalog.Toolbar.Final", null) with { Kind = ToolbarKind.Action, Priority = 4 },
|
||||
Item("radar", "radar", "Ui.Toolbar.Radar", "F9") with { End = true, Priority = 6 },
|
||||
Item("previous", "chevron-up", "Ui.Toolbar.Previous", "Ctrl+ArrowUp") with { End = true, Priority = 7 },
|
||||
Item("next", "chevron-down", "Ui.Toolbar.Next", "Ctrl+ArrowDown") with { End = true, Priority = 7 },
|
||||
Item("settings", "settings", "Pages.Catalog.Toolbar.Settings", null) with { Kind = ToolbarKind.Menu },
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void OnInitialized() =>
|
||||
_document = CatalogSamples.Document(DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime));
|
||||
|
||||
private ToolbarItem Item(string id, string icon, string key, string? shortcut) =>
|
||||
new(id, icon, T[key]) { Shortcut = shortcut, OnClick = () => Clicked(key) };
|
||||
|
||||
private Task Clicked(string key)
|
||||
{
|
||||
Toasts.Show(ToastKind.Info, T.Format("Pages.Catalog.Toolbar.Clicked", T[key]));
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private string? EmailRule(string? value) =>
|
||||
string.IsNullOrEmpty(value) || value.Contains('@', StringComparison.Ordinal) ? null : T["Auth.Errors.email_invalid"];
|
||||
|
||||
private void OnValid() => Toasts.Show(ToastKind.Success, T["Pages.Catalog.Fields.Valid"]);
|
||||
|
||||
private void ServerError() => _validation.Add("number", T["Pages.Catalog.Fields.NumberTaken"]);
|
||||
|
||||
private void Radar(string text) => Toasts.Show(ToastKind.Info, T.Format("Pages.Catalog.Fields.RadarOpened", text));
|
||||
|
||||
private void OpenParty(SampleParty party) => Toasts.Show(ToastKind.Info, T.Format("Pages.Catalog.Fields.PartyOpened", party.Name));
|
||||
|
||||
private void CreateParty(string text)
|
||||
{
|
||||
_document.Party = new SampleParty("C9999", text);
|
||||
Toasts.Show(ToastKind.Success, T.Format("Pages.Catalog.Fields.PartyCreated", text));
|
||||
}
|
||||
|
||||
private Task ServiceDrawerAsync() => Drawers.ShowAsync(new DrawerRequest(
|
||||
T["Pages.Catalog.Windows.DrawerService"], "sidebar",
|
||||
@<div><p>@T["Pages.Catalog.Windows.DrawerServiceText"]</p><KhStrip Items="Stats" /></div>,
|
||||
@<button type="button" class="btn primary" @onclick="Drawers.Close">@T["Common.Close"]</button>));
|
||||
|
||||
private async Task ConfirmAsync()
|
||||
{
|
||||
var yes = await Dialogs.ConfirmAsync(new(T["Ui.Record.DeleteTitle"], T["Ui.Record.DeleteText"], T["Ui.Toolbar.Delete"], T["Common.Cancel"], Danger: true));
|
||||
Toasts.Show(yes ? ToastKind.Warning : ToastKind.Info, T[yes ? "Pages.Catalog.Windows.Confirmed" : "Pages.Catalog.Windows.Cancelled"]);
|
||||
}
|
||||
|
||||
private static string KindKey(ToastKind kind) => "Pages.Catalog.Windows.Toast." + kind;
|
||||
|
||||
private static readonly IReadOnlyList<ListFilter> VipOnly = [ListFilter.Of("vip", ListFilterOperator.Equals, "true")];
|
||||
|
||||
private IReadOnlyList<KhOption<string>> KindChoices =>
|
||||
[
|
||||
new("company", T["Pages.Catalog.Grids.KindCompany"]),
|
||||
new("person", T["Pages.Catalog.Grids.KindPerson"]),
|
||||
new("public", T["Pages.Catalog.Grids.KindPublic"]),
|
||||
];
|
||||
|
||||
private IReadOnlyList<KhOption<string>> StateChoices =>
|
||||
[
|
||||
new("active", T["Pages.Catalog.Grids.StateActive"]),
|
||||
new("blocked", T["Pages.Catalog.Grids.StateBlocked"]),
|
||||
new("disabled", T["Pages.Catalog.Grids.StateDisabled"]),
|
||||
];
|
||||
|
||||
private IReadOnlyList<KhColumn<SampleCustomer>> CustomerColumns =>
|
||||
[
|
||||
new("code", T["Pages.Catalog.Grids.Code"], c => c.Code) { Kind = KhColumnKind.Code, Width = "96px" },
|
||||
new("name", T["Pages.Catalog.Grids.Name"], c => c.Name),
|
||||
new("city", T["Pages.Catalog.Grids.City"], c => c.City),
|
||||
new("province", T["Pages.Catalog.Grids.Province"], c => c.Province) { Width = "60px" },
|
||||
new("agent", T["Pages.Catalog.Grids.Agent"], c => c.Agent),
|
||||
new("kind", T["Pages.Catalog.Grids.Kind"], c => KindChoices.First(k => k.Value == c.Kind).Text) { Choices = KindChoices, Visible = false },
|
||||
new("revenue", T["Pages.Catalog.Grids.Revenue"], c => c.Revenue) { Kind = KhColumnKind.Money, Total = true },
|
||||
new("overdue", T["Pages.Catalog.Grids.Overdue"], c => c.Overdue) { Kind = KhColumnKind.Money, Total = true, CellClass = c => c.Overdue > 0 ? "neg" : null },
|
||||
new("since", T["Pages.Catalog.Grids.Since"], c => c.Since) { Kind = KhColumnKind.Date, Visible = false },
|
||||
new("vip", T["Pages.Catalog.Grids.Vip"], c => c.Vip) { Kind = KhColumnKind.Bool, Visible = false },
|
||||
new("state", T["Pages.Catalog.Grids.State"], c => StateChoices.First(k => k.Value == c.State).Text)
|
||||
{
|
||||
Choices = StateChoices,
|
||||
Template = c => @<KhBadge Tone="@(c.State switch { "active" => KhTone.Ok, "blocked" => KhTone.Error, _ => KhTone.Neutral })">@StateChoices.First(k => k.Value == c.State).Text</KhBadge>,
|
||||
},
|
||||
];
|
||||
|
||||
private IReadOnlyList<KhColumn<SampleCustomer>> PagedColumns =>
|
||||
[
|
||||
new("code", T["Pages.Catalog.Grids.Code"], c => c.Code) { Kind = KhColumnKind.Code, Width = "96px" },
|
||||
new("name", T["Pages.Catalog.Grids.Name"], c => c.Name),
|
||||
new("revenue", T["Pages.Catalog.Grids.Revenue"], c => c.Revenue) { Kind = KhColumnKind.Money, Total = true },
|
||||
new("credit", T["Pages.Catalog.Grids.Credit"], c => c.Credit) { Kind = KhColumnKind.Money, Total = true, Edit = EditCreditAsync },
|
||||
];
|
||||
|
||||
private IReadOnlyList<KhQuickFilter> CustomerQuickFilters =>
|
||||
[
|
||||
new("kind", T["Pages.Catalog.Grids.Kind"], [new(string.Empty, T["Pages.Catalog.Grids.All"]), .. KindChoices]),
|
||||
new("agent", T["Pages.Catalog.Grids.Agent"], [new(string.Empty, T["Pages.Catalog.Grids.All"]), new("M. Verdi", "M. Verdi"), new("L. Neri", "L. Neri"), new("A. Bianchi", "A. Bianchi")]),
|
||||
new("state", T["Pages.Catalog.Grids.State"], [new(string.Empty, T["Pages.Catalog.Grids.All"]), .. StateChoices]),
|
||||
];
|
||||
|
||||
private static string? CustomerRowClass(SampleCustomer customer) => customer.State == "blocked" ? "hl" : null;
|
||||
|
||||
private IEnumerable<ToolbarItem> CustomerMenu(SampleCustomer customer)
|
||||
{
|
||||
yield return new ToolbarItem("open", "external", T["Pages.Catalog.Grids.OpenCard"]) { OnClick = () => { OpenCustomer(customer); return Task.CompletedTask; } };
|
||||
yield return new ToolbarItem("copy", "copy", T["Pages.Catalog.Grids.Duplicate"]) { OnClick = () => Clicked("Pages.Catalog.Grids.Duplicate") };
|
||||
yield return new ToolbarItem("block", "lock", T["Pages.Catalog.Grids.Block"]) { Danger = true, Disabled = customer.State == "blocked", OnClick = () => Clicked("Pages.Catalog.Grids.Block") };
|
||||
}
|
||||
|
||||
private void OpenCustomer(SampleCustomer customer) => Toasts.Show(ToastKind.Info, T.Format("Pages.Catalog.Grids.Opened", customer.Name));
|
||||
|
||||
private Task<string?> EditCreditAsync(SampleCustomer customer, string text)
|
||||
{
|
||||
if (!ItalianNumber.TryParse(text, out var value) || value is null)
|
||||
{
|
||||
return Task.FromResult<string?>(T["Ui.Validation.Number"]);
|
||||
}
|
||||
|
||||
if (value < 0)
|
||||
{
|
||||
return Task.FromResult<string?>(T["Pages.Catalog.Grids.CreditInvalid"]);
|
||||
}
|
||||
|
||||
customer.Credit = Math.Round(value.Value, 2);
|
||||
return Task.FromResult<string?>(null);
|
||||
}
|
||||
|
||||
private void ShowToast(ToastKind kind) => Toasts.Show(kind, T[KindKey(kind)], T["Pages.Catalog.Windows.ToastText"]);
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
@page "/sviluppo/documento"
|
||||
@attribute [Authorize]
|
||||
@inherits DocumentPage<SampleDocument, SampleLine>
|
||||
@inject IWebHostEnvironment Environment
|
||||
@inject TimeProvider Clock
|
||||
@inject ShellSession Session
|
||||
@inject AttachmentService Attachments
|
||||
@using Khaemhat.Application.Audit
|
||||
|
||||
@* A document page built on DocumentPage (issue #29): toolbar, header, tabs with Righe first, shortcuts. Fake data,
|
||||
development only; the attachments (issue #34) are real, on the test document of the generators. *@
|
||||
<KhPageTitle Text="@T["Pages.Catalog.Document"]" Icon="file" />
|
||||
|
||||
@if (!Environment.IsDevelopment() || Record is null)
|
||||
{
|
||||
<div class="kh-message"><h1>@T["Pages.Catalog.DevOnly"]</h1></div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<KhRecordLayout Page="this">
|
||||
<Heading>
|
||||
<KhDocHead KindIcon="file" KindLabel="@T["Pages.Catalog.Head.Kind"]" Number="@Record.Number"
|
||||
PartyName="@Record.Party?.Name" PartyCode="@Record.Party?.Code" PartyLines="PartyLines"
|
||||
TotalLabel="@T["Pages.Catalog.Head.Total"]" TotalValue="@T.Money(Record.Total)" SubValues="SubValues">
|
||||
<Facts>
|
||||
<span>@T["Pages.Catalog.Fields.Date"] <b>@(Record.Date is { } d ? T.Date(d) : null)</b></span>
|
||||
</Facts>
|
||||
<State>
|
||||
@if (Record.Issued)
|
||||
{
|
||||
<KhBadge Tone="KhTone.Accent">@T["Pages.Catalog.Panels.Issued"]</KhBadge>
|
||||
}
|
||||
else
|
||||
{
|
||||
<KhBadge Tone="KhTone.Info">@T["Pages.Catalog.Panels.Draft"]</KhBadge>
|
||||
}
|
||||
@if (IsModified)
|
||||
{
|
||||
<KhBadge Tone="KhTone.Warning">@T["Pages.Catalog.Modified"]</KhBadge>
|
||||
}
|
||||
</State>
|
||||
<Chips>
|
||||
<KhChip Icon="coins" Text="@T["Pages.Catalog.Panels.Payment"]" Value="@T["Pages.Catalog.Panels.PaymentValue"]" />
|
||||
</Chips>
|
||||
</KhDocHead>
|
||||
</Heading>
|
||||
<ChildContent>
|
||||
@switch (ActiveTab)
|
||||
{
|
||||
case TabIds.Lines:
|
||||
<KhLinesGrid TLine="SampleLine" @ref="_lines" Lines="Record.Lines" Columns="LineColumns" NewLine="() => new SampleLine()" IsEmpty="l => l.IsEmpty"
|
||||
IsDescriptive="l => l.Descriptive" NewDescriptive="() => new SampleLine { Descriptive = true }" DescriptionColumn="LineColumns[1]"
|
||||
ReadOnly="IsReadOnly" OnChanged="MarkModified" Label="@T["Pages.Catalog.Grids.Lines"]" />
|
||||
break;
|
||||
|
||||
case TabIds.Header:
|
||||
<KhForm Validation="Validation" ReadOnly="IsReadOnly" Layout="KhFormLayout.Groups" @ref="Form">
|
||||
<KhFieldGroup Title="@T["Pages.Catalog.Fields.Document"]" Icon="file">
|
||||
<KhTextBox Label="@T["Pages.Catalog.Fields.Number"]" Name="number" Value="@Record.Number" ValueChanged="v => Change(() => Record.Number = v ?? string.Empty)" Required="true" Mono="true" />
|
||||
<KhDateBox Label="@T["Pages.Catalog.Fields.Date"]" Name="date" Value="Record.Date" ValueChanged="v => Change(() => Record.Date = v)" Required="true" />
|
||||
<KhHotlink TItem="SampleParty" Label="@T["Pages.Catalog.Fields.Party"]" Name="party" Value="Record.Party" ValueChanged="v => Change(() => Record.Party = v)"
|
||||
Required="true" Span="12" Search="CatalogSamples.SearchAsync" CodeOf="p => p.Code" DescriptionOf="p => p.Name" />
|
||||
</KhFieldGroup>
|
||||
<KhFieldGroup Title="@T["Pages.Catalog.Fields.Conditions"]" Icon="coins">
|
||||
<KhNumberBox Label="@T["Pages.Catalog.Fields.Discount"]" Name="discount" Value="Record.Discount" ValueChanged="v => Change(() => Record.Discount = v)" Min="0" Max="100" />
|
||||
<KhTextArea Label="@T["Pages.Catalog.Fields.Notes"]" Name="notes" Value="@Record.Notes" ValueChanged="v => Change(() => Record.Notes = v)" Span="12" Rows="2" />
|
||||
</KhFieldGroup>
|
||||
</KhForm>
|
||||
break;
|
||||
|
||||
case TabIds.Attachments:
|
||||
<div class="kh-tab-body"><KhAttachmentList Entity="@DemoDocument.Entity" EntityId="SampleId" OnCountChanged="SetAttachments" /></div>
|
||||
break;
|
||||
|
||||
case TabIds.History:
|
||||
<div class="kh-tab-body"><KhAuditList Items="History" FieldName="FieldLabel" /></div>
|
||||
break;
|
||||
|
||||
default:
|
||||
<div class="pb"><p class="muted">@T["Pages.Catalog.TabPlaceholder"]</p></div>
|
||||
break;
|
||||
}
|
||||
</ChildContent>
|
||||
</KhRecordLayout>
|
||||
|
||||
<KhDrawer Open="_drawer" Title="@T["Ui.Attachments.Title"]" Icon="paperclip" Wide="true" OnClose="() => _drawer = false">
|
||||
<KhAttachmentList Entity="@DemoDocument.Entity" EntityId="SampleId" OnCountChanged="SetAttachments" />
|
||||
</KhDrawer>
|
||||
|
||||
<KhRadarDialog TItem="SampleItem" Id="catalog.items" Open="_lookupLine is not null" Title="@T["Pages.Catalog.Grids.ItemRadar"]" Columns="ItemColumns"
|
||||
Source="CatalogSamples.ItemsAsync" KeyOf="i => i.Code" InitialSearch="@_lookupLine?.Code" OnPick="PickItemAsync" OnClose="() => _lookupLine = null"
|
||||
OnCreate="CreateItem" />
|
||||
}
|
||||
|
||||
@code {
|
||||
/// <summary>The test document the attachments belong to.</summary>
|
||||
public const long SampleId = 1;
|
||||
|
||||
private int _saved;
|
||||
private int _attachments;
|
||||
private bool _drawer;
|
||||
private KhLinesGrid<SampleLine>? _lines;
|
||||
private SampleLine? _lookupLine;
|
||||
private TaskCompletionSource? _lookupDone;
|
||||
private IReadOnlyList<KhLineColumn<SampleLine>>? _lineColumns;
|
||||
|
||||
private IReadOnlyList<KhLineColumn<SampleLine>> LineColumns => _lineColumns ??=
|
||||
[
|
||||
new("code", T["Pages.Catalog.Grids.Item"], l => l.Code) { Kind = KhColumnKind.Code, Width = "120px", SetText = SetCode, Lookup = LookupAsync },
|
||||
new("description", T["Pages.Catalog.Grids.Description"], l => l.Description) { SetText = (l, v) => l.Description = v ?? string.Empty },
|
||||
new("unit", T["Pages.Catalog.Grids.Unit"], l => l.Unit) { Width = "56px", SetText = (l, v) => l.Unit = v?.ToUpperInvariant() },
|
||||
new("quantity", T["Pages.Catalog.Grids.Quantity"], l => l.Quantity) { Kind = KhColumnKind.Number, Width = "96px", SetNumber = (l, v) => l.Quantity = v },
|
||||
new("price", T["Pages.Catalog.Grids.Price"], l => l.Price) { Kind = KhColumnKind.Money, Width = "110px", SetNumber = (l, v) => l.Price = v },
|
||||
new("discount", T["Pages.Catalog.Grids.Discount"], l => l.Discount) { Kind = KhColumnKind.Number, Width = "80px", SetNumber = (l, v) => l.Discount = v },
|
||||
new("amount", T["Pages.Catalog.Grids.Amount"], l => l.Descriptive || l.IsEmpty ? null : l.Amount) { Kind = KhColumnKind.Money, Width = "120px" },
|
||||
];
|
||||
|
||||
private IReadOnlyList<KhColumn<SampleItem>> ItemColumns =>
|
||||
[
|
||||
new("code", T["Pages.Catalog.Grids.Item"], i => i.Code) { Kind = KhColumnKind.Code, Width = "100px" },
|
||||
new("description", T["Pages.Catalog.Grids.Description"], i => i.Description),
|
||||
new("unit", T["Pages.Catalog.Grids.Unit"], i => i.Unit) { Width = "56px" },
|
||||
new("stock", T["Pages.Catalog.Grids.Quantity"], i => i.Stock) { Kind = KhColumnKind.Number, Decimals = 0 },
|
||||
new("price", T["Pages.Catalog.Grids.Price"], i => i.Price) { Kind = KhColumnKind.Money },
|
||||
];
|
||||
|
||||
// Typing a known code fills description, unit and price, as a real item would.
|
||||
private static void SetCode(SampleLine line, string? code)
|
||||
{
|
||||
line.Code = code?.ToUpperInvariant() ?? string.Empty;
|
||||
if (CatalogSamples.ItemByCode(code) is { } item)
|
||||
{
|
||||
Fill(line, item);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Fill(SampleLine line, SampleItem item)
|
||||
{
|
||||
line.Code = item.Code;
|
||||
line.Description = item.Description;
|
||||
line.Unit = item.Unit;
|
||||
line.Price = item.Price;
|
||||
line.Quantity ??= 1;
|
||||
}
|
||||
|
||||
private Task LookupAsync(SampleLine line)
|
||||
{
|
||||
_lookupLine = line;
|
||||
_lookupDone = new TaskCompletionSource();
|
||||
StateHasChanged();
|
||||
return _lookupDone.Task;
|
||||
}
|
||||
|
||||
private async Task PickItemAsync(SampleItem item)
|
||||
{
|
||||
if (_lookupLine is { } line)
|
||||
{
|
||||
Fill(line, item);
|
||||
_lookupLine = null;
|
||||
_lookupDone?.TrySetResult();
|
||||
MarkModified();
|
||||
await Task.Yield();
|
||||
if (_lines is not null)
|
||||
{
|
||||
await _lines.FocusCellAsync(line, "quantity");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void CreateItem(string text)
|
||||
{
|
||||
Toasts.Show(ToastKind.Info, T.Format("Pages.Catalog.Grids.ItemCreated", text));
|
||||
_lookupLine = null;
|
||||
_lookupDone?.TrySetResult();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override IReadOnlyList<KhTabItem> Tabs => Record is null ? [] : StandardTabs(attachments: _attachments, links: 1);
|
||||
|
||||
/// <inheritdoc />
|
||||
public override bool IsReadOnly => Record?.Issued == true;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override IList<SampleLine> Lines => Record?.Lines ?? [];
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string? NewUrl => "sviluppo/documento";
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override int? AttachmentCount => _attachments;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override bool CanMove => true;
|
||||
|
||||
private IReadOnlyList<string> PartyLines => [T["Pages.Catalog.Head.Address"], T["Pages.Catalog.Head.Vat"]];
|
||||
|
||||
private IReadOnlyList<KhStat> SubValues => Record is null ? [] :
|
||||
[
|
||||
new(T["Pages.Catalog.Panels.Taxable"], T.Money(Record.Taxable)),
|
||||
new(T["Pages.Catalog.Head.VatAmount"], T.Money(Record.Vat)),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void OnInitialized()
|
||||
{
|
||||
base.OnInitialized();
|
||||
Record = CatalogSamples.Document(Today);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await Session.EnsureLoadedAsync();
|
||||
if (Session.Actor is { CompanyCode: { } company } actor && Session.Permissions.Allows(AttachmentService.ReadPermission))
|
||||
{
|
||||
_attachments = await Attachments.CountAsync(actor, company, DemoDocument.Entity, SampleId);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override Task AttachmentsAsync()
|
||||
{
|
||||
// Toolbar commands are plain callbacks: render the page for the panel.
|
||||
_drawer = !_drawer;
|
||||
StateHasChanged();
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override Task PrintAsync()
|
||||
{
|
||||
Navigation.NavigateTo("sviluppo/documento/stampa");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private void SetAttachments(int count) => _attachments = count;
|
||||
|
||||
// A pretend history: the sample document is not saved anywhere.
|
||||
private IReadOnlyList<AuditItem> History =>
|
||||
[
|
||||
new(3, Clock.GetUtcNow().UtcDateTime.AddMinutes(-12), AuditAction.Update, Session.Actor?.UserName,
|
||||
[new("Discount", "0", "5"), new("Notes", null, T["Pages.Catalog.Fields.Notes"])]),
|
||||
new(2, Clock.GetUtcNow().UtcDateTime.AddHours(-3), AuditAction.Update, "anna", [new("Number", "2026/0417", Record?.Number)]),
|
||||
new(1, Clock.GetUtcNow().UtcDateTime.AddDays(-1), AuditAction.Insert, "anna", []),
|
||||
];
|
||||
|
||||
private string? FieldLabel(string field) => field switch
|
||||
{
|
||||
"Discount" => T["Pages.Catalog.Fields.Discount"],
|
||||
"Notes" => T["Pages.Catalog.Fields.Notes"],
|
||||
"Number" => T["Pages.Catalog.Fields.Number"],
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override IEnumerable<ToolbarItem> ContextActions()
|
||||
{
|
||||
yield return new ToolbarItem("issue", "send", T["Pages.Catalog.Toolbar.Issue"])
|
||||
{
|
||||
Kind = ToolbarKind.Action, Primary = true, Disabled = IsReadOnly || IsModified, OnClick = IssueAsync,
|
||||
};
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override Task<bool> SaveCoreAsync()
|
||||
{
|
||||
// A pretend rule of the service: the number must keep the year prefix.
|
||||
if (Record is null || !Record.Number.StartsWith("2026/", StringComparison.Ordinal))
|
||||
{
|
||||
Validation.Add("number", T["Pages.Catalog.Fields.NumberTaken"]);
|
||||
return Task.FromResult(false);
|
||||
}
|
||||
|
||||
_saved++;
|
||||
return Task.FromResult(true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override Task ReloadAsync()
|
||||
{
|
||||
Record = CatalogSamples.Document(Today);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override Task MoveAsync(int direction)
|
||||
{
|
||||
Toasts.Show(ToastKind.Info, T[direction < 0 ? "Ui.Toolbar.Previous" : "Ui.Toolbar.Next"]);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override Task RadarAsync()
|
||||
{
|
||||
Toasts.Show(ToastKind.Info, T["Ui.Toolbar.Radar"]);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
|
||||
|
||||
private void Change(Action change)
|
||||
{
|
||||
change();
|
||||
MarkModified();
|
||||
}
|
||||
|
||||
private Task IssueAsync()
|
||||
{
|
||||
if (Record is not null)
|
||||
{
|
||||
Record.Issued = true;
|
||||
Toasts.Show(ToastKind.Success, T["Pages.Catalog.Panels.Issued"]);
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
@page "/sviluppo/documento/stampa"
|
||||
@attribute [Authorize]
|
||||
@using System.Globalization
|
||||
@using Khaemhat.Application.Security
|
||||
@using Khaemhat.Web.Hosting
|
||||
@inject IWebHostEnvironment Environment
|
||||
@inject ShellSession Session
|
||||
@inject FileGenerationService Generation
|
||||
@inject ToastService Toasts
|
||||
@inject TimeProvider Clock
|
||||
|
||||
@* The print preview of the test document (issue #34, mockup 025): the same lines the PDF generator writes, as an A4
|
||||
sheet in HTML; Stampa prints the sheet only, the PDF comes from DemoPdfGenerator. Development only. *@
|
||||
<KhPageTitle Text="@T["Pages.Print.Title"]" Icon="printer" />
|
||||
|
||||
@if (!Environment.IsDevelopment())
|
||||
{
|
||||
<div class="kh-message"><h1>@T["Pages.Catalog.DevOnly"]</h1></div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="phead">
|
||||
<div>
|
||||
<div class="crumbs">@T["Pages.Print.Crumb"] › <b>@T["Pages.Print.Title"]</b></div>
|
||||
<h1>@T.Format("Pages.Print.Heading", DemoDocument.Title, Number)</h1>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<KhPrintPreview PdfUrl="@PdfUrl(false)" PdfDownloadUrl="@PdfUrl(true)" OnSaveAttachment="SaveAsync" Saving="_saving">
|
||||
<div class="kh-sheet-head">
|
||||
<div>
|
||||
<div class="kh-sheet-company">@(Session.Company?.Name ?? Company)</div>
|
||||
<div class="kh-sheet-muted">@T.Format("Pages.Print.CompanyLine", Company)</div>
|
||||
</div>
|
||||
<div class="kh-sheet-title">
|
||||
<div class="k">@DemoDocument.Title</div>
|
||||
<div class="n">@T.Format("Pages.Print.Number", Number, T.Date(Today))</div>
|
||||
</div>
|
||||
</div>
|
||||
<p class="kh-sheet-intro">@T.Format("Pages.Print.Intro", Company, Session.Actor?.UserName ?? string.Empty)</p>
|
||||
<table class="kh-sheet-table">
|
||||
<thead>
|
||||
<tr>
|
||||
@for (var i = 0; i < DemoDocument.Headers.Count; i++)
|
||||
{
|
||||
<th class="@(i >= 2 ? "num" : null)">@DemoDocument.Headers[i]</th>
|
||||
}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var line in DemoDocument.Lines)
|
||||
{
|
||||
<tr>
|
||||
<td class="mono">@line.Code</td>
|
||||
<td>@line.Description</td>
|
||||
<td class="num">@line.Quantity.ToString("#,##0.##", T.Culture)</td>
|
||||
<td class="num">@DemoDocument.Euro(line.UnitPrice, T.Culture)</td>
|
||||
<td class="num">@DemoDocument.Euro(DemoDocument.Amount(line), T.Culture)</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr>
|
||||
<td colspan="4" class="num">@T["Pages.Print.Total"]</td>
|
||||
<td class="num"><b>@DemoDocument.Euro(DemoDocument.Total, T.Culture)</b></td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
<p class="kh-sheet-foot">@T["Pages.Print.Footer"]</p>
|
||||
</KhPrintPreview>
|
||||
}
|
||||
|
||||
@code {
|
||||
private bool _saving;
|
||||
|
||||
private static string Number => SampleDocumentPage.SampleId.ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
private string Company => Session.Actor?.CompanyCode ?? string.Empty;
|
||||
|
||||
private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override Task OnInitializedAsync() => Session.EnsureLoadedAsync();
|
||||
|
||||
private string? PdfUrl(bool download) =>
|
||||
Session.Actor?.CompanyCode is null ? null : FileEndpoints.Generated(DemoDocument.Entity, SampleDocumentPage.SampleId, DemoPdfGenerator.GeneratorCode, download);
|
||||
|
||||
private async Task SaveAsync()
|
||||
{
|
||||
if (Session.Actor is not { CompanyCode: { } company } actor)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_saving = true;
|
||||
try
|
||||
{
|
||||
var saved = await Generation.GenerateAsync(actor, company, DemoDocument.Entity, SampleDocumentPage.SampleId, DemoPdfGenerator.GeneratorCode);
|
||||
Toasts.Show(ToastKind.Success, T["Ui.Attachments.GeneratedToast"], saved.FileName);
|
||||
}
|
||||
catch (Exception ex) when (ex is AccessDeniedException or ValidationFailedException)
|
||||
{
|
||||
Toasts.Show(ToastKind.Error, T["Ui.Print.SaveAttachment"], T["Ui.Attachments.Denied"]);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_saving = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,21 @@
|
||||
@page "/Error"
|
||||
@attribute [ExcludeFromInteractiveRouting]
|
||||
@layout AuthLayout
|
||||
@using System.Diagnostics
|
||||
|
||||
@* The error code shown to people is the trace id, the same one written in the log (SPEC §9.5). *@
|
||||
<PageTitle>Khaemhat · errore</PageTitle>
|
||||
<PageTitle>@T["Pages.Error.PageTitle"] · @T["Common.ProductName"]</PageTitle>
|
||||
|
||||
<main class="kh-construction">
|
||||
<section class="hero">
|
||||
<h1>Si è verificato un errore</h1>
|
||||
<p class="lead">La richiesta non è stata completata. Se il problema si ripete, comunica all'amministratore il codice qui sotto.</p>
|
||||
@if (!string.IsNullOrEmpty(TraceId))
|
||||
{
|
||||
<p class="build">Codice errore: <code>@TraceId</code></p>
|
||||
}
|
||||
<ul class="links"><li><a href="/">Torna alla pagina iniziale</a></li></ul>
|
||||
</section>
|
||||
</main>
|
||||
<div class="kh-message">
|
||||
<KhIcon Name="alert" Class="lg" />
|
||||
<h1>@T["Pages.Error.Title"]</h1>
|
||||
<p class="lead">@T["Pages.Error.Lead"]</p>
|
||||
@if (!string.IsNullOrEmpty(TraceId))
|
||||
{
|
||||
<p class="muted">@T["Pages.Error.Code"] <code>@TraceId</code></p>
|
||||
}
|
||||
<a class="btn" href="./">@T["Common.BackHome"]</a>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
[CascadingParameter]
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
@page "/aiuto"
|
||||
@page "/aiuto/{Name}"
|
||||
@attribute [Authorize]
|
||||
@using Khaemhat.Application.Configuration
|
||||
@using Khaemhat.Web.Help
|
||||
@inject WikiLibrary Wiki
|
||||
@inject KhaemhatOptions Options
|
||||
|
||||
@* The help of SPEC §17 (mockup 011): the wiki page of the screen, from the copy shipped with the application, with
|
||||
the wiki index at the side, "Apri nel wiki" for the online version and "Segnala un problema". F1 and the "?" of the
|
||||
top bar open it on the page of the current screen. *@
|
||||
<KhPageTitle Text="@T.Format("Pages.Help.TabTitle", Current?.Title ?? T["Pages.Help.Title"])" Icon="help" />
|
||||
|
||||
<div class="phead">
|
||||
<div>
|
||||
<div class="crumbs">@T["Pages.Help.Crumb"]@if (Section is { } section){<text> › @section.Title</text>} › <b>@(Current?.Title ?? Name)</b></div>
|
||||
<h1>@T.Format("Pages.Help.Heading", Current?.Title ?? T["Pages.Help.Title"])</h1>
|
||||
</div>
|
||||
<div class="grow"></div>
|
||||
<a class="btn" href="@OnlineUrl" target="_blank" rel="noopener"><KhIcon Name="external" /> @T["Pages.Help.OpenWiki"]</a>
|
||||
@if (IssuesUrl is { } issues)
|
||||
{
|
||||
<a class="btn" href="@issues" target="_blank" rel="noopener"><KhIcon Name="alert" /> @T["Pages.Help.Report"]</a>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="kh-help">
|
||||
<nav class="panel kh-help-index" aria-label="@T["Pages.Help.Index"]">
|
||||
@foreach (var group in Wiki.Sidebar)
|
||||
{
|
||||
<div class="kh-help-group">@group.Title</div>
|
||||
@foreach (var (page, label) in group.Pages)
|
||||
{
|
||||
<a class="kh-help-link @(string.Equals(page, PageName, StringComparison.OrdinalIgnoreCase) ? "on" : null)" href="@WikiLibrary.Href(page)"
|
||||
aria-current="@(string.Equals(page, PageName, StringComparison.OrdinalIgnoreCase) ? "page" : null)">
|
||||
<KhIcon Name="file" Class="sm" /> @label
|
||||
</a>
|
||||
}
|
||||
}
|
||||
</nav>
|
||||
<article class="panel kh-help-body">
|
||||
@if (!Wiki.IsAvailable)
|
||||
{
|
||||
<div class="callout warn"><KhIcon Name="alert" /> <span>@T["Pages.Help.Missing"]</span></div>
|
||||
}
|
||||
else if (Current is null)
|
||||
{
|
||||
<div class="callout warn"><KhIcon Name="alert" /> <span>@T.Format("Pages.Help.NotFound", Name ?? string.Empty)</span></div>
|
||||
}
|
||||
else
|
||||
{
|
||||
@((MarkupString)Current.Html)
|
||||
}
|
||||
</article>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
/// <summary>The wiki page, such as <c>Interfaccia-e-scorciatoie</c>; empty for the wiki home.</summary>
|
||||
[Parameter]
|
||||
public string? Name { get; set; }
|
||||
|
||||
private string PageName => string.IsNullOrWhiteSpace(Name) ? "Home" : Name;
|
||||
|
||||
private WikiPage? Current => Wiki.Get(PageName);
|
||||
|
||||
private WikiSection? Section => Wiki.Sidebar.FirstOrDefault(s => s.Pages.Any(p => string.Equals(p.Page, PageName, StringComparison.OrdinalIgnoreCase)));
|
||||
|
||||
private string BaseUrl => HelpLinks.BaseUrl(Options.HelpUrl);
|
||||
|
||||
private string OnlineUrl => BaseUrl + (Current?.Name ?? PageName);
|
||||
|
||||
private string? IssuesUrl => HelpLinks.IssuesUrl(BaseUrl);
|
||||
}
|
||||
@@ -1,42 +1,368 @@
|
||||
@page "/"
|
||||
@attribute [Authorize]
|
||||
@using Khaemhat.Application.Licensing
|
||||
@using Khaemhat.Core.Common
|
||||
@inject ProductVersion Version
|
||||
@inject ILicenseGate Licenses
|
||||
@using Khaemhat.Application.Modules
|
||||
@using Khaemhat.Core.Security
|
||||
@using Khaemhat.Application.Instance
|
||||
@inject ShellSession Session
|
||||
@inject DashboardService Dashboard
|
||||
@inject ToastService Toasts
|
||||
@inject TimeProvider Clock
|
||||
|
||||
@* Placeholder until the shell of M3 (SPEC §20): who is signed in, in which company, with which licence. Texts move to
|
||||
the it-IT resources with the localization of M3. *@
|
||||
<PageTitle>Khaemhat</PageTitle>
|
||||
@* The home page (SPEC §10.3, mockups 004 and 006): the widget dashboard, with the Personalizza panel to switch widgets
|
||||
on and off, order and size them, choose the start page and, for whoever manages the company, the default of a
|
||||
role. With the dashboard switched off, the areas the user can open. *@
|
||||
<KhPageTitle Text="@T["Pages.Home.Title"]" Icon="home" />
|
||||
|
||||
<main class="kh-construction">
|
||||
<section class="hero">
|
||||
<img class="mark" src="icon.svg" alt="" width="96" height="96" />
|
||||
<h1>Khaemhat <span class="ver">v @Version.MajorMinor</span></h1>
|
||||
<AuthorizeView>
|
||||
<p class="lead">Benvenuto, <strong>@context.User.FindFirst(SessionCookie.DisplayNameClaim)?.Value</strong>
|
||||
(@LevelLabel(context.User.FindFirst(SessionCookie.LevelClaim)?.Value))
|
||||
@if (context.User.FindFirst(SessionCookie.CompanyClaim)?.Value is { } company)
|
||||
<div class="kh-home @(_customizing ? "kh-with-drawer" : null)">
|
||||
<div class="phead">
|
||||
<div>
|
||||
<h1>@Greeting</h1>
|
||||
<div class="sub">@T.Format("Pages.Home.Today", Today)</div>
|
||||
</div>
|
||||
<div class="grow"></div>
|
||||
@if (_loaded && ShowDashboard)
|
||||
{
|
||||
<div class="actions">
|
||||
<button type="button" class="btn @(_customizing ? "primary" : null)" aria-pressed="@(_customizing ? "true" : "false")"
|
||||
@onclick="ToggleCustomize"><KhIcon Name="layout" /> @T["Dashboard.Customize"]</button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (!_loaded)
|
||||
{
|
||||
<p class="muted">@T["Dashboard.Feed.Loading"]</p>
|
||||
}
|
||||
else if (ShowDashboard)
|
||||
{
|
||||
@if (_layout.Widgets.Count == 0)
|
||||
{
|
||||
<div class="callout info"><KhIcon Name="info" /> <span>@T["Dashboard.Empty"]</span></div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<KhWidgetGrid Layout="_layout" Editing="_customizing" LayoutChanged="ChangeLayoutAsync" Label="@T["Dashboard.Grid"]">
|
||||
@foreach (var placement in _layout.Widgets)
|
||||
{
|
||||
<span> · azienda <strong>@company</strong></span>
|
||||
if (WidgetCatalog.Find(placement.Id) is { } definition)
|
||||
{
|
||||
<DashboardWidget @key="placement.Id" Definition="definition" />
|
||||
}
|
||||
}
|
||||
</p>
|
||||
</AuthorizeView>
|
||||
<p class="state">Accesso, utenti, ruoli, licenze e log sono pronti; le schermate di lavoro arrivano con l'interfaccia della milestone 3.
|
||||
Licenza: @(Licenses.Current.Kind == LicenseKind.Trial ? "prova" : Licenses.Current.Licensee) · moduli @string.Join(", ", Licenses.Current.Modules.Order())</p>
|
||||
<form method="post" action="/logout" class="links">
|
||||
<AntiforgeryToken />
|
||||
<button type="submit" class="kh-btn ghost">Esci</button>
|
||||
</form>
|
||||
<p class="build">Versione @Version.Full</p>
|
||||
</section>
|
||||
</main>
|
||||
</KhWidgetGrid>
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="callout info kh-home-off">
|
||||
<KhIcon Name="info" />
|
||||
<span class="grow">@T["Dashboard.Off"]</span>
|
||||
<button type="button" class="btn sm" @onclick="() => ChangeShowAsync(true)">@T["Dashboard.ShowAgain"]</button>
|
||||
</div>
|
||||
|
||||
<div class="cols cols-3 kh-home-tiles">
|
||||
<div class="tile acc">
|
||||
<div class="t"><KhIcon Name="key" Class="sm" /> @T["Pages.Home.LicenseTile"]</div>
|
||||
<div class="v">@(License.Kind == LicenseKind.Trial ? T["Pages.Home.LicenseTrial"] : T["Pages.Home.LicenseFull"])</div>
|
||||
<div class="d">@LicenseDetail</div>
|
||||
</div>
|
||||
<div class="tile">
|
||||
<div class="t"><KhIcon Name="layers" Class="sm" /> @T["Pages.Home.ModulesTile"]</div>
|
||||
<div class="v">@T.Format("Pages.Home.ModulesText", License.Modules.Count, ModuleRegistry.Default.Modules.Count)</div>
|
||||
<div class="d">@(License.Modules.Count == 0 ? T["Pages.Home.ModulesNone"] : string.Join(" · ", License.Modules.Order(StringComparer.Ordinal)))</div>
|
||||
</div>
|
||||
<div class="tile">
|
||||
<div class="t"><KhIcon Name="building" Class="sm" /> @T["Pages.Home.CompanyTile"]</div>
|
||||
<div class="v">@(Session.Company?.Name ?? T["Pages.Home.CompanyNone"])</div>
|
||||
<div class="d">@Session.Company?.Code</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section class="panel" aria-labelledby="kh-home-areas">
|
||||
<div class="ph"><KhIcon Name="grid" /> <span id="kh-home-areas">@T["Pages.Home.AreasTitle"]</span></div>
|
||||
<div class="pb">
|
||||
<p class="muted">@T["Pages.Home.AreasHint"]</p>
|
||||
<div class="kh-areas">
|
||||
@foreach (var area in Areas)
|
||||
{
|
||||
<a class="kh-area" href="@area.Href.TrimStart('/')">
|
||||
<span class="ico-box"><KhIcon Name="@area.Icon" /></span>
|
||||
<span class="grow">@T[area.Key]</span>
|
||||
@if (area.Milestone is { } milestone)
|
||||
{
|
||||
<span class="badge gray">@T.Format("Pages.Home.Coming", milestone)</span>
|
||||
}
|
||||
</a>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
}
|
||||
</div>
|
||||
|
||||
<KhDrawer Open="_customizing" Title="@T["Dashboard.CustomizeTitle"]" Icon="layout" OnClose="CloseCustomize">
|
||||
<ChildContent>
|
||||
<section class="kh-dsec" aria-labelledby="kh-dash-start-h">
|
||||
<h3 class="fgh" id="kh-dash-start-h"><KhIcon Name="home" /> @T["Dashboard.Panel.Start"]</h3>
|
||||
<div class="f">
|
||||
<label for="kh-dash-start">@T["Dashboard.Panel.StartPage"]</label>
|
||||
<select id="kh-dash-start" class="kh-input" value="@StartValue" @onchange="ChangeStartAsync">
|
||||
<option value="@nameof(StartPage.Dashboard)">@T["Pages.Profile.Start.Dashboard"]</option>
|
||||
<option value="@nameof(StartPage.LastTab)">@T["Pages.Profile.Start.LastTab"]</option>
|
||||
@foreach (var item in StartChoices)
|
||||
{
|
||||
<option value="@item.Href">@T[item.Key]</option>
|
||||
}
|
||||
</select>
|
||||
</div>
|
||||
<KhSwitchRow Label="@T["Dashboard.Panel.Show"]" Value="Session.Preferences.ShowDashboard" ValueChanged="ChangeShowAsync" />
|
||||
</section>
|
||||
|
||||
<section class="kh-dsec" aria-labelledby="kh-dash-widgets-h">
|
||||
<h3 class="fgh" id="kh-dash-widgets-h"><KhIcon Name="grid" /> @T["Dashboard.Panel.Widgets"]</h3>
|
||||
<p class="muted s">@T["Dashboard.Panel.WidgetsHint"] @SourceText</p>
|
||||
<div class="kh-wpick">
|
||||
@foreach (var definition in _available)
|
||||
{
|
||||
var on = _layout.Contains(definition.Id);
|
||||
var title = T[definition.TitleKey];
|
||||
<div class="kh-wpick-row @(on ? null : "off")" @key="definition.Id">
|
||||
<KhSwitchRow Label="@title" Hint="@HintOf(definition)" Value="on" ValueChanged="v => ToggleAsync(definition.Id, v)" />
|
||||
@if (on)
|
||||
{
|
||||
<div class="kh-wpick-tools">
|
||||
<select class="kh-input" aria-label="@T.Format("Dashboard.Panel.Width", title)" value="@_layout.WidthOf(definition.Id)"
|
||||
@onchange="e => ResizeAsync(definition.Id, e.Value as string)">
|
||||
@foreach (var width in WidgetDefinition.Widths)
|
||||
{
|
||||
<option value="@width">@T["Dashboard.Widths." + width]</option>
|
||||
}
|
||||
</select>
|
||||
<button type="button" class="ib" title="@T.Format("Dashboard.Panel.MoveUp", title)" aria-label="@T.Format("Dashboard.Panel.MoveUp", title)"
|
||||
disabled="@(_layout.Widgets[0].Id == definition.Id)" @onclick="() => MoveAsync(definition.Id, -1)"><KhIcon Name="chevron-up" /></button>
|
||||
<button type="button" class="ib" title="@T.Format("Dashboard.Panel.MoveDown", title)" aria-label="@T.Format("Dashboard.Panel.MoveDown", title)"
|
||||
disabled="@(_layout.Widgets[^1].Id == definition.Id)" @onclick="() => MoveAsync(definition.Id, 1)"><KhIcon Name="chevron-down" /></button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@if (CanSetRoleDefaults)
|
||||
{
|
||||
<section class="kh-dsec" aria-labelledby="kh-dash-role-h">
|
||||
<h3 class="fgh" id="kh-dash-role-h"><KhIcon Name="users" /> @T["Dashboard.Panel.Role"]</h3>
|
||||
<p class="muted s">@T["Dashboard.Panel.RoleHint"]</p>
|
||||
@if (_roles.Count == 0)
|
||||
{
|
||||
<p class="muted s">@T["Dashboard.Panel.RoleNone"]</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="f">
|
||||
<label for="kh-dash-role">@T["Dashboard.Panel.RolePick"]</label>
|
||||
<select id="kh-dash-role" class="kh-input" value="@_role" @onchange="e => _role = e.Value as string">
|
||||
@foreach (var (role, layout) in _roles)
|
||||
{
|
||||
<option value="@role.Code">@(layout is null ? role.Name : T.Format("Dashboard.Panel.RoleHas", role.Name))</option>
|
||||
}
|
||||
</select>
|
||||
</div>
|
||||
<div class="kh-row">
|
||||
<button type="button" class="btn" @onclick="SaveRoleAsync"><KhIcon Name="users" /> @T["Dashboard.Panel.RoleSave"]</button>
|
||||
@if (SelectedRole is { Layout: not null })
|
||||
{
|
||||
<button type="button" class="btn ghost" @onclick="RemoveRoleAsync"><KhIcon Name="x" /> @T["Dashboard.Panel.RoleRemove"]</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
</ChildContent>
|
||||
<Footer>
|
||||
<button type="button" class="btn" @onclick="ResetAsync"><KhIcon Name="refresh" /> @T["Dashboard.Panel.Reset"]</button>
|
||||
<button type="button" class="btn primary" @onclick="CloseCustomize"><KhIcon Name="check" /> @T["Dashboard.Panel.Done"]</button>
|
||||
</Footer>
|
||||
</KhDrawer>
|
||||
|
||||
@code {
|
||||
private static string LevelLabel(string? level) => level switch
|
||||
private DashboardLayout _layout = WidgetCatalog.BuiltIn;
|
||||
private DashboardView? _view;
|
||||
private IReadOnlyList<WidgetDefinition> _available = [];
|
||||
private IReadOnlyList<(Role Role, DashboardLayout? Layout)> _roles = [];
|
||||
private string? _role;
|
||||
private bool _loaded;
|
||||
private bool _customizing;
|
||||
|
||||
private LicenseState License => Session.Licenses.Current;
|
||||
|
||||
private bool ShowDashboard => Session.Preferences.ShowDashboard;
|
||||
|
||||
private bool CanSetRoleDefaults => Session.Company is not null && Session.Permissions.Allows(CompanySettingsService.WritePermission);
|
||||
|
||||
private (Role Role, DashboardLayout? Layout)? SelectedRole =>
|
||||
_roles.Where(r => r.Role.Code == _role).Select(r => ((Role, DashboardLayout?)?)r).FirstOrDefault();
|
||||
|
||||
private IEnumerable<MenuItem> Areas =>
|
||||
MenuCatalog.Sections.SelectMany(s => s.Items).Where(i => i.Href != "/" && Session.CanSee(i));
|
||||
|
||||
private IEnumerable<MenuItem> StartChoices => MenuCatalog.All.Where(i => i.Href != "/" && i.Milestone is null && Session.CanSee(i));
|
||||
|
||||
private string StartValue => Session.Preferences.StartPage switch
|
||||
{
|
||||
"SuperUser" => "super utente",
|
||||
"Administrator" => "amministratore",
|
||||
_ => "utente",
|
||||
StartPage.Page when Session.Preferences.StartPath is { } path => path,
|
||||
StartPage.LastTab => nameof(StartPage.LastTab),
|
||||
_ => nameof(StartPage.Dashboard),
|
||||
};
|
||||
|
||||
private string SourceText => _view?.Source switch
|
||||
{
|
||||
DashboardLayoutSource.User => T["Dashboard.Panel.SourceUser"],
|
||||
DashboardLayoutSource.Role => T.Format("Dashboard.Panel.SourceRole", _roles.FirstOrDefault(r => r.Role.Code == _view.RoleCode).Role?.Name ?? _view.RoleCode ?? string.Empty),
|
||||
_ => T["Dashboard.Panel.SourceBuiltIn"],
|
||||
};
|
||||
|
||||
private string Today => Clock.GetLocalNow().ToString("dddd d MMMM yyyy", T.Culture);
|
||||
|
||||
private string Greeting
|
||||
{
|
||||
get
|
||||
{
|
||||
var key = Clock.GetLocalNow().Hour switch
|
||||
{
|
||||
< 13 => "Pages.Home.Greeting",
|
||||
< 18 => "Pages.Home.GreetingAfternoon",
|
||||
_ => "Pages.Home.GreetingEvening",
|
||||
};
|
||||
return T.Format(key, FirstName);
|
||||
}
|
||||
}
|
||||
|
||||
private string FirstName => Session.DisplayName.Split(' ', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault() ?? Session.DisplayName;
|
||||
|
||||
private string LicenseDetail
|
||||
{
|
||||
get
|
||||
{
|
||||
var parts = new List<string>();
|
||||
if (License.Licensee is { Length: > 0 } licensee)
|
||||
{
|
||||
parts.Add(T.Format("Pages.Home.LicenseLicensee", licensee));
|
||||
}
|
||||
|
||||
parts.Add(License.DaysLeft(Clock.GetUtcNow().UtcDateTime) is { } days
|
||||
? T.Format("Pages.Home.LicenseDaysLeft", days)
|
||||
: T["Pages.Home.LicenseUnlimited"]);
|
||||
return string.Join(" · ", parts);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await Session.EnsureLoadedAsync();
|
||||
if (Session.Actor is { } actor)
|
||||
{
|
||||
_available = await Dashboard.AvailableAsync(actor);
|
||||
_view = await Dashboard.GetAsync(actor);
|
||||
_layout = _view.Layout;
|
||||
}
|
||||
|
||||
_loaded = true;
|
||||
}
|
||||
|
||||
private string HintOf(WidgetDefinition definition) =>
|
||||
definition.Milestone is { } milestone
|
||||
? T[definition.DescriptionKey] + " " + T.Format("Dashboard.Panel.ComingFrom", milestone)
|
||||
: T[definition.DescriptionKey];
|
||||
|
||||
private async Task ToggleCustomize()
|
||||
{
|
||||
if (_customizing)
|
||||
{
|
||||
CloseCustomize();
|
||||
return;
|
||||
}
|
||||
|
||||
if (CanSetRoleDefaults && Session.Company is { } company)
|
||||
{
|
||||
_roles = await Dashboard.RoleDefaultsAsync(company.Code);
|
||||
_role ??= _roles.FirstOrDefault().Role?.Code;
|
||||
}
|
||||
|
||||
_customizing = true;
|
||||
}
|
||||
|
||||
private void CloseCustomize() => _customizing = false;
|
||||
|
||||
private async Task ChangeLayoutAsync(DashboardLayout next)
|
||||
{
|
||||
_layout = next;
|
||||
if (Session.Actor is { } actor)
|
||||
{
|
||||
await Dashboard.SaveAsync(actor, next);
|
||||
_view = new DashboardView(next, DashboardLayoutSource.User);
|
||||
}
|
||||
}
|
||||
|
||||
private Task ToggleAsync(string id, bool visible) => ChangeLayoutAsync(_layout.Toggle(id, visible));
|
||||
|
||||
private Task MoveAsync(string id, int offset) => ChangeLayoutAsync(_layout.Move(id, offset));
|
||||
|
||||
private Task ResizeAsync(string id, string? value) =>
|
||||
int.TryParse(value, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var width)
|
||||
? ChangeLayoutAsync(_layout.Resize(id, width))
|
||||
: Task.CompletedTask;
|
||||
|
||||
private async Task ResetAsync()
|
||||
{
|
||||
if (Session.Actor is not { } actor)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await Dashboard.ResetAsync(actor);
|
||||
_view = await Dashboard.GetAsync(actor);
|
||||
_layout = _view.Layout;
|
||||
Toasts.Show(ToastKind.Info, T["Dashboard.Panel.ResetDone"]);
|
||||
}
|
||||
|
||||
private async Task ChangeShowAsync(bool show)
|
||||
{
|
||||
await Session.SavePreferencesAsync(Session.Preferences with { ShowDashboard = show });
|
||||
if (!show)
|
||||
{
|
||||
_customizing = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ChangeStartAsync(ChangeEventArgs e)
|
||||
{
|
||||
var value = e.Value as string;
|
||||
var next = value switch
|
||||
{
|
||||
nameof(StartPage.LastTab) => Session.Preferences with { StartPage = StartPage.LastTab },
|
||||
_ when UserPreferences.IsLocalPath(value) && value != "/" => Session.Preferences with { StartPage = StartPage.Page, StartPath = value },
|
||||
_ => Session.Preferences with { StartPage = StartPage.Dashboard },
|
||||
};
|
||||
await Session.SavePreferencesAsync(next);
|
||||
}
|
||||
|
||||
private async Task SaveRoleAsync() => await SetRoleDefaultAsync(_layout, "Dashboard.Panel.RoleSaved");
|
||||
|
||||
private async Task RemoveRoleAsync() => await SetRoleDefaultAsync(null, "Dashboard.Panel.RoleRemoved");
|
||||
|
||||
private async Task SetRoleDefaultAsync(DashboardLayout? layout, string doneKey)
|
||||
{
|
||||
if (Session.Actor is not { } actor || Session.Company is not { } company || SelectedRole is not { } selected)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await Dashboard.SaveRoleDefaultAsync(actor, company.Code, selected.Role.Code, layout);
|
||||
_roles = await Dashboard.RoleDefaultsAsync(company.Code);
|
||||
Toasts.Show(ToastKind.Success, T.Format(doneKey, selected.Role.Name));
|
||||
}
|
||||
}
|
||||
@@ -12,10 +12,10 @@
|
||||
@inject NavigationManager Navigation
|
||||
@inject TimeProvider Clock
|
||||
|
||||
<PageTitle>Accedi · Khaemhat</PageTitle>
|
||||
<PageTitle>@T["Auth.Login.Title"] · @T["Common.ProductName"]</PageTitle>
|
||||
|
||||
<h1>Accedi</h1>
|
||||
<p class="sub">Scegli l'azienda e inserisci le credenziali.</p>
|
||||
<h1>@T["Auth.Login.Title"]</h1>
|
||||
<p class="sub">@T["Auth.Login.Subtitle"]</p>
|
||||
|
||||
@foreach (var message in Errors)
|
||||
{
|
||||
@@ -23,24 +23,24 @@
|
||||
}
|
||||
|
||||
<EditForm Model="Input" method="post" FormName="login" OnSubmit="SubmitAsync" class="kh-form">
|
||||
<label for="company">Azienda</label>
|
||||
<label for="company">@T["Auth.Login.Company"]</label>
|
||||
<InputSelect id="company" @bind-Value="Input.CompanyCode">
|
||||
<option value="">Nessuna (account di istanza)</option>
|
||||
<option value="">@T["Auth.Login.NoCompany"]</option>
|
||||
@foreach (var company in AvailableCompanies)
|
||||
{
|
||||
<option value="@company.Code">@company.Name (@company.Code)</option>
|
||||
<option value="@company.Code">@T.Format("Auth.Login.CompanyOption", company.Name, company.Code)</option>
|
||||
}
|
||||
</InputSelect>
|
||||
|
||||
<label for="user">Nome utente</label>
|
||||
<label for="user">@T["Auth.Login.UserName"]</label>
|
||||
<InputText id="user" @bind-Value="Input.UserName" autocomplete="username" autofocus required />
|
||||
|
||||
<label for="password">Password</label>
|
||||
<label for="password">@T["Auth.Login.Password"]</label>
|
||||
<InputText id="password" type="password" @bind-Value="Input.Password" autocomplete="current-password" required />
|
||||
|
||||
<label class="check"><InputCheckbox @bind-Value="Input.Remember" /> Ricordami su questo dispositivo</label>
|
||||
<label class="check"><InputCheckbox @bind-Value="Input.Remember" /> @T["Auth.Login.Remember"]</label>
|
||||
|
||||
<button type="submit" class="kh-btn primary">Accedi</button>
|
||||
<button type="submit" class="kh-btn primary">@T["Auth.Login.Submit"]</button>
|
||||
</EditForm>
|
||||
|
||||
@if (TrialNotice is not null)
|
||||
@@ -77,11 +77,11 @@
|
||||
var license = Licenses.Current;
|
||||
if (license.Kind == LicenseKind.Trial)
|
||||
{
|
||||
TrialNotice = $"Licenza in modalità prova: restano {license.DaysLeft(Clock.GetUtcNow().UtcDateTime)} giorni, con i moduli Base e Contabilità e {license.MaxConcurrentUsers} utenti collegati.";
|
||||
TrialNotice = T.Format("Auth.Login.Trial", license.DaysLeft(Clock.GetUtcNow().UtcDateTime), license.MaxConcurrentUsers);
|
||||
}
|
||||
else if (license.Status != LicenseStatus.Valid)
|
||||
{
|
||||
TrialNotice = "La licenza è scaduta: rivolgiti all'amministratore.";
|
||||
TrialNotice = T["Auth.Login.Expired"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,7 +94,7 @@
|
||||
Input.Password = null;
|
||||
if (!result.Succeeded || result.Cookie is null)
|
||||
{
|
||||
Errors = LoginFlow.Messages(result.Error);
|
||||
Errors = LoginFlow.Messages(T, Policy, result.Error);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||