From acb7e598d134e734d70d37afefdbd7ddabe54a6b Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 11 Nov 2026 19:15:06 +0100 Subject: [PATCH] feat: widget dashboard and company settings (#30, #31) The home page becomes the widget dashboard of mockups 004-006. Each user switches widgets on and off, orders them (drag and drop or buttons that also work from the keyboard), sizes them on the 12-column grid and picks the start page; every change is saved at once. Whoever may change the company settings sets a default layout per role, used by people who never customized; Reset goes back to it. Todo, Done and Deadlines collect lines from sources each module registers, so later milestones fill them without touching the widgets; a failing source is logged and skipped. M3 provides licence, unread warnings and scheduled task runs. Notes, Shortcuts and System status work now; widgets of modules still to come say which milestone brings their data instead of showing fake numbers. Role defaults live in the new company_settings table, written through CompanySettingsService with company.settings.write (ADR 0022). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 10 +- docs/DATA-MODEL.md | 16 + docs/adr/0022-dashboard-a-widget.md | 47 +++ docs/wiki/Dashboard.md | 75 +++- .../Dashboard/DashboardFeeds.cs | 186 +++++++++ .../Dashboard/DashboardLayout.cs | 166 ++++++++ .../Dashboard/DashboardService.cs | 284 ++++++++++++++ .../Dashboard/SystemFeedSources.cs | 182 +++++++++ .../Dashboard/SystemStatusService.cs | 42 ++ .../Dashboard/WidgetCatalog.cs | 132 +++++++ .../Instance/CompanySettingsService.cs | 126 ++++++ src/Khaemhat.Core/Instance/CompanySettings.cs | 16 + .../CompanyDatabase/CompanyMaps.cs | 11 + .../M20261111_008_CreateCompanySettings.cs | 23 ++ .../Components/Dashboard/ComingWidget.razor | 18 + .../Dashboard/DashboardWidget.razor | 31 ++ .../Components/Dashboard/FeedWidget.razor | 140 +++++++ .../Components/Dashboard/NotesWidget.razor | 110 ++++++ .../Dashboard/ShortcutsWidget.razor | 105 +++++ .../Dashboard/SystemStatusWidget.razor | 86 +++++ src/Khaemhat.Web/Components/Pages/Home.razor | 358 +++++++++++++++--- src/Khaemhat.Web/Components/Ui/KhWidget.razor | 114 ++++++ .../Components/Ui/KhWidgetGrid.razor | 94 +++++ src/Khaemhat.Web/Components/_Imports.razor | 2 + src/Khaemhat.Web/Hosting/KhaemhatServices.cs | 16 + .../Resources/it-IT/Dashboard.json | 162 ++++++++ src/Khaemhat.Web/Resources/it-IT/Pages.json | 5 +- src/Khaemhat.Web/Ui/DashboardModels.cs | 14 + src/Khaemhat.Web/wwwroot/app.css | 52 +++ src/Khaemhat.Web/wwwroot/js/khaemhat.js | 8 + .../DashboardTests.cs | 134 +++++++ tests/Khaemhat.Data.Tests/MappingTests.cs | 2 +- .../Shell/DashboardServiceTests.cs | 115 ++++++ .../Shell/LocalizationRulesTests.cs | 6 +- 34 files changed, 2812 insertions(+), 76 deletions(-) create mode 100644 docs/adr/0022-dashboard-a-widget.md create mode 100644 src/Khaemhat.Application/Dashboard/DashboardFeeds.cs create mode 100644 src/Khaemhat.Application/Dashboard/DashboardLayout.cs create mode 100644 src/Khaemhat.Application/Dashboard/DashboardService.cs create mode 100644 src/Khaemhat.Application/Dashboard/SystemFeedSources.cs create mode 100644 src/Khaemhat.Application/Dashboard/SystemStatusService.cs create mode 100644 src/Khaemhat.Application/Dashboard/WidgetCatalog.cs create mode 100644 src/Khaemhat.Application/Instance/CompanySettingsService.cs create mode 100644 src/Khaemhat.Core/Instance/CompanySettings.cs create mode 100644 src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_008_CreateCompanySettings.cs create mode 100644 src/Khaemhat.Web/Components/Dashboard/ComingWidget.razor create mode 100644 src/Khaemhat.Web/Components/Dashboard/DashboardWidget.razor create mode 100644 src/Khaemhat.Web/Components/Dashboard/FeedWidget.razor create mode 100644 src/Khaemhat.Web/Components/Dashboard/NotesWidget.razor create mode 100644 src/Khaemhat.Web/Components/Dashboard/ShortcutsWidget.razor create mode 100644 src/Khaemhat.Web/Components/Dashboard/SystemStatusWidget.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhWidget.razor create mode 100644 src/Khaemhat.Web/Components/Ui/KhWidgetGrid.razor create mode 100644 src/Khaemhat.Web/Resources/it-IT/Dashboard.json create mode 100644 src/Khaemhat.Web/Ui/DashboardModels.cs create mode 100644 tests/Khaemhat.Application.Tests/DashboardTests.cs create mode 100644 tests/Khaemhat.Web.Tests/Shell/DashboardServiceTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ccb981..d8dd3b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,8 +26,14 @@ M3 — Framework UI, prima parte: la shell dell'applicazione, i testi localizzat 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. -- Home con licenza, moduli, azienda e aree disponibili; le aree delle prossime versioni aprono una pagina che dice - con quale milestone arrivano. +- 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. diff --git a/docs/DATA-MODEL.md b/docs/DATA-MODEL.md index 6c8f388..d88e4c2 100644 --- a/docs/DATA-MODEL.md +++ b/docs/DATA-MODEL.md @@ -702,6 +702,7 @@ Migrazioni applicate in ordine: - `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) #### `attachments` @@ -748,6 +749,21 @@ 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` + #### `notifications` | Colonna | Tipo | Null | Default | Note | diff --git a/docs/adr/0022-dashboard-a-widget.md b/docs/adr/0022-dashboard-a-widget.md new file mode 100644 index 0000000..098b9da --- /dev/null +++ b/docs/adr/0022-dashboard-a-widget.md @@ -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.`) 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à. diff --git a/docs/wiki/Dashboard.md b/docs/wiki/Dashboard.md index bbd7556..2aa886e 100644 --- a/docs/wiki/Dashboard.md +++ b/docs/wiki/Dashboard.md @@ -1,6 +1,6 @@ # Dashboard -> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M3) +> **Stato:** bozza · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.3.0 (milestone M3, in sviluppo) > **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 è @@ -23,11 +23,18 @@ diversamente in *Pagina iniziale*. ![006 · Dashboard · personalizzazione](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/006-dashboard-personalizza.png) *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**. +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 +50,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 +117,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. diff --git a/src/Khaemhat.Application/Dashboard/DashboardFeeds.cs b/src/Khaemhat.Application/Dashboard/DashboardFeeds.cs new file mode 100644 index 0000000..45ca124 --- /dev/null +++ b/src/Khaemhat.Application/Dashboard/DashboardFeeds.cs @@ -0,0 +1,186 @@ +using Khaemhat.Application.Security; +using Microsoft.Extensions.Logging; + +namespace Khaemhat.Application.Dashboard; + +/// The colour of a line in a dashboard list. +public enum FeedTone +{ + /// Nothing special. + Neutral = 0, + + /// Information. + Info = 1, + + /// Done, fine. + Ok = 2, + + /// Needs attention. + Warning = 3, + + /// Something went wrong. + Error = 4, +} + +/// +/// A line of Da fare oggi, Fatto oggi or Scadenze. The texts are already in the user's +/// language; is the text key of the area label (Sistema, Vendite, Fiscale…). +/// +/// A stable id, unique within the list. +/// What it is. +/// The text key of the area. +/// The colour. +public sealed record FeedItem(string Id, string Text, string AreaKey, FeedTone Tone = FeedTone.Neutral) +{ + /// A second line, if any. + public string? Detail { get; init; } + + /// When: the time for what was done, the date for a deadline. + public DateTimeOffset? When { get; init; } + + /// Where it opens, a local address. + public string? Href { get; init; } + + /// Higher first, for the things to do. + public int Priority { get; init; } +} + +/// Who asks and when. +/// The user. +/// The local time now. +public sealed record FeedContext(Actor Actor, DateTimeOffset Now) +{ + /// Today, local. + public DateOnly Today => DateOnly.FromDateTime(Now.DateTime); + + /// The start of today, local. + public DateTimeOffset StartOfToday => new(Now.Date, Now.Offset); +} + +/// A source of things to do today (rejected SDI invoices, VAT settlements, procedures waiting… as the modules come). +public interface ITodoSource +{ + /// The things to do. + /// Who and when. + /// Cancellation. + /// The lines. + Task> GetAsync(FeedContext context, CancellationToken cancellationToken); +} + +/// A source of things done today (documents issued, collections, backups, scheduled tasks…). +public interface IDoneSource +{ + /// The things done. + /// Who and when. + /// Cancellation. + /// The lines. + Task> GetAsync(FeedContext context, CancellationToken cancellationToken); +} + +/// A source of deadlines (fiscal, sales, treasury, contracts…). +public interface IDeadlineSource +{ + /// The deadlines from today up to the horizon. + /// Who and when. + /// The last day included. + /// Cancellation. + /// The lines, with set. + Task> GetAsync(FeedContext context, DateOnly until, CancellationToken cancellationToken); +} + +/// +/// 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. +/// +public abstract class FeedAggregator +{ + /// The most lines a widget shows. + public const int MaxItems = 50; + + /// Runs the sources one after the other (they share the database connections of the scope). + /// The calls. + /// Where failures go. + /// Cancellation. + /// All the lines. + protected static async Task> CollectAsync( + IEnumerable<(string Name, Func>> Call)> sources, ILogger logger, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(sources); + var items = new List(); + 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; + } +} + +/// What to do today, the most urgent first. +/// The sources. +/// The clock. +/// The log. +public sealed class TodoAggregator(IEnumerable sources, TimeProvider clock, ILogger logger) : FeedAggregator +{ + /// The things to do. + /// The user. + /// Cancellation. + /// Higher priority first, then the oldest. + public async Task> GetAsync(Actor actor, CancellationToken cancellationToken = default) + { + var context = new FeedContext(actor, clock.GetLocalNow()); + var items = await CollectAsync(sources.Select(s => (s.GetType().Name, (Func>>)(() => s.GetAsync(context, cancellationToken)))), logger, cancellationToken).ConfigureAwait(false); + return [.. items.OrderByDescending(i => i.Priority).ThenBy(i => i.When ?? DateTimeOffset.MaxValue).Take(MaxItems)]; + } +} + +/// What was done today, the latest first. +/// The sources. +/// The clock. +/// The log. +public sealed class DoneAggregator(IEnumerable sources, TimeProvider clock, ILogger logger) : FeedAggregator +{ + /// The things done today. + /// The user. + /// Cancellation. + /// The latest first. + public async Task> GetAsync(Actor actor, CancellationToken cancellationToken = default) + { + var context = new FeedContext(actor, clock.GetLocalNow()); + var items = await CollectAsync(sources.Select(s => (s.GetType().Name, (Func>>)(() => s.GetAsync(context, cancellationToken)))), logger, cancellationToken).ConfigureAwait(false); + return [.. items.OrderByDescending(i => i.When ?? DateTimeOffset.MinValue).Take(MaxItems)]; + } +} + +/// The deadlines of the next days, the nearest first. +/// The sources. +/// The clock. +/// The log. +public sealed class DeadlineAggregator(IEnumerable sources, TimeProvider clock, ILogger logger) : FeedAggregator +{ + /// How far the widget looks ahead. + public const int HorizonDays = 30; + + /// The deadlines from today to days ahead. + /// The user. + /// Cancellation. + /// The nearest first. + public async Task> 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>>)(() => 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)]; + } +} diff --git a/src/Khaemhat.Application/Dashboard/DashboardLayout.cs b/src/Khaemhat.Application/Dashboard/DashboardLayout.cs new file mode 100644 index 0000000..144b8d0 --- /dev/null +++ b/src/Khaemhat.Application/Dashboard/DashboardLayout.cs @@ -0,0 +1,166 @@ +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace Khaemhat.Application.Dashboard; + +/// A widget on the dashboard: which one and how wide. +/// The widget id (). +/// The width in columns of twelve: 3, 4, 6, 8 or 12. +public sealed record WidgetPlacement(string Id, int Width); + +/// +/// 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 user_settings (dashboard.layout) and, as the default of a role, in +/// company_settings: {"v":1,"widgets":[{"id":"todo","w":4}]}. +/// +/// The widgets in order. +public sealed record DashboardLayout(IReadOnlyList Widgets) +{ + /// The most widgets a layout keeps. + public const int MaxWidgets = 30; + + private const int Version = 1; + + /// Whether a widget is shown. + /// The widget id. + /// when it is in the layout. + public bool Contains(string id) => Widgets.Any(w => w.Id == id); + + /// The width of a widget, or its default when not shown. + /// The widget id. + /// The width. + public int WidthOf(string id) => + Widgets.FirstOrDefault(w => w.Id == id)?.Width ?? WidgetCatalog.Find(id)?.DefaultWidth ?? 4; + + /// Reads a layout saved as JSON. + /// The JSON, or . + /// The layout without unknown widgets, duplicates or invalid widths; when there + /// is none or it cannot be read. + 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(); + 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() : 0; + widgets.Add(new WidgetPlacement(item["id"]!.GetValue(), width)); + } + } + + return new DashboardLayout(widgets).Normalize(); + } + catch (Exception ex) when (ex is JsonException or FormatException or InvalidOperationException) + { + return null; + } + } + + /// The layout as JSON. + /// The JSON. + 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(); + } + + /// Drops unknown widgets and repeated ones and snaps the widths to the allowed ones. + /// The clean layout. + public DashboardLayout Normalize() + { + var seen = new HashSet(StringComparer.Ordinal); + var widgets = new List(); + 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); + } + + /// Only the widgets that pass a test, such as those the user may see. + /// The test. + /// The layout. + public DashboardLayout Where(Func keep) + { + ArgumentNullException.ThrowIfNull(keep); + return new DashboardLayout([.. Widgets.Where(w => keep(w.Id))]); + } + + /// Shows a widget at the end, or hides it. + /// The widget id. + /// Whether to show it. + /// The layout. + 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)]); + } + + /// Changes the width of a widget. + /// The widget id. + /// The new width (snapped to the allowed ones). + /// The layout. + public DashboardLayout Resize(string id, int width) => + new([.. Widgets.Select(w => w.Id == id ? w with { Width = WidgetDefinition.Snap(width) } : w)]); + + /// Moves a widget by some places. + /// The widget id. + /// -1 before the previous one, +1 after the next one. + /// The layout. + 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)); + } + + /// Moves a widget to a position, as dropping it on another widget does. + /// The widget id. + /// The new position. + /// The layout. + 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); + } + + /// Whether two layouts show the same widgets in the same order and widths. + /// The other layout. + /// when they look the same. + public bool SameAs(DashboardLayout? other) => other is not null && Widgets.SequenceEqual(other.Widgets); +} diff --git a/src/Khaemhat.Application/Dashboard/DashboardService.cs b/src/Khaemhat.Application/Dashboard/DashboardService.cs new file mode 100644 index 0000000..1c31d9b --- /dev/null +++ b/src/Khaemhat.Application/Dashboard/DashboardService.cs @@ -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; + +/// Where the layout shown comes from. +public enum DashboardLayoutSource +{ + /// The built-in layout of . + BuiltIn = 0, + + /// The default of one of the user's roles. + Role = 1, + + /// The user's own layout. + User = 2, +} + +/// The dashboard of a user: the layout and where it comes from. +/// The widgets the user may see, in order. +/// Where it comes from. +/// The role whose default is used, when is . +public sealed record DashboardView(DashboardLayout Layout, DashboardLayoutSource Source, string? RoleCode = null); + +/// A personal reminder of the dashboard. +/// What to remember. +/// Whether it is ticked. +public sealed record PersonalNote(string Text, bool Done); + +/// +/// 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 user_settings; the role defaults belong to the company in company_settings. +/// +/// The user's settings. +/// The company's settings. +/// Opens the company database, for the roles of a user. +/// The user's permissions. +/// The licensed modules. +public sealed class DashboardService( + UserSettingsService settings, + CompanySettingsService company, + IUnitOfWorkFactory factory, + PermissionService permissions, + ILicenseGate licenses) +{ + /// The key of the user's layout. + public const string LayoutKey = "dashboard.layout"; + + /// The key of the personal reminders. + public const string NotesKey = "dashboard.notes"; + + /// The key of the shortcuts. + public const string ShortcutsKey = "dashboard.shortcuts"; + + /// The start of the keys of the role defaults in company_settings. + public const string RolePrefix = "dashboard.layout.role."; + + /// The most reminders kept. + public const int MaxNotes = 20; + + /// The longest reminder. + public const int MaxNoteLength = 300; + + /// The most shortcuts kept. + public const int MaxShortcuts = 12; + + /// The key of the default layout of a role. + /// The role code. + /// The key. + public static string RoleKey(string roleCode) => RolePrefix + roleCode; + + /// The widgets a user may see: licensed module, permission, administrators only. + /// The user. + /// Cancellation. + /// The widgets in catalog order. + public async Task> 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)))]; + } + + /// The dashboard to show. + /// The user. + /// Cancellation. + /// The layout, limited to the widgets the user may see, and where it comes from. + public async Task 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); + } + + /// Saves the user's layout. + /// The user. + /// The layout. + /// Cancellation. + /// A task. + public Task SaveAsync(Actor actor, DashboardLayout layout, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(layout); + return settings.SetAsync(actor, LayoutKey, layout.ToJson(), cancellationToken); + } + + /// Forgets the user's layout: the role default or the built-in one comes back. + /// The user. + /// Cancellation. + /// A task. + public Task ResetAsync(Actor actor, CancellationToken cancellationToken = default) => + settings.SetAsync(actor, LayoutKey, null, cancellationToken); + + /// The roles of the company with their default layout, if they have one. + /// The company. + /// Cancellation. + /// The roles in name order. + public async Task> 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().ListAsync(Query.For(), 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))]; + } + + /// Sets or removes () the default layout of a role. + /// Who sets it: needs company.settings.write. + /// The company. + /// The role. + /// The layout, or . + /// Cancellation. + /// A task. + 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); + } + + /// The personal reminders. + /// The user. + /// Cancellation. + /// The reminders in order. + public async Task> GetNotesAsync(Actor actor, CancellationToken cancellationToken = default) + { + var json = await settings.GetAsync(actor, NotesKey, cancellationToken).ConfigureAwait(false); + var notes = new List(); + foreach (var node in ReadArray(json)) + { + if (node is JsonObject item && item["t"]?.GetValueKind() == JsonValueKind.String) + { + notes.Add(new PersonalNote(item["t"]!.GetValue(), item["d"]?.GetValueKind() == JsonValueKind.True)); + } + } + + return CleanNotes(notes); + } + + /// Saves the personal reminders (at most , each up to characters). + /// The user. + /// The reminders. + /// Cancellation. + /// A task. + public Task SaveNotesAsync(Actor actor, IReadOnlyList 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); + } + + /// The addresses of the shortcut buttons. + /// The user. + /// Cancellation. + /// The addresses in order; when the user never chose them. + public async Task?> 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())); + } + + /// Saves the shortcut buttons (local addresses only, at most ). + /// The user. + /// The addresses. + /// Cancellation. + /// A task. + public Task SaveShortcutsAsync(Actor actor, IReadOnlyList 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 CleanNotes(IEnumerable 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 CleanShortcuts(IEnumerable 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().ListAsync(Query.For().Where(r => r.UserId == userId), cancellationToken).ConfigureAwait(false)) + .Items.Select(r => r.RoleId).ToHashSet(); + var roles = (await unitOfWork.Repository().ListAsync(Query.For(), 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; + } +} diff --git a/src/Khaemhat.Application/Dashboard/SystemFeedSources.cs b/src/Khaemhat.Application/Dashboard/SystemFeedSources.cs new file mode 100644 index 0000000..51a958e --- /dev/null +++ b/src/Khaemhat.Application/Dashboard/SystemFeedSources.cs @@ -0,0 +1,182 @@ +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; + +/// Text keys of the dashboard areas (the label at the side of a line). +public static class FeedAreas +{ + /// System and administration. + public const string System = "Dashboard.Areas.System"; + + /// Messages for the user. + public const string Notifications = "Dashboard.Areas.Notifications"; +} + +/// +/// 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. +/// +/// The licence in force. +/// The texts. +public sealed class LicenseFeedSource(ILicenseGate licenses, ITexts texts) : ITodoSource, IDeadlineSource +{ + /// Days before the expiry when renewing becomes a thing to do. + public const int RenewDays = 7; + + private const string Href = "/amministrazione/licenze"; + + /// + public Task> GetAsync(FeedContext context, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + var license = licenses.Current; + if (!context.Actor.IsInstanceAccount || license.IsTestMode) + { + return Task.FromResult>([]); + } + + 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>(item is null ? [] : [item]); + } + + /// + public Task> 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>([]); + } + + var when = new DateTimeOffset(DateTime.SpecifyKind(expires, DateTimeKind.Utc)).ToOffset(context.Now.Offset); + if (DateOnly.FromDateTime(when.DateTime) > until) + { + return Task.FromResult>([]); + } + + var key = license.Kind == LicenseKind.Trial ? "Dashboard.Feed.TrialEnds" : "Dashboard.Feed.LicenseEnds"; + var near = license.DaysLeft(context.Now.UtcDateTime) <= RenewDays; + return Task.FromResult>( + [ + new FeedItem("license-expiry", texts[key], FeedAreas.System, near ? FeedTone.Warning : FeedTone.Info) { When = when, Href = Href }, + ]); + } +} + +/// The unread warnings and errors addressed to the user, until they are read. +/// The notifications. +public sealed class NotificationTodoSource(NotificationDispatcher notifications) : ITodoSource +{ + /// + public async Task> GetAsync(FeedContext context, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + IReadOnlyList unread = context.Actor switch + { + { SystemUserId: { } id } => await notifications.UnreadForInstanceAsync(id, cancellationToken).ConfigureAwait(false), + { CompanyUserId: { } id, CompanyCode: { } company } => await notifications.UnreadForUserAsync(company, id, 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), + })]; + } +} + +/// +/// 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. +/// +/// Opens the system database. +/// The texts. +public sealed class JobRunFeedSource(IUnitOfWorkFactory factory, ITexts texts) : IDoneSource, ITodoSource +{ + private const string Href = "/amministrazione/attivita"; + + /// + async Task> 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 }; + })]; + } + + /// + async Task> 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 Runs, IReadOnlyDictionary 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().ListAsync(Query.For().Where(r => r.StartedAt >= since), cancellationToken).ConfigureAwait(false)).Items; + var tasks = (await unitOfWork.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items; + return (runs, tasks.ToDictionary(t => t.Code, t => t.Name, StringComparer.Ordinal)); + } +} diff --git a/src/Khaemhat.Application/Dashboard/SystemStatusService.cs b/src/Khaemhat.Application/Dashboard/SystemStatusService.cs new file mode 100644 index 0000000..e20a9ff --- /dev/null +++ b/src/Khaemhat.Application/Dashboard/SystemStatusService.cs @@ -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; + +/// What the Stato del sistema widget shows besides version, cache and licence. +/// The database engine. +/// The companies that are not disabled. +/// Those that failed to open at start-up. +/// Scheduled task runs of today that succeeded. +/// Those that failed. +public sealed record SystemStatus(DbEngine Engine, int Companies, int FailedCompanies, int JobsSucceeded, int JobsFailed); + +/// Reads the state of the instance for the administrators' widget. +/// Opens the system database. +/// The system database. +/// The companies. +/// What happened at start-up. +/// The clock. +public sealed class SystemStatusService(IUnitOfWorkFactory factory, DatabaseTarget system, ICompanyRegistry companies, BootstrapState bootstrap, TimeProvider clock) +{ + /// The state now. + /// Cancellation. + /// The state. + public async Task 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().ListAsync(Query.For().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)); + } +} diff --git a/src/Khaemhat.Application/Dashboard/WidgetCatalog.cs b/src/Khaemhat.Application/Dashboard/WidgetCatalog.cs new file mode 100644 index 0000000..af7b74c --- /dev/null +++ b/src/Khaemhat.Application/Dashboard/WidgetCatalog.cs @@ -0,0 +1,132 @@ +using Khaemhat.Application.Modules; + +namespace Khaemhat.Application.Dashboard; + +/// +/// A widget of the dashboard (SPEC §10.3, mockup 004): what it is, how wide it starts and who may see it. The +/// 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. +/// +/// The id, kept in the layouts. +/// The text key of the title. +/// The icon. +/// The starting width in columns of twelve. +/// The licensed module it needs. +/// The permission it needs, if any. +/// Only for administrators of the instance. +/// The milestone that brings its data, if still to come. +public sealed record WidgetDefinition( + string Id, + string TitleKey, + string Icon, + int DefaultWidth, + string Module, + string? Permission = null, + bool InstanceOnly = false, + string? Milestone = null) +{ + /// The widths a widget can take, in columns of twelve. + public static readonly IReadOnlyList Widths = [3, 4, 6, 8, 12]; + + /// The text key of the description shown in the customize panel. + public string DescriptionKey => TitleKey[..TitleKey.LastIndexOf('.')] + ".Description"; + + /// The nearest allowed width. + /// Any number. + /// One of . + public static int Snap(int width) => Widths.OrderBy(w => Math.Abs(w - width)).ThenByDescending(w => w).First(); + + /// The next width up or down, staying at the ends. + /// The current width. + /// +1 wider, -1 narrower. + /// The width. + 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]; + } +} + +/// The ids of the widgets. +public static class WidgetIds +{ + /// Indicators chosen by the user. + public const string Kpi = "kpi"; + + /// What to do today. + public const string Todo = "todo"; + + /// What was done today. + public const string Done = "done"; + + /// Deadlines of the next 30 days. + public const string Deadlines = "deadlines"; + + /// Orders and delivery notes still to fulfil. + public const string ToFulfil = "to-fulfil"; + + /// Revenue of the last 12 months. + public const string Revenue = "revenue"; + + /// CRM activities. + public const string CrmActivities = "crm-activities"; + + /// Personal reminders. + public const string Notes = "notes"; + + /// Shortcut buttons. + public const string Shortcuts = "shortcuts"; + + /// Items under the minimum stock. + public const string Understock = "understock"; + + /// The CRM pipeline. + public const string Pipeline = "pipeline"; + + /// The last documents. + public const string RecentDocuments = "recent-documents"; + + /// State of the system (administrators). + public const string SystemStatus = "system"; +} + +/// Every widget, in the order of the customize panel (SPEC §10.3). +public static class WidgetCatalog +{ + /// The widgets. + public static IReadOnlyList 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), + ]; + + /// + /// 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. + /// + 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), + ]); + + /// Finds a widget. + /// The id. + /// The widget, or . + public static WidgetDefinition? Find(string? id) => All.FirstOrDefault(w => string.Equals(w.Id, id, StringComparison.Ordinal)); +} diff --git a/src/Khaemhat.Application/Instance/CompanySettingsService.cs b/src/Khaemhat.Application/Instance/CompanySettingsService.cs new file mode 100644 index 0000000..b12eee4 --- /dev/null +++ b/src/Khaemhat.Application/Instance/CompanySettingsService.cs @@ -0,0 +1,126 @@ +using Khaemhat.Application.Security; +using Khaemhat.Core.Instance; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Instance; + +/// +/// Reads and writes the preferences of a company as a whole (company_settings, 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 company.settings.write. +/// +/// Opens the databases. +/// Checks the permission to write. +public sealed class CompanySettingsService(IUnitOfWorkFactory factory, PermissionService permissions) +{ + /// The permission to change the settings. + public const string WritePermission = "company.settings.write"; + + /// The longest value accepted (layouts are JSON). + public const int MaxValueLength = 64 * 1024; + + /// Reads the settings of a company, all or those whose key starts with a prefix. + /// The company. + /// The start of the keys, or for all. + /// Cancellation. + /// The values by key. + public async Task> 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); + } + + /// Reads one setting. + /// The company. + /// The key. + /// Cancellation. + /// The value, or . + public async Task 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; + } + + /// Writes one setting; removes it. + /// Who writes: needs in that company. + /// The company. + /// The key. + /// The value. + /// Cancellation. + /// A task. + public Task SetAsync(Actor actor, string companyCode, string key, string? value, CancellationToken cancellationToken = default) => + SetManyAsync(actor, companyCode, new Dictionary(StringComparer.Ordinal) { [key] = value }, cancellationToken); + + /// Writes several settings in one transaction; values remove the key. + /// Who writes: needs in that company. + /// The company. + /// The values by key. + /// Cancellation. + /// A task. + /// The actor may not change this company's settings. + public async Task SetManyAsync(Actor actor, string companyCode, IReadOnlyDictionary 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> ListAsync(IUnitOfWork unitOfWork, CancellationToken cancellationToken) => + (await unitOfWork.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items; + + private static async Task WriteAsync(IUnitOfWork unitOfWork, IReadOnlyDictionary values, CancellationToken cancellationToken) + { + var repository = unitOfWork.Repository(); + 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); + } + } + } +} diff --git a/src/Khaemhat.Core/Instance/CompanySettings.cs b/src/Khaemhat.Core/Instance/CompanySettings.cs new file mode 100644 index 0000000..3bf23c3 --- /dev/null +++ b/src/Khaemhat.Core/Instance/CompanySettings.cs @@ -0,0 +1,16 @@ +using Khaemhat.Core.Entities; + +namespace Khaemhat.Core.Instance; + +/// +/// A preference of the whole company (company_settings), such as the default dashboard of a role: one value per +/// key, written by whoever holds company.settings.write. +/// +public sealed class CompanySetting : Entity +{ + /// The key, such as dashboard.layout.role.SALES. + public string Key { get; set; } = string.Empty; + + /// The value, often JSON. + public string? Value { get; set; } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/CompanyMaps.cs b/src/Khaemhat.Data/CompanyDatabase/CompanyMaps.cs index 4d7af8a..32e3a73 100644 --- a/src/Khaemhat.Data/CompanyDatabase/CompanyMaps.cs +++ b/src/Khaemhat.Data/CompanyDatabase/CompanyMaps.cs @@ -108,6 +108,17 @@ public sealed class UserSettingMap : EntityMap } } +/// Map of to company_settings. +public sealed class CompanySettingMap : EntityMap +{ + /// Creates the map. + public CompanySettingMap() + { + ToTable("company_settings"); + Map(x => x.Key).MaxLength(200); + } +} + /// Map of to attachments. public sealed class AttachmentMap : EntityMap { diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_008_CreateCompanySettings.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_008_CreateCompanySettings.cs new file mode 100644 index 0000000..c43cd8e --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_008_CreateCompanySettings.cs @@ -0,0 +1,23 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// The preferences of the company as a whole, such as the default dashboard of each role (SPEC §10.3). +[Migration(20261111_008, "create_company_settings")] +public sealed class M20261111_008_CreateCompanySettings : IMigration +{ + /// + 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"); + }); + } +} diff --git a/src/Khaemhat.Web/Components/Dashboard/ComingWidget.razor b/src/Khaemhat.Web/Components/Dashboard/ComingWidget.razor new file mode 100644 index 0000000..1a9f632 --- /dev/null +++ b/src/Khaemhat.Web/Components/Dashboard/ComingWidget.razor @@ -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. *@ + +
+ +

@T[Definition.DescriptionKey]

+ @if (Definition.Milestone is { } milestone) + { +

@T.Format("Dashboard.Coming.Text", T["Dashboard.Coming." + milestone], milestone)

+ } +
+
+ +@code { + /// The widget. + [Parameter, EditorRequired] + public WidgetDefinition Definition { get; set; } = default!; +} diff --git a/src/Khaemhat.Web/Components/Dashboard/DashboardWidget.razor b/src/Khaemhat.Web/Components/Dashboard/DashboardWidget.razor new file mode 100644 index 0000000..56f417d --- /dev/null +++ b/src/Khaemhat.Web/Components/Dashboard/DashboardWidget.razor @@ -0,0 +1,31 @@ +@* Picks the component of a widget of the layout. *@ +@switch (Definition.Id) +{ + case WidgetIds.Todo: + + break; + case WidgetIds.Done: + + break; + case WidgetIds.Deadlines: + + break; + case WidgetIds.Notes: + + break; + case WidgetIds.Shortcuts: + + break; + case WidgetIds.SystemStatus: + + break; + default: + + break; +} + +@code { + /// The widget. + [Parameter, EditorRequired] + public WidgetDefinition Definition { get; set; } = default!; +} diff --git a/src/Khaemhat.Web/Components/Dashboard/FeedWidget.razor b/src/Khaemhat.Web/Components/Dashboard/FeedWidget.razor new file mode 100644 index 0000000..b0b3329 --- /dev/null +++ b/src/Khaemhat.Web/Components/Dashboard/FeedWidget.razor @@ -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. *@ + + + @if (_items is { Count: > 0 }) + { + @T.Number(_items.Count) + } + + + @if (_failed) + { +

@T["Dashboard.Feed.Error"]

+ } + else if (_items is null) + { +

@T["Dashboard.Feed.Loading"]

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

@T[EmptyKey]

+ } + else if (Kind == FeedKind.Deadlines) + { + + } + else + { + + } +
+
+ +@code { + private IReadOnlyList? _items; + private bool _failed; + + /// The widget. + [Parameter, EditorRequired] + public WidgetDefinition Definition { get; set; } = default!; + + /// Which list. + [Parameter] + public FeedKind Kind { get; set; } + + private string EmptyKey => Definition.TitleKey[..Definition.TitleKey.LastIndexOf('.')] + ".Empty"; + + /// + 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), + }; +} diff --git a/src/Khaemhat.Web/Components/Dashboard/NotesWidget.razor b/src/Khaemhat.Web/Components/Dashboard/NotesWidget.razor new file mode 100644 index 0000000..540da43 --- /dev/null +++ b/src/Khaemhat.Web/Components/Dashboard/NotesWidget.razor @@ -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. *@ + + + @if (_notes.Any(n => n.Done)) + { + + } + + +
+ @for (var i = 0; i < _notes.Count; i++) + { + var index = i; + var note = _notes[i]; +
+ +
@note.Text
+ +
+ } + @if (_loaded && _notes.Count == 0) + { +

@T["Dashboard.Widgets.Notes.Empty"]

+ } +
+
+ + +
+
+
+ +@code { + private List _notes = []; + private string? _text; + private bool _loaded; + + /// The widget. + [Parameter, EditorRequired] + public WidgetDefinition Definition { get; set; } = default!; + + /// + 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); + } + } +} diff --git a/src/Khaemhat.Web/Components/Dashboard/ShortcutsWidget.razor b/src/Khaemhat.Web/Components/Dashboard/ShortcutsWidget.razor new file mode 100644 index 0000000..85efee8 --- /dev/null +++ b/src/Khaemhat.Web/Components/Dashboard/ShortcutsWidget.razor @@ -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. *@ + + + + + + @if (Shortcuts.Count == 0) + { +

@T["Dashboard.Widgets.Shortcuts.Empty"]

+ } + else + { +
+ @foreach (var item in Shortcuts) + { + + + @T[item.Key] + + } +
+ } +
+
+ + + +

@T.Format("Dashboard.Widgets.Shortcuts.Hint", DashboardService.MaxShortcuts)

+
+ @foreach (var item in Choices) + { + var chosen = _draft.Contains(item.Href); + + } +
+
+
+ + +
+
+ +@code { + private IReadOnlyList? _paths; + private List _draft = []; + private bool _editing; + + /// The widget. + [Parameter, EditorRequired] + public WidgetDefinition Definition { get; set; } = default!; + + private IEnumerable Choices => MenuCatalog.All.Where(i => i.Href != "/" && Session.CanSee(i)); + + private IReadOnlyList 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()]; + + /// + 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; + } +} diff --git a/src/Khaemhat.Web/Components/Dashboard/SystemStatusWidget.razor b/src/Khaemhat.Web/Components/Dashboard/SystemStatusWidget.razor new file mode 100644 index 0000000..9e70641 --- /dev/null +++ b/src/Khaemhat.Web/Components/Dashboard/SystemStatusWidget.razor @@ -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. *@ + +
+
+ + @T["Dashboard.Widgets.System.Version"] + @Version.Version@(ShortRevision.Length == 0 ? null : " (" + ShortRevision + ")") +
+
+ + @T["Dashboard.Widgets.System.Database"] + @(_status?.Engine == DbEngine.PostgreSql ? "PostgreSQL" : "SQLite") +
+
+ + @T["Dashboard.Widgets.System.Cache"] + @(Cache.IsDistributed ? T["Dashboard.Widgets.System.Redis"] : T["Dashboard.Widgets.System.LocalCache"]) +
+
+ + @T["Dashboard.Widgets.System.License"] + @LicenseText +
+ @if (_status is { } status) + { +
+ + @T["Dashboard.Widgets.System.Companies"] + @(status.FailedCompanies > 0 + ? T.Format("Dashboard.Widgets.System.CompaniesFailed", status.Companies, status.FailedCompanies) + : T.Format("Dashboard.Widgets.System.CompaniesOk", status.Companies)) +
+
+ + @T["Dashboard.Widgets.System.Jobs"] + @T.Format("Dashboard.Widgets.System.JobsSummary", status.JobsSucceeded, status.JobsFailed) +
+ } +
+
+ +@code { + private SystemStatus? _status; + + /// The widget. + [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"], + }; + + /// + protected override async Task OnInitializedAsync() => _status = await Status.GetAsync(); +} diff --git a/src/Khaemhat.Web/Components/Pages/Home.razor b/src/Khaemhat.Web/Components/Pages/Home.razor index 9cb2cb2..725ab9e 100644 --- a/src/Khaemhat.Web/Components/Pages/Home.razor +++ b/src/Khaemhat.Web/Components/Pages/Home.razor @@ -2,66 +2,228 @@ @attribute [Authorize] @using Khaemhat.Application.Licensing @using Khaemhat.Application.Modules +@using Khaemhat.Core.Security +@using Khaemhat.Application.Instance @inject ShellSession Session +@inject DashboardService Dashboard +@inject ToastService Toasts @inject TimeProvider Clock -@* The home page of SPEC §10.2 until the widget dashboard of mockup 004 (issue #30): who is signed in, the licence, - the company and the areas the user can open, with the milestone of those still to come. *@ +@* 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. *@ -
-
-

@Greeting

-
@T.Format("Pages.Home.Today", Today)
-
-
- -
-
-
@T["Pages.Home.LicenseTile"]
-
@(License.Kind == LicenseKind.Trial ? T["Pages.Home.LicenseTrial"] : T["Pages.Home.LicenseFull"])
-
@LicenseDetail
-
-
-
@T["Pages.Home.ModulesTile"]
-
@T.Format("Pages.Home.ModulesText", License.Modules.Count, ModuleRegistry.Default.Modules.Count)
-
@(License.Modules.Count == 0 ? T["Pages.Home.ModulesNone"] : string.Join(" · ", License.Modules.Order(StringComparer.Ordinal)))
-
-
-
@T["Pages.Home.CompanyTile"]
-
@(Session.Company?.Name ?? T["Pages.Home.CompanyNone"])
-
@Session.Company?.Code
-
-
- -
-
@T["Pages.Home.AreasTitle"]
-
-

@T["Pages.Home.AreasHint"]

-
- @foreach (var area in Areas) - { - - - @T[area.Key] - @if (area.Milestone is { } milestone) - { - @T.Format("Pages.Home.Coming", milestone) - } - - } +
+
+
+

@Greeting

+
@T.Format("Pages.Home.Today", Today)
+
+ @if (_loaded && ShowDashboard) + { +
+ +
+ }
-
-
@T["Pages.Home.DashboardSoon"]
+ @if (!_loaded) + { +

@T["Dashboard.Feed.Loading"]

+ } + else if (ShowDashboard) + { + @if (_layout.Widgets.Count == 0) + { +
@T["Dashboard.Empty"]
+ } + else + { + + @foreach (var placement in _layout.Widgets) + { + if (WidgetCatalog.Find(placement.Id) is { } definition) + { + + } + } + + } + } + else + { +
+ + @T["Dashboard.Off"] + +
+ +
+
+
@T["Pages.Home.LicenseTile"]
+
@(License.Kind == LicenseKind.Trial ? T["Pages.Home.LicenseTrial"] : T["Pages.Home.LicenseFull"])
+
@LicenseDetail
+
+
+
@T["Pages.Home.ModulesTile"]
+
@T.Format("Pages.Home.ModulesText", License.Modules.Count, ModuleRegistry.Default.Modules.Count)
+
@(License.Modules.Count == 0 ? T["Pages.Home.ModulesNone"] : string.Join(" · ", License.Modules.Order(StringComparer.Ordinal)))
+
+
+
@T["Pages.Home.CompanyTile"]
+
@(Session.Company?.Name ?? T["Pages.Home.CompanyNone"])
+
@Session.Company?.Code
+
+
+ +
+
@T["Pages.Home.AreasTitle"]
+
+

@T["Pages.Home.AreasHint"]

+ +
+
+ } + + + + +
+

@T["Dashboard.Panel.Start"]

+
+ + +
+ +
+ +
+

@T["Dashboard.Panel.Widgets"]

+

@T["Dashboard.Panel.WidgetsHint"] @SourceText

+
+ @foreach (var definition in _available) + { + var on = _layout.Contains(definition.Id); + var title = T[definition.TitleKey]; +
+ + @if (on) + { +
+ + + +
+ } +
+ } +
+
+ + @if (CanSetRoleDefaults) + { +
+

@T["Dashboard.Panel.Role"]

+

@T["Dashboard.Panel.RoleHint"]

+ @if (_roles.Count == 0) + { +

@T["Dashboard.Panel.RoleNone"]

+ } + else + { +
+ + +
+
+ + @if (SelectedRole is { Layout: not null }) + { + + } +
+ } +
+ } +
+
+ + +
+
@code { + private DashboardLayout _layout = WidgetCatalog.BuiltIn; + private DashboardView? _view; + private IReadOnlyList _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 Areas => MenuCatalog.Sections.SelectMany(s => s.Items).Where(i => i.Href != "/" && Session.CanSee(i)); + private IEnumerable StartChoices => MenuCatalog.All.Where(i => i.Href != "/" && i.Milestone is null && Session.CanSee(i)); + + private string StartValue => Session.Preferences.StartPage switch + { + 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 @@ -98,5 +260,109 @@ } /// - protected override Task OnInitializedAsync() => Session.EnsureLoadedAsync(); + 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)); + } } diff --git a/src/Khaemhat.Web/Components/Ui/KhWidget.razor b/src/Khaemhat.Web/Components/Ui/KhWidget.razor new file mode 100644 index 0000000..91c2d5c --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhWidget.razor @@ -0,0 +1,114 @@ +@* A widget of the dashboard (SPEC §10.3): a card with icon, title and actions, as wide as the KhWidgetGrid around it + says. In customize mode the header shows the drag grip and the buttons to move, resize and hide it, so all of it + works from the keyboard too. *@ +
+
+ @if (Editing) + { + + } + else if (Icon is not null) + { + + } + @Title + +
+
+ @ChildContent +
+
+ +@code { + private static int _next; + private readonly string _id = "kh-wdg" + Interlocked.Increment(ref _next).ToString(System.Globalization.CultureInfo.InvariantCulture); + private bool _over; + + /// The grid around, which knows the width and handles the changes. + [CascadingParameter] + public KhWidgetGrid? Grid { get; set; } + + /// The widget id, as in the layout. + [Parameter, EditorRequired] + public string Id { get; set; } = string.Empty; + + /// The title. + [Parameter] + public string? Title { get; set; } + + /// The icon before the title. + [Parameter] + public string? Icon { get; set; } + + /// Buttons at the right of the title (hidden while customizing). + [Parameter] + public RenderFragment? Actions { get; set; } + + /// The content. + [Parameter] + public RenderFragment? ChildContent { get; set; } + + /// Content without padding (lists that run to the edges). + [Parameter] + public bool Tight { get; set; } + + /// The width when there is no grid around. + [Parameter] + public int FallbackWidth { get; set; } = 4; + + private int Width => Grid?.WidthOf(Id) ?? FallbackWidth; + + private bool Editing => Grid?.Editing == true; + + private void StartDrag() + { + if (Editing) + { + Grid!.StartDrag(Id); + } + } + + private void EndDrag() + { + _over = false; + Grid?.EndDrag(); + } + + private void SetOver(bool over) + { + if (Editing) + { + _over = over; + } + } + + private async Task DropAsync() + { + _over = false; + if (Editing) + { + await Grid!.DropOnAsync(Id); + } + } +} diff --git a/src/Khaemhat.Web/Components/Ui/KhWidgetGrid.razor b/src/Khaemhat.Web/Components/Ui/KhWidgetGrid.razor new file mode 100644 index 0000000..3096ace --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhWidgetGrid.razor @@ -0,0 +1,94 @@ +@using Khaemhat.Application.Dashboard + +@* The grid of the dashboard (SPEC §10.3, mockup 004/006): twelve columns, each KhWidget inside takes 3, 4, 6, 8 or 12. + In customize mode the widgets are dashed and can be dragged onto each other, moved with the arrow buttons, + narrowed, widened and hidden; every change comes out of LayoutChanged. *@ + +
+ @ChildContent +
+
+ +@code { + private string? _dragging; + + /// The widgets in order, with their width. + [Parameter, EditorRequired] + public DashboardLayout Layout { get; set; } = WidgetCatalog.BuiltIn; + + /// Whether the widgets can be moved, resized and hidden. + [Parameter] + public bool Editing { get; set; } + + /// Called with the new layout after a move, resize or hide. + [Parameter] + public EventCallback LayoutChanged { get; set; } + + /// The name of the grid for screen readers. + [Parameter] + public string? Label { get; set; } + + /// The KhWidget components, one per widget of the layout. + [Parameter] + public RenderFragment? ChildContent { get; set; } + + /// The width of a widget, in columns of twelve. + /// The widget id. + /// The width. + public int WidthOf(string id) => Layout.WidthOf(id); + + /// Whether a widget is the first or the last. + /// The widget id. + /// Ask about the last one. + /// at that end. + public bool IsAtEnd(string id, bool last) => + Layout.Widgets.Count > 0 && (last ? Layout.Widgets[^1].Id : Layout.Widgets[0].Id) == id; + + /// Moves a widget by one place. + /// The widget id. + /// -1 before, +1 after. + /// A task. + public Task MoveAsync(string id, int offset) => ChangeAsync(Layout.Move(id, offset)); + + /// Makes a widget narrower or wider by one step. + /// The widget id. + /// -1 narrower, +1 wider. + /// A task. + public Task ResizeAsync(string id, int step) => ChangeAsync(Layout.Resize(id, WidgetDefinition.Step(WidthOf(id), step))); + + /// Hides a widget. + /// The widget id. + /// A task. + public Task HideAsync(string id) => ChangeAsync(Layout.Toggle(id, false)); + + /// A widget starts being dragged. + /// The widget id. + public void StartDrag(string id) => _dragging = id; + + /// The dragged widget is dropped on another one: it takes that one's place. + /// The widget dropped on. + /// A task. + public async Task DropOnAsync(string target) + { + var dragged = _dragging; + _dragging = null; + if (dragged is null || dragged == target) + { + return; + } + + var index = Layout.Widgets.ToList().FindIndex(w => w.Id == target); + await ChangeAsync(Layout.MoveTo(dragged, index)); + } + + /// The drag ended without a drop. + public void EndDrag() => _dragging = null; + + private async Task ChangeAsync(DashboardLayout next) + { + if (!next.SameAs(Layout)) + { + await LayoutChanged.InvokeAsync(next); + } + } +} diff --git a/src/Khaemhat.Web/Components/_Imports.razor b/src/Khaemhat.Web/Components/_Imports.razor index 1277013..d807619 100644 --- a/src/Khaemhat.Web/Components/_Imports.razor +++ b/src/Khaemhat.Web/Components/_Imports.razor @@ -22,4 +22,6 @@ @using Khaemhat.Web.Components.Shell @using Khaemhat.Web.Components.Ui @using Khaemhat.Web.Ui +@using Khaemhat.Web.Components.Dashboard +@using Khaemhat.Application.Dashboard @inject ITexts T diff --git a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs index 00b90e9..6eec4f5 100644 --- a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs +++ b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs @@ -1,6 +1,7 @@ using System.Globalization; using Khaemhat.Application.Audit; using Khaemhat.Application.Configuration; +using Khaemhat.Application.Dashboard; using Khaemhat.Application.Files; using Khaemhat.Application.Instance; using Khaemhat.Application.Jobs; @@ -142,6 +143,21 @@ internal static class KhaemhatServices // Interface (SPEC §10): texts, preferences and the per-circuit state of the shell. services.AddSingleton(JsonTextProvider.FromAssembly(typeof(KhaemhatServices).Assembly, ItalianCulture)); services.AddSingleton(); + services.AddSingleton(); + + // Dashboard (SPEC §10.3): the sources of the lists join from the modules that feed them. + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/src/Khaemhat.Web/Resources/it-IT/Dashboard.json b/src/Khaemhat.Web/Resources/it-IT/Dashboard.json new file mode 100644 index 0000000..ea07685 --- /dev/null +++ b/src/Khaemhat.Web/Resources/it-IT/Dashboard.json @@ -0,0 +1,162 @@ +{ + "Dashboard": { + "Customize": "Personalizza", + "CustomizeTitle": "Personalizza dashboard", + "Empty": "Nessun widget acceso: sceglili da Personalizza.", + "Off": "La dashboard è spenta. Puoi riaccenderla da qui o dal tuo profilo, scheda Pagina iniziale.", + "ShowAgain": "Mostra la dashboard", + "Grid": "Widget della dashboard", + "Panel": { + "Start": "Pagina iniziale", + "StartPage": "Pagina da aprire", + "Show": "Mostra la dashboard", + "Widgets": "Widget", + "WidgetsHint": "Accendi i widget, mettili in ordine e scegli quanto sono larghi. Sulla pagina puoi anche trascinarli.", + "Width": "Larghezza di {0}", + "MoveUp": "Sposta {0} prima", + "MoveDown": "Sposta {0} dopo", + "Show1": "Mostra {0}", + "ComingFrom": "dati da {0}", + "Reset": "Ripristina", + "ResetDone": "Torna il layout predefinito.", + "Done": "Fine", + "SourceUser": "Stai usando un layout tuo.", + "SourceRole": "Stai usando il layout predefinito del ruolo {0}.", + "SourceBuiltIn": "Stai usando il layout predefinito di Khaemhat.", + "Role": "Predefinito per ruolo", + "RoleHint": "Chi non ha mai personalizzato la dashboard parte dal layout del suo ruolo.", + "RolePick": "Ruolo", + "RoleHas": "{0} (ha un predefinito)", + "RoleSave": "Usa questo layout per il ruolo", + "RoleRemove": "Togli il predefinito", + "RoleSaved": "Il ruolo {0} ora parte da questo layout.", + "RoleRemoved": "Il ruolo {0} torna al layout di Khaemhat.", + "RoleNone": "Nessun ruolo in questa azienda." + }, + "Widths": { + "3": "Un quarto", + "4": "Un terzo", + "6": "Metà", + "8": "Due terzi", + "12": "Tutta la riga" + }, + "Edit": { + "Drag": "Trascina per spostare", + "Before": "Sposta prima", + "After": "Sposta dopo", + "Narrower": "Più stretto", + "Wider": "Più largo", + "Hide": "Nascondi" + }, + "Areas": { + "System": "Sistema", + "Notifications": "Avvisi" + }, + "Coming": { + "Text": "Questo widget si riempie con i dati di {0}, in arrivo con la milestone {1}. Intanto puoi già metterlo dove ti serve.", + "M5": "Vendite", + "M6": "Acquisti e magazzino", + "M11": "CRM" + }, + "Feed": { + "Loading": "Caricamento...", + "Error": "Non è stato possibile leggere i dati: riprova più tardi.", + "Today": "Oggi", + "Tomorrow": "Domani", + "InDays": "Fra {0} giorni", + "LicenseExpired": "La licenza è scaduta e Khaemhat è in sola lettura: rinnovala", + "LicenseGrace": "La licenza è scaduta: rinnovala prima della fine della tolleranza", + "LicenseRenew": "La licenza scade fra {0} giorni: rinnovala", + "LicenseEnds": "Scadenza della licenza", + "TrialEnds": "Fine del periodo di prova", + "JobRanOnce": "Attività programmata", + "JobRanTimes": "Eseguita {0} volte oggi", + "JobFailed": "Attività «{0}» non riuscita" + }, + "Widgets": { + "Kpi": { + "Title": "Indicatori", + "Description": "I numeri chiave che scegli tu: fatturato, incassi, scaduto, ordini." + }, + "Todo": { + "Title": "Da fare oggi", + "Description": "Scarti SDI, liquidazioni e scadenze fiscali, procedure e approvazioni in attesa.", + "Empty": "Niente da fare: tutto in ordine." + }, + "Done": { + "Title": "Fatto oggi", + "Description": "Documenti emessi, incassi, backup e attività programmate di oggi.", + "Empty": "Ancora niente di fatto oggi." + }, + "Deadlines": { + "Title": "Scadenze 30 giorni", + "Description": "Scadenze fiscali, di vendita, di tesoreria e dei contratti.", + "Empty": "Nessuna scadenza nei prossimi 30 giorni." + }, + "ToFulfil": { + "Title": "Da evadere", + "Description": "Ordini e DDT con quantità ancora da consegnare o da fatturare." + }, + "Revenue": { + "Title": "Fatturato 12 mesi", + "Description": "Il fatturato mese per mese dell'ultimo anno." + }, + "CrmActivities": { + "Title": "Attività CRM", + "Description": "Chiamate, incontri e compiti in agenda." + }, + "Notes": { + "Title": "Promemoria personali", + "Description": "Note libere che vedi solo tu.", + "Add": "Nuovo promemoria", + "Placeholder": "Scrivi e premi Invio", + "Remove": "Togli «{0}»", + "Toggle": "Fatto: {0}", + "Empty": "Nessun promemoria.", + "ClearDone": "Togli quelli fatti", + "Full": "Hai già {0} promemoria: togline qualcuno." + }, + "Shortcuts": { + "Title": "Scorciatoie", + "Description": "I pulsanti delle pagine che apri più spesso.", + "Edit": "Scegli le scorciatoie", + "Hint": "Scegli fino a {0} pagine fra quelle che puoi aprire.", + "Empty": "Nessuna scorciatoia: sceglile con la matita." + }, + "Understock": { + "Title": "Sottoscorta", + "Description": "Gli articoli sotto la scorta minima." + }, + "Pipeline": { + "Title": "Pipeline CRM", + "Description": "Le opportunità aperte per fase." + }, + "RecentDocuments": { + "Title": "Ultimi documenti", + "Description": "Gli ultimi documenti creati o modificati." + }, + "System": { + "Title": "Stato del sistema", + "Description": "Versione, database, cache, licenza e attività programmate (solo amministratori).", + "Version": "Versione", + "Database": "Database", + "Cache": "Cache", + "License": "Licenza", + "Companies": "Aziende", + "Jobs": "Attività di oggi", + "Redis": "Redis", + "LocalCache": "In memoria", + "LicenseTest": "Codici di prova", + "LicenseTrial": "Prova, {0} giorni rimasti", + "LicenseDays": "Valida, {0} giorni rimasti", + "LicenseUnlimited": "Valida, senza scadenza", + "LicenseGrace": "Scaduta, in tolleranza", + "LicenseExpired": "Scaduta: sola lettura", + "CompaniesOk": "{0} aperte", + "CompaniesFailed": "{0} aperte, {1} con errori", + "JobsSummary": "{0} riuscite, {1} non riuscite", + "Open": "Apri lo stato del sistema" + } + } + } +} diff --git a/src/Khaemhat.Web/Resources/it-IT/Pages.json b/src/Khaemhat.Web/Resources/it-IT/Pages.json index 9667b74..41c40a4 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Pages.json +++ b/src/Khaemhat.Web/Resources/it-IT/Pages.json @@ -18,11 +18,8 @@ "AreasTitle": "Aree disponibili", "AreasHint": "Le aree si attivano con la licenza e i permessi; quelle segnate arrivano nelle prossime versioni.", "Coming": "in arrivo con {0}", - "DashboardSoon": "La dashboard a widget personalizzabile (KPI, da fare oggi, scadenze, fatturato…) arriva con la prossima parte di questa versione.", - "Subtitle": "{0}", "LicenseUnlimited": "senza scadenza", - "ModulesNone": "nessun modulo", - "Open": "Apri" + "ModulesNone": "nessun modulo" }, "ComingSoon": { "Title": "In arrivo", diff --git a/src/Khaemhat.Web/Ui/DashboardModels.cs b/src/Khaemhat.Web/Ui/DashboardModels.cs new file mode 100644 index 0000000..895714e --- /dev/null +++ b/src/Khaemhat.Web/Ui/DashboardModels.cs @@ -0,0 +1,14 @@ +namespace Khaemhat.Web.Ui; + +/// Which list a feed widget of the dashboard shows. +public enum FeedKind +{ + /// Da fare oggi. + Todo = 0, + + /// Fatto oggi. + Done = 1, + + /// Scadenze 30 giorni. + Deadlines = 2, +} diff --git a/src/Khaemhat.Web/wwwroot/app.css b/src/Khaemhat.Web/wwwroot/app.css index 1edff91..c4fb351 100644 --- a/src/Khaemhat.Web/wwwroot/app.css +++ b/src/Khaemhat.Web/wwwroot/app.css @@ -139,3 +139,55 @@ h1[tabindex="-1"]:focus { outline: none; box-shadow: none; } .kh-auth .features { display: none; } .cols-3 { grid-template-columns: 1fr; } } + +/* ---- dashboard (issue #30, mockups 004 and 006) ---- */ +.kh-home.kh-with-drawer { margin-right: 420px; } +.kh-home-off { align-items: center; margin-bottom: var(--kh-gap); } +.kh-home-off .grow { flex: 1; } +.kh-wgrid { margin-bottom: var(--kh-gap); } +.kh-wgrid.kh-editing .widget { cursor: grab; } +.kh-wgrid.kh-editing .widget .wb { pointer-events: none; opacity: .75; } +.widget.kh-over { outline-style: solid; background: var(--kh-accent-soft); } +.widget .wh .badge { font-size: 10.5px; } +.kh-wlist { overflow: auto; max-height: 320px; } +.kh-wlist .li .s { display: -webkit-box; -webkit-line-clamp: 2; line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; } +.kh-wlist a.li, a.deadline { color: var(--kh-text); text-decoration: none; } +.kh-wlist a.li[href]:hover, a.deadline[href]:hover { background: var(--kh-row-hover); } +.kh-wlist a[aria-disabled="true"] { cursor: default; } +.kh-wempty { display: flex; align-items: center; gap: 8px; margin: 0; padding: 14px 12px; font-size: 12.5px; color: var(--kh-text-2); } +.kh-wempty svg.i { color: var(--kh-ok); } +.kh-tone { flex: none; width: 8px; height: 8px; border-radius: 50%; background: var(--kh-text-3); } +.kh-tone.ok { background: var(--kh-ok); } .kh-tone.info { background: var(--kh-info, var(--kh-accent)); } +.kh-tone.warn { background: var(--kh-warn); } .kh-tone.err { background: var(--kh-err); } +.kh-status .li { padding: 7px 12px; } +.kh-status .li .s { text-align: right; } +.chk-row input[type="checkbox"] { margin: 0; accent-color: var(--kh-accent); } +.kh-rowx { opacity: 0; } +.chk-row:hover .kh-rowx, .kh-rowx:focus-visible { opacity: 1; } +.kh-wadd { display: flex; align-items: center; gap: 8px; padding: 8px 10px; border-top: 1px solid var(--kh-border); color: var(--kh-text-3); } +.kh-wadd .kh-input { flex: 1; min-width: 0; } +.kh-shortcuts { display: grid; grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); gap: 8px; } +.kh-shortcut { display: flex; flex-direction: column; align-items: center; gap: 6px; padding: 10px 6px; border: 1px solid var(--kh-border); + border-radius: var(--kh-radius-lg); color: var(--kh-text); text-decoration: none; font-size: 12px; text-align: center; } +.kh-shortcut:hover { border-color: var(--kh-accent); background: var(--kh-row-hover); } +.kh-shortcut .ico-box { width: 30px; height: 30px; } +.kh-picklist { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 4px 12px; max-height: 50vh; overflow: auto; } +.kh-picklist .chk { display: flex; align-items: center; gap: 6px; cursor: pointer; padding: 3px 0; } +.kh-wcoming { display: flex; flex-direction: column; align-items: flex-start; gap: 6px; font-size: 12.5px; } +.kh-wcoming > svg.i { color: var(--kh-text-3); } +.kh-wcoming p { margin: 0; } +.kh-wcoming .s { color: var(--kh-text-3); font-size: 11.5px; } +.kh-dsec { display: flex; flex-direction: column; gap: 8px; padding-bottom: 12px; border-bottom: 1px solid var(--kh-border); } +.kh-dsec:last-child { border-bottom: 0; } +.kh-dsec h3 { margin: 0; } +.kh-dsec p { margin: 0; } +.kh-dsec .f { display: flex; flex-direction: column; gap: 4px; } +.kh-wpick-row { border-bottom: 1px solid var(--kh-border); } +.kh-wpick-row .kh-switch-row { border-bottom: 0; } +.kh-wpick-row.off .kh-switch-row .t { color: var(--kh-text-2); } +.kh-wpick-tools { display: flex; align-items: center; gap: 4px; padding: 0 4px 8px; } +.kh-wpick-tools select { flex: 1; height: 26px; font-size: 12px; } +.kh-row { display: flex; gap: 8px; flex-wrap: wrap; } +@media (max-width: 1279px) { .kh-home.kh-with-drawer { margin-right: 0; } } +@media (max-width: 999px) { .kh-wgrid > .widget { grid-column: 1 / -1; } } +@media (max-width: 599px) { .kh-wlist .badge { display: none; } } diff --git a/src/Khaemhat.Web/wwwroot/js/khaemhat.js b/src/Khaemhat.Web/wwwroot/js/khaemhat.js index d1ec203..a28dd95 100644 --- a/src/Khaemhat.Web/wwwroot/js/khaemhat.js +++ b/src/Khaemhat.Web/wwwroot/js/khaemhat.js @@ -49,6 +49,14 @@ if (close) close.click(); }); + // Dashboard widgets being customized can be dragged: Firefox starts a drag only when some data is set. + document.addEventListener("dragstart", function (e) { + const widget = e.target.closest && e.target.closest("[data-kh-drag]"); + if (!widget || !e.dataTransfer) return; + e.dataTransfer.effectAllowed = "move"; + e.dataTransfer.setData("text/plain", widget.getAttribute("data-widget") || ""); + }); + function onBeforeUnload(e) { if (!unloadGuard) return; e.preventDefault(); diff --git a/tests/Khaemhat.Application.Tests/DashboardTests.cs b/tests/Khaemhat.Application.Tests/DashboardTests.cs new file mode 100644 index 0000000..34456ea --- /dev/null +++ b/tests/Khaemhat.Application.Tests/DashboardTests.cs @@ -0,0 +1,134 @@ +using Khaemhat.Application.Dashboard; +using Khaemhat.Application.Security; +using Khaemhat.Core.Security; +using Microsoft.Extensions.Logging.Abstractions; + +namespace Khaemhat.Application.Tests; + +/// The widget dashboard (SPEC §10.3, issue #30): the saved layout and the lists the widgets read. +[TestClass] +public sealed class DashboardTests +{ + private static readonly Actor User = new("mario", UserLevel.Standard, null, 1, "demo"); + private static readonly DateTimeOffset Now = new(2026, 11, 11, 10, 0, 0, TimeSpan.Zero); + + [TestMethod] + public void Layout_RoundTrips_AndDropsWhatItCannotUse() + { + var layout = new DashboardLayout([new("todo", 4), new("notes", 6), new("kpi", 12)]); + + var read = DashboardLayout.Parse(layout.ToJson()); + + Assert.IsNotNull(read); + Assert.IsTrue(layout.SameAs(read)); + + // Unknown and repeated widgets go, odd widths snap to the nearest allowed one (the wider on a tie), a missing width takes the default. + var messy = DashboardLayout.Parse("""{"v":1,"widgets":[{"id":"todo","w":5},{"id":"nope","w":4},{"id":"todo","w":4},{"id":"notes"}]}"""); + Assert.IsNotNull(messy); + CollectionAssert.AreEqual(new[] { new WidgetPlacement("todo", 6), new WidgetPlacement("notes", 4) }, messy.Widgets.ToList()); + + Assert.IsNull(DashboardLayout.Parse(null)); + Assert.IsNull(DashboardLayout.Parse("not json")); + Assert.IsNull(DashboardLayout.Parse("""{"widgets":"x"}""")); + } + + [TestMethod] + public void Layout_Toggles_Moves_AndResizes() + { + var layout = new DashboardLayout([new("todo", 4), new("done", 4), new("notes", 4)]); + + var shown = layout.Toggle("shortcuts", true); + Assert.AreEqual("shortcuts", shown.Widgets[^1].Id); + Assert.AreEqual(WidgetCatalog.Find("shortcuts")!.DefaultWidth, shown.Widgets[^1].Width); + Assert.AreSame(layout, layout.Toggle("todo", true), "Already shown."); + Assert.AreSame(layout, layout.Toggle("nope", true), "Not a widget."); + Assert.IsFalse(layout.Toggle("done", false).Contains("done")); + + CollectionAssert.AreEqual(new[] { "done", "todo", "notes" }, layout.Move("done", -1).Widgets.Select(w => w.Id).ToList()); + CollectionAssert.AreEqual(new[] { "todo", "done", "notes" }, layout.Move("todo", -1).Widgets.Select(w => w.Id).ToList(), "Already first."); + CollectionAssert.AreEqual(new[] { "notes", "todo", "done" }, layout.MoveTo("notes", 0).Widgets.Select(w => w.Id).ToList(), "Dropped on the first."); + + Assert.AreEqual(8, layout.Resize("todo", 7).WidthOf("todo")); + Assert.AreEqual(6, WidgetDefinition.Step(4, 1)); + Assert.AreEqual(3, WidgetDefinition.Step(3, -1)); + Assert.AreEqual(12, WidgetDefinition.Step(12, 1)); + } + + [TestMethod] + public void Catalog_BuiltInLayout_UsesOnlyWidgetsWithData() + { + Assert.IsTrue(WidgetCatalog.BuiltIn.Widgets.All(w => WidgetCatalog.Find(w.Id) is { Milestone: null })); + Assert.AreEqual(WidgetCatalog.All.Count, WidgetCatalog.All.Select(w => w.Id).Distinct().Count()); + Assert.IsTrue(WidgetCatalog.All.All(w => WidgetDefinition.Widths.Contains(w.DefaultWidth))); + } + + [TestMethod] + public async Task Todo_LeavesOutAFailingSource_AndPutsTheUrgentFirst() + { + var aggregator = new TodoAggregator( + [ + new Source(new FeedItem("a", "Normale", "x") { When = Now.AddHours(-2) }), + new FailingSource(), + new Source(new FeedItem("b", "Urgente", "x", FeedTone.Error) { Priority = 10 }), + ], + new FixedClock(Now), + NullLogger.Instance); + + var items = await aggregator.GetAsync(User); + + CollectionAssert.AreEqual(new[] { "b", "a" }, items.Select(i => i.Id).ToList()); + } + + [TestMethod] + public async Task Deadlines_KeepTheNext30Days_NearestFirst() + { + var aggregator = new DeadlineAggregator( + [ + new Source( + new FeedItem("later", "Fra 20 giorni", "x") { When = Now.AddDays(20) }, + new FeedItem("past", "Ieri", "x") { When = Now.AddDays(-1) }, + new FeedItem("far", "Fra 40 giorni", "x") { When = Now.AddDays(40) }, + new FeedItem("today", "Oggi", "x") { When = Now }, + new FeedItem("undated", "Senza data", "x")), + ], + new FixedClock(Now), + NullLogger.Instance); + + var items = await aggregator.GetAsync(User); + + CollectionAssert.AreEqual(new[] { "today", "later" }, items.Select(i => i.Id).ToList()); + } + + [TestMethod] + public async Task Done_LatestFirst() + { + var aggregator = new DoneAggregator( + [new Source(new FeedItem("early", "Alle 8", "x") { When = Now.AddHours(-2) }, new FeedItem("late", "Alle 9", "x") { When = Now.AddHours(-1) })], + new FixedClock(Now), + NullLogger.Instance); + + CollectionAssert.AreEqual(new[] { "late", "early" }, (await aggregator.GetAsync(User)).Select(i => i.Id).ToList()); + } + + private sealed class Source(params FeedItem[] items) : ITodoSource, IDoneSource, IDeadlineSource + { + public Task> GetAsync(FeedContext context, CancellationToken cancellationToken) => + Task.FromResult>(items); + + public Task> GetAsync(FeedContext context, DateOnly until, CancellationToken cancellationToken) => + Task.FromResult>(items); + } + + private sealed class FailingSource : ITodoSource + { + public Task> GetAsync(FeedContext context, CancellationToken cancellationToken) => + throw new InvalidOperationException("The module is down."); + } + + private sealed class FixedClock(DateTimeOffset now) : TimeProvider + { + public override DateTimeOffset GetUtcNow() => now; + + public override TimeZoneInfo LocalTimeZone => TimeZoneInfo.Utc; + } +} diff --git a/tests/Khaemhat.Data.Tests/MappingTests.cs b/tests/Khaemhat.Data.Tests/MappingTests.cs index 29ab7d2..d264b71 100644 --- a/tests/Khaemhat.Data.Tests/MappingTests.cs +++ b/tests/Khaemhat.Data.Tests/MappingTests.cs @@ -71,7 +71,7 @@ public sealed class MappingTests [ "sys_companies", "sys_data_protection_keys", "sys_job_locks", "sys_job_runs", "sys_license_activations", "sys_licenses", "sys_log", "sys_notifications", "sys_roles_templates", "sys_scheduled_tasks", "sys_security_audit", "sys_sessions", "sys_settings", "sys_user_settings", "sys_users", - "attachments", "audit_log", "notifications", "role_permissions", "roles", "user_permission_overrides", "user_roles", "user_sessions", "user_settings", "users", + "attachments", "audit_log", "company_settings", "notifications", "role_permissions", "roles", "user_permission_overrides", "user_roles", "user_sessions", "user_settings", "users", ]; CollectionAssert.AreEquivalent(expected, registry.Maps.Select(m => m.Table).ToArray()); } diff --git a/tests/Khaemhat.Web.Tests/Shell/DashboardServiceTests.cs b/tests/Khaemhat.Web.Tests/Shell/DashboardServiceTests.cs new file mode 100644 index 0000000..6beb907 --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Shell/DashboardServiceTests.cs @@ -0,0 +1,115 @@ +using Khaemhat.Application.Dashboard; +using Khaemhat.Application.Instance; +using Khaemhat.Application.Modules; +using Khaemhat.Application.Security; +using Khaemhat.Core.Security; +using Khaemhat.Web.Tests.Hosting; +using Microsoft.Extensions.DependencyInjection; + +namespace Khaemhat.Web.Tests.Shell; + +/// The dashboard of each user, the default of a role and the company settings behind it (issues #30 and #31). +[TestClass] +public sealed class DashboardServiceTests +{ + [TestMethod] + public async Task Layout_IsPersonal_FallsBackToTheRole_ThenToTheBuiltIn() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var dashboard = app.Services.GetRequiredService(); + var users = app.Services.GetRequiredService(); + var root = new Actor(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null); + var (anna, _) = await users.CreateAsync(root, company, new NewCompanyUser("anna", "Anna Verdi", null, UserKind.Human, [PredefinedRoles.ReadOnly], new UserFlags(false, false, false, false))); + var (luca, _) = await users.CreateAsync(root, company, new NewCompanyUser("luca", "Luca Neri", null, UserKind.Human, [PredefinedRoles.Administration], new UserFlags(false, false, false, false))); + var annaActor = new Actor("anna", UserLevel.Standard, null, anna.Id, company); + var lucaActor = new Actor("luca", UserLevel.Standard, null, luca.Id, company); + + // Only instance accounts see the state of the system. + Assert.IsTrue((await dashboard.AvailableAsync(root)).Any(w => w.Id == WidgetIds.SystemStatus)); + Assert.IsFalse((await dashboard.AvailableAsync(annaActor)).Any(w => w.Id == WidgetIds.SystemStatus)); + + // Nothing saved: the built-in layout, without what the user may not see. + var first = await dashboard.GetAsync(annaActor); + Assert.AreEqual(DashboardLayoutSource.BuiltIn, first.Source); + Assert.IsTrue(first.Layout.Contains(WidgetIds.Todo)); + Assert.IsFalse(first.Layout.Contains(WidgetIds.SystemStatus)); + + // The default of the role applies to whoever never customized. + var roleLayout = new DashboardLayout([new(WidgetIds.Notes, 6), new(WidgetIds.Deadlines, 6)]); + await dashboard.SaveRoleDefaultAsync(lucaActor, company, PredefinedRoles.ReadOnly, roleLayout); + var fromRole = await dashboard.GetAsync(annaActor); + Assert.AreEqual(DashboardLayoutSource.Role, fromRole.Source); + Assert.AreEqual(PredefinedRoles.ReadOnly, fromRole.RoleCode); + Assert.IsTrue(roleLayout.SameAs(fromRole.Layout)); + Assert.IsTrue((await dashboard.RoleDefaultsAsync(company)).Any(r => r.Role.Code == PredefinedRoles.ReadOnly && r.Layout is not null)); + + // A user's own layout wins and stays across services; Reset brings the role default back. + var own = new DashboardLayout([new(WidgetIds.Shortcuts, 12), new(WidgetIds.Todo, 4)]); + await dashboard.SaveAsync(annaActor, own); + var reread = await app.Services.CreateScope().ServiceProvider.GetRequiredService().GetAsync(annaActor with { }); + Assert.AreEqual(DashboardLayoutSource.User, reread.Source); + Assert.IsTrue(own.SameAs(reread.Layout)); + Assert.AreEqual(DashboardLayoutSource.BuiltIn, (await dashboard.GetAsync(lucaActor)).Source, "Another user is not touched."); + await dashboard.ResetAsync(annaActor); + Assert.AreEqual(DashboardLayoutSource.Role, (await dashboard.GetAsync(annaActor)).Source); + + // Only who may change the company settings sets the default of a role. + await Assert.ThrowsExactlyAsync(() => dashboard.SaveRoleDefaultAsync(annaActor, company, PredefinedRoles.ReadOnly, null)); + await dashboard.SaveRoleDefaultAsync(lucaActor, company, PredefinedRoles.ReadOnly, null); + Assert.AreEqual(DashboardLayoutSource.BuiltIn, (await dashboard.GetAsync(annaActor)).Source); + await app.StopAsync(); + } + } + + [TestMethod] + public async Task Notes_AndShortcuts_AreKeptPerUser_AndCleaned() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var dashboard = app.Services.GetRequiredService(); + var root = new Actor(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null); + + Assert.IsEmpty(await dashboard.GetNotesAsync(root)); + Assert.IsNull(await dashboard.GetShortcutsAsync(root), "Never chosen: the widget shows the first areas."); + + await dashboard.SaveNotesAsync(root, [new(" Chiamare il commercialista ", false), new(" ", false), new("Fatto", true)]); + CollectionAssert.AreEqual(new[] { new PersonalNote("Chiamare il commercialista", false), new PersonalNote("Fatto", true) }, (await dashboard.GetNotesAsync(root)).ToList()); + await dashboard.SaveNotesAsync(root, [.. Enumerable.Range(1, 30).Select(i => new PersonalNote(new string('n', 400), false))]); + var notes = await dashboard.GetNotesAsync(root); + Assert.HasCount(DashboardService.MaxNotes, notes); + Assert.IsTrue(notes.All(n => n.Text.Length <= DashboardService.MaxNoteLength)); + + await dashboard.SaveShortcutsAsync(root, ["/anagrafiche/clienti", "https://example.com", "//evil", "/anagrafiche/clienti", "/vendite"]); + CollectionAssert.AreEqual(new[] { "/anagrafiche/clienti", "/vendite" }, (await dashboard.GetShortcutsAsync(root))!.ToList()); + await dashboard.SaveShortcutsAsync(root, []); + Assert.IsEmpty((await dashboard.GetShortcutsAsync(root))!, "An empty choice is a choice."); + await app.StopAsync(); + } + } + + [TestMethod] + public async Task CompanySettings_NeedThePermission_AndStayInTheirCompany() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var settings = app.Services.GetRequiredService(); + var root = new Actor(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null); + var stranger = new Actor("altro", UserLevel.Standard, null, 1, "altra"); + + await settings.SetAsync(root, company, "test.alpha", "uno"); + await settings.SetManyAsync(root, company, new Dictionary { ["test.beta"] = "due", ["test.alpha"] = null }); + Assert.IsNull(await settings.GetAsync(company, "test.alpha")); + Assert.AreEqual("due", await settings.GetAsync(company, "test.beta")); + CollectionAssert.AreEquivalent(new[] { "test.beta" }, (await settings.GetAllAsync(company, "test.")).Keys.ToList()); + + await Assert.ThrowsExactlyAsync(() => settings.SetAsync(stranger, company, "test.gamma", "tre")); + await Assert.ThrowsExactlyAsync(() => settings.SetAsync(root, company, " ", "x")); + await Assert.ThrowsExactlyAsync(() => settings.SetAsync(root, company, "test.big", new string('x', CompanySettingsService.MaxValueLength + 1))); + await app.StopAsync(); + } + } +} diff --git a/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs b/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs index 17c947d..e78c232 100644 --- a/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs +++ b/tests/Khaemhat.Web.Tests/Shell/LocalizationRulesTests.cs @@ -62,7 +62,9 @@ public sealed partial class LocalizationRulesTests public void EveryTextKeyInTheCode_Exists() { var missing = new List(); - foreach (var file in Directory.EnumerateFiles(Path.Combine(Repository.Root, "src", "Khaemhat.Web"), "*.*", SearchOption.AllDirectories) + // The web project, and the application one where the dashboard catalog and sources name their texts. + foreach (var file in new[] { "Khaemhat.Web", "Khaemhat.Application" } + .SelectMany(project => Directory.EnumerateFiles(Path.Combine(Repository.Root, "src", project), "*.*", SearchOption.AllDirectories)) .Where(f => (f.EndsWith(".razor", StringComparison.Ordinal) || f.EndsWith(".cs", StringComparison.Ordinal)) && !Repository.IsBuildOutput(f))) { foreach (Match match in KeyPattern().Matches(File.ReadAllText(file))) @@ -269,6 +271,6 @@ public sealed partial class LocalizationRulesTests [GeneratedRegex(@"&[a-zA-Z]+;|&#\d+;")] private static partial Regex EntityPattern(); - [GeneratedRegex("\"((?:Shell|Pages|Auth|Common|Ui)\\.[A-Za-z0-9_.]+)\"")] + [GeneratedRegex("\"((?:Shell|Pages|Auth|Common|Ui|Dashboard)\\.[A-Za-z0-9_.]+)\"")] private static partial Regex KeyPattern(); }