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 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 19:15:06 +01:00
1 parent 75d60ee4c4
commit acb7e598d1
34 files changed
+2812 -76

No files matched your search

+8 -2
View File
@@ -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.
+16
View File
@@ -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 |
+47
View File
@@ -0,0 +1,47 @@
# ADR 0022 - Dashboard a widget: layout per utente e per ruolo, liste fornite dai moduli
- **Stato:** accettata
- **Data:** 2026-11-11
- **Modifica:** SPEC §10.3, §11.12; milestone M3, issue #30 e #31
## Contesto
La specifica descrive la dashboard (mockup 004-006) con widget attivabili, ordinabili e ridimensionabili, una pagina
iniziale scelta dall'utente e un layout predefinito per ruolo, ma non dice dove si salvano i layout dei ruoli, quale
layout vede chi non ha mai personalizzato, né come i moduli che arrivano dopo M3 (vendite, magazzino, CRM) riempiono
i widget. Lascia anche aperto il comando per tornare alla disposizione iniziale.
## Decisione
1. **Catalogo fisso.** I widget sono un catalogo nel codice (`WidgetCatalog`): id, titolo, icona, larghezza
predefinita, modulo di licenza, permesso di lettura, solo amministratori, milestone che porta i dati. Un widget è
*disponibile* se il modulo è attivo, l'utente ha il permesso e, per *Stato del sistema*, è un account di istanza.
2. **Layout in JSON.** `{"v":1,"widgets":[{"id":"todo","w":4}]}`: l'ordine è quello dell'elenco, le larghezze sono 3,
4, 6, 8 o 12 colonne (una larghezza diversa va alla più vicina, la più larga a parità). Leggendolo si scartano id
sconosciuti e ripetuti; un layout illeggibile vale come assente. Al massimo 30 widget.
3. **Dove si salva.** Il layout dell'utente è un'impostazione utente (`dashboard.layout`, ADR 0020: sistema per gli
account di istanza, azienda per gli utenti aziendali). Il layout di un ruolo è un'impostazione **dell'azienda**
(`dashboard.layout.role.<CODICE>`) nella nuova tabella `company_settings`, scritta da `CompanySettingsService`
con il permesso `company.settings.write`. Promemoria (`dashboard.notes`) e scorciatoie (`dashboard.shortcuts`)
sono impostazioni utente.
4. **Quale layout si vede.** Quello dell'utente; altrimenti quello del primo ruolo dell'utente (per id) che ne ha uno;
altrimenti il layout di Khaemhat. In ogni caso si tolgono i widget non disponibili. **Ripristina** cancella il
layout dell'utente e riporta quello del ruolo o di Khaemhat.
5. **Layout di Khaemhat.** Solo widget che hanno già dati: Da fare oggi, Fatto oggi, Scadenze, Scorciatoie,
Promemoria, Stato del sistema. I widget dei moduli futuri (KPI, Da evadere, Fatturato, Sottoscorta, CRM, Ultimi
documenti) si possono già accendere e mostrano da quale milestone arrivano i dati, senza numeri finti.
6. **Liste dai moduli.** *Da fare oggi*, *Fatto oggi* e *Scadenze 30 giorni* raccolgono le righe da sorgenti
registrate nel contenitore (`ITodoSource`, `IDoneSource`, `IDeadlineSource`): ogni modulo aggiunge le sue. Le
sorgenti si chiamano una dopo l'altra; una che fallisce si scrive nel log e si salta, il widget mostra le altre.
In M3 ci sono licenza, avvisi non letti e attività programmate.
7. **Personalizza.** Pannello laterale non modale (la pagina resta visibile) con pagina iniziale, interruttore della
dashboard, elenco dei widget con interruttore, larghezza e frecce, e il predefinito per ruolo per chi gestisce
l'azienda. Sulla griglia i widget si trascinano (HTML drag and drop) e hanno anche pulsanti per spostare,
allargare, restringere e nascondere, così tutto funziona da tastiera. Ogni modifica si salva subito.
## Conseguenze
- I moduli di M5, M6 e M11 riempiono i widget registrando sorgenti e sostituendo il componente del widget; il layout
salvato dagli utenti resta valido.
- `company_settings` è il posto per le altre impostazioni di azienda delle prossime milestone.
- Un utente con più ruoli prende il predefinito del primo; se servirà una priorità esplicita fra ruoli si aggiungerà.
+54 -21
View File
@@ -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.
@@ -0,0 +1,186 @@
using Khaemhat.Application.Security;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Application.Dashboard;
/// <summary>The colour of a line in a dashboard list.</summary>
public enum FeedTone
{
/// <summary>Nothing special.</summary>
Neutral = 0,
/// <summary>Information.</summary>
Info = 1,
/// <summary>Done, fine.</summary>
Ok = 2,
/// <summary>Needs attention.</summary>
Warning = 3,
/// <summary>Something went wrong.</summary>
Error = 4,
}
/// <summary>
/// A line of <em>Da fare oggi</em>, <em>Fatto oggi</em> or <em>Scadenze</em>. The texts are already in the user's
/// language; <see cref="AreaKey"/> is the text key of the area label (Sistema, Vendite, Fiscale…).
/// </summary>
/// <param name="Id">A stable id, unique within the list.</param>
/// <param name="Text">What it is.</param>
/// <param name="AreaKey">The text key of the area.</param>
/// <param name="Tone">The colour.</param>
public sealed record FeedItem(string Id, string Text, string AreaKey, FeedTone Tone = FeedTone.Neutral)
{
/// <summary>A second line, if any.</summary>
public string? Detail { get; init; }
/// <summary>When: the time for what was done, the date for a deadline.</summary>
public DateTimeOffset? When { get; init; }
/// <summary>Where it opens, a local address.</summary>
public string? Href { get; init; }
/// <summary>Higher first, for the things to do.</summary>
public int Priority { get; init; }
}
/// <summary>Who asks and when.</summary>
/// <param name="Actor">The user.</param>
/// <param name="Now">The local time now.</param>
public sealed record FeedContext(Actor Actor, DateTimeOffset Now)
{
/// <summary>Today, local.</summary>
public DateOnly Today => DateOnly.FromDateTime(Now.DateTime);
/// <summary>The start of today, local.</summary>
public DateTimeOffset StartOfToday => new(Now.Date, Now.Offset);
}
/// <summary>A source of things to do today (rejected SDI invoices, VAT settlements, procedures waiting… as the modules come).</summary>
public interface ITodoSource
{
/// <summary>The things to do.</summary>
/// <param name="context">Who and when.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The lines.</returns>
Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, CancellationToken cancellationToken);
}
/// <summary>A source of things done today (documents issued, collections, backups, scheduled tasks…).</summary>
public interface IDoneSource
{
/// <summary>The things done.</summary>
/// <param name="context">Who and when.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The lines.</returns>
Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, CancellationToken cancellationToken);
}
/// <summary>A source of deadlines (fiscal, sales, treasury, contracts…).</summary>
public interface IDeadlineSource
{
/// <summary>The deadlines from today up to the horizon.</summary>
/// <param name="context">Who and when.</param>
/// <param name="until">The last day included.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The lines, with <see cref="FeedItem.When"/> set.</returns>
Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, DateOnly until, CancellationToken cancellationToken);
}
/// <summary>
/// Runs every source of one kind and merges what they say. A source that fails is logged and left out: one broken
/// module must not empty the whole dashboard.
/// </summary>
public abstract class FeedAggregator
{
/// <summary>The most lines a widget shows.</summary>
public const int MaxItems = 50;
/// <summary>Runs the sources one after the other (they share the database connections of the scope).</summary>
/// <param name="sources">The calls.</param>
/// <param name="logger">Where failures go.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>All the lines.</returns>
protected static async Task<List<FeedItem>> CollectAsync(
IEnumerable<(string Name, Func<Task<IReadOnlyList<FeedItem>>> Call)> sources, ILogger logger, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(sources);
var items = new List<FeedItem>();
foreach (var (name, call) in sources)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
items.AddRange(await call().ConfigureAwait(false));
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
logger.LogWarning(ex, "Dashboard source {Source} failed and was left out.", name);
}
}
return items;
}
}
/// <summary>What to do today, the most urgent first.</summary>
/// <param name="sources">The sources.</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log.</param>
public sealed class TodoAggregator(IEnumerable<ITodoSource> sources, TimeProvider clock, ILogger<TodoAggregator> logger) : FeedAggregator
{
/// <summary>The things to do.</summary>
/// <param name="actor">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Higher priority first, then the oldest.</returns>
public async Task<IReadOnlyList<FeedItem>> GetAsync(Actor actor, CancellationToken cancellationToken = default)
{
var context = new FeedContext(actor, clock.GetLocalNow());
var items = await CollectAsync(sources.Select(s => (s.GetType().Name, (Func<Task<IReadOnlyList<FeedItem>>>)(() => s.GetAsync(context, cancellationToken)))), logger, cancellationToken).ConfigureAwait(false);
return [.. items.OrderByDescending(i => i.Priority).ThenBy(i => i.When ?? DateTimeOffset.MaxValue).Take(MaxItems)];
}
}
/// <summary>What was done today, the latest first.</summary>
/// <param name="sources">The sources.</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log.</param>
public sealed class DoneAggregator(IEnumerable<IDoneSource> sources, TimeProvider clock, ILogger<DoneAggregator> logger) : FeedAggregator
{
/// <summary>The things done today.</summary>
/// <param name="actor">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The latest first.</returns>
public async Task<IReadOnlyList<FeedItem>> GetAsync(Actor actor, CancellationToken cancellationToken = default)
{
var context = new FeedContext(actor, clock.GetLocalNow());
var items = await CollectAsync(sources.Select(s => (s.GetType().Name, (Func<Task<IReadOnlyList<FeedItem>>>)(() => s.GetAsync(context, cancellationToken)))), logger, cancellationToken).ConfigureAwait(false);
return [.. items.OrderByDescending(i => i.When ?? DateTimeOffset.MinValue).Take(MaxItems)];
}
}
/// <summary>The deadlines of the next days, the nearest first.</summary>
/// <param name="sources">The sources.</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log.</param>
public sealed class DeadlineAggregator(IEnumerable<IDeadlineSource> sources, TimeProvider clock, ILogger<DeadlineAggregator> logger) : FeedAggregator
{
/// <summary>How far the widget looks ahead.</summary>
public const int HorizonDays = 30;
/// <summary>The deadlines from today to <see cref="HorizonDays"/> days ahead.</summary>
/// <param name="actor">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The nearest first.</returns>
public async Task<IReadOnlyList<FeedItem>> GetAsync(Actor actor, CancellationToken cancellationToken = default)
{
var context = new FeedContext(actor, clock.GetLocalNow());
var until = context.Today.AddDays(HorizonDays);
var items = await CollectAsync(sources.Select(s => (s.GetType().Name, (Func<Task<IReadOnlyList<FeedItem>>>)(() => s.GetAsync(context, until, cancellationToken)))), logger, cancellationToken).ConfigureAwait(false);
return [.. items
.Where(i => i.When is { } when && DateOnly.FromDateTime(when.DateTime) >= context.Today && DateOnly.FromDateTime(when.DateTime) <= until)
.OrderBy(i => i.When)
.Take(MaxItems)];
}
}
@@ -0,0 +1,166 @@
using System.Text.Json;
using System.Text.Json.Nodes;
namespace Khaemhat.Application.Dashboard;
/// <summary>A widget on the dashboard: which one and how wide.</summary>
/// <param name="Id">The widget id (<see cref="WidgetIds"/>).</param>
/// <param name="Width">The width in columns of twelve: 3, 4, 6, 8 or 12.</param>
public sealed record WidgetPlacement(string Id, int Width);
/// <summary>
/// The widgets shown, in order, with their width (SPEC §10.3). A widget that is not in the list is switched off.
/// Kept as JSON in <c>user_settings</c> (<c>dashboard.layout</c>) and, as the default of a role, in
/// <c>company_settings</c>: <c>{"v":1,"widgets":[{"id":"todo","w":4}]}</c>.
/// </summary>
/// <param name="Widgets">The widgets in order.</param>
public sealed record DashboardLayout(IReadOnlyList<WidgetPlacement> Widgets)
{
/// <summary>The most widgets a layout keeps.</summary>
public const int MaxWidgets = 30;
private const int Version = 1;
/// <summary>Whether a widget is shown.</summary>
/// <param name="id">The widget id.</param>
/// <returns><see langword="true"/> when it is in the layout.</returns>
public bool Contains(string id) => Widgets.Any(w => w.Id == id);
/// <summary>The width of a widget, or its default when not shown.</summary>
/// <param name="id">The widget id.</param>
/// <returns>The width.</returns>
public int WidthOf(string id) =>
Widgets.FirstOrDefault(w => w.Id == id)?.Width ?? WidgetCatalog.Find(id)?.DefaultWidth ?? 4;
/// <summary>Reads a layout saved as JSON.</summary>
/// <param name="json">The JSON, or <see langword="null"/>.</param>
/// <returns>The layout without unknown widgets, duplicates or invalid widths; <see langword="null"/> when there
/// is none or it cannot be read.</returns>
public static DashboardLayout? Parse(string? json)
{
if (string.IsNullOrWhiteSpace(json))
{
return null;
}
try
{
if (JsonNode.Parse(json) is not JsonObject root || root["widgets"] is not JsonArray array)
{
return null;
}
var widgets = new List<WidgetPlacement>();
foreach (var node in array)
{
if (node is JsonObject item && item["id"]?.GetValueKind() == JsonValueKind.String)
{
var width = item["w"]?.GetValueKind() == JsonValueKind.Number ? item["w"]!.GetValue<int>() : 0;
widgets.Add(new WidgetPlacement(item["id"]!.GetValue<string>(), width));
}
}
return new DashboardLayout(widgets).Normalize();
}
catch (Exception ex) when (ex is JsonException or FormatException or InvalidOperationException)
{
return null;
}
}
/// <summary>The layout as JSON.</summary>
/// <returns>The JSON.</returns>
public string ToJson()
{
var array = new JsonArray();
foreach (var widget in Normalize().Widgets)
{
array.Add(new JsonObject { ["id"] = widget.Id, ["w"] = widget.Width });
}
return new JsonObject { ["v"] = Version, ["widgets"] = array }.ToJsonString();
}
/// <summary>Drops unknown widgets and repeated ones and snaps the widths to the allowed ones.</summary>
/// <returns>The clean layout.</returns>
public DashboardLayout Normalize()
{
var seen = new HashSet<string>(StringComparer.Ordinal);
var widgets = new List<WidgetPlacement>();
foreach (var widget in Widgets)
{
if (WidgetCatalog.Find(widget.Id) is { } definition && seen.Add(widget.Id) && widgets.Count < MaxWidgets)
{
widgets.Add(new WidgetPlacement(definition.Id, widget.Width <= 0 ? definition.DefaultWidth : WidgetDefinition.Snap(widget.Width)));
}
}
return new DashboardLayout(widgets);
}
/// <summary>Only the widgets that pass a test, such as those the user may see.</summary>
/// <param name="keep">The test.</param>
/// <returns>The layout.</returns>
public DashboardLayout Where(Func<string, bool> keep)
{
ArgumentNullException.ThrowIfNull(keep);
return new DashboardLayout([.. Widgets.Where(w => keep(w.Id))]);
}
/// <summary>Shows a widget at the end, or hides it.</summary>
/// <param name="id">The widget id.</param>
/// <param name="visible">Whether to show it.</param>
/// <returns>The layout.</returns>
public DashboardLayout Toggle(string id, bool visible)
{
if (visible == Contains(id) || WidgetCatalog.Find(id) is not { } definition)
{
return this;
}
return visible
? new DashboardLayout([.. Widgets, new WidgetPlacement(id, definition.DefaultWidth)])
: new DashboardLayout([.. Widgets.Where(w => w.Id != id)]);
}
/// <summary>Changes the width of a widget.</summary>
/// <param name="id">The widget id.</param>
/// <param name="width">The new width (snapped to the allowed ones).</param>
/// <returns>The layout.</returns>
public DashboardLayout Resize(string id, int width) =>
new([.. Widgets.Select(w => w.Id == id ? w with { Width = WidgetDefinition.Snap(width) } : w)]);
/// <summary>Moves a widget by some places.</summary>
/// <param name="id">The widget id.</param>
/// <param name="offset">-1 before the previous one, +1 after the next one.</param>
/// <returns>The layout.</returns>
public DashboardLayout Move(string id, int offset)
{
var index = Widgets.ToList().FindIndex(w => w.Id == id);
return index < 0 ? this : MoveTo(id, Math.Clamp(index + offset, 0, Widgets.Count - 1));
}
/// <summary>Moves a widget to a position, as dropping it on another widget does.</summary>
/// <param name="id">The widget id.</param>
/// <param name="index">The new position.</param>
/// <returns>The layout.</returns>
public DashboardLayout MoveTo(string id, int index)
{
var list = Widgets.ToList();
var from = list.FindIndex(w => w.Id == id);
if (from < 0)
{
return this;
}
var widget = list[from];
list.RemoveAt(from);
list.Insert(Math.Clamp(index, 0, list.Count), widget);
return new DashboardLayout(list);
}
/// <summary>Whether two layouts show the same widgets in the same order and widths.</summary>
/// <param name="other">The other layout.</param>
/// <returns><see langword="true"/> when they look the same.</returns>
public bool SameAs(DashboardLayout? other) => other is not null && Widgets.SequenceEqual(other.Widgets);
}
@@ -0,0 +1,284 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Preferences;
using Khaemhat.Application.Security;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Dashboard;
/// <summary>Where the layout shown comes from.</summary>
public enum DashboardLayoutSource
{
/// <summary>The built-in layout of <see cref="WidgetCatalog.BuiltIn"/>.</summary>
BuiltIn = 0,
/// <summary>The default of one of the user's roles.</summary>
Role = 1,
/// <summary>The user's own layout.</summary>
User = 2,
}
/// <summary>The dashboard of a user: the layout and where it comes from.</summary>
/// <param name="Layout">The widgets the user may see, in order.</param>
/// <param name="Source">Where it comes from.</param>
/// <param name="RoleCode">The role whose default is used, when <see cref="Source"/> is <see cref="DashboardLayoutSource.Role"/>.</param>
public sealed record DashboardView(DashboardLayout Layout, DashboardLayoutSource Source, string? RoleCode = null);
/// <summary>A personal reminder of the dashboard.</summary>
/// <param name="Text">What to remember.</param>
/// <param name="Done">Whether it is ticked.</param>
public sealed record PersonalNote(string Text, bool Done);
/// <summary>
/// The dashboard of SPEC §10.3: which widgets a user may see, the layout to show (the user's own, else the default
/// of one of their roles, else the built-in one), the personal reminders and the shortcuts. Everything belongs to the
/// user in <c>user_settings</c>; the role defaults belong to the company in <c>company_settings</c>.
/// </summary>
/// <param name="settings">The user's settings.</param>
/// <param name="company">The company's settings.</param>
/// <param name="factory">Opens the company database, for the roles of a user.</param>
/// <param name="permissions">The user's permissions.</param>
/// <param name="licenses">The licensed modules.</param>
public sealed class DashboardService(
UserSettingsService settings,
CompanySettingsService company,
IUnitOfWorkFactory factory,
PermissionService permissions,
ILicenseGate licenses)
{
/// <summary>The key of the user's layout.</summary>
public const string LayoutKey = "dashboard.layout";
/// <summary>The key of the personal reminders.</summary>
public const string NotesKey = "dashboard.notes";
/// <summary>The key of the shortcuts.</summary>
public const string ShortcutsKey = "dashboard.shortcuts";
/// <summary>The start of the keys of the role defaults in <c>company_settings</c>.</summary>
public const string RolePrefix = "dashboard.layout.role.";
/// <summary>The most reminders kept.</summary>
public const int MaxNotes = 20;
/// <summary>The longest reminder.</summary>
public const int MaxNoteLength = 300;
/// <summary>The most shortcuts kept.</summary>
public const int MaxShortcuts = 12;
/// <summary>The key of the default layout of a role.</summary>
/// <param name="roleCode">The role code.</param>
/// <returns>The key.</returns>
public static string RoleKey(string roleCode) => RolePrefix + roleCode;
/// <summary>The widgets a user may see: licensed module, permission, administrators only.</summary>
/// <param name="actor">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The widgets in catalog order.</returns>
public async Task<IReadOnlyList<WidgetDefinition>> AvailableAsync(Actor actor, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var granted = await permissions.GetAsync(actor, cancellationToken).ConfigureAwait(false);
return [.. WidgetCatalog.All.Where(w =>
licenses.IsModuleActive(w.Module)
&& (!w.InstanceOnly || actor.IsInstanceAccount)
&& (w.Permission is null || granted.Allows(w.Permission)))];
}
/// <summary>The dashboard to show.</summary>
/// <param name="actor">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The layout, limited to the widgets the user may see, and where it comes from.</returns>
public async Task<DashboardView> GetAsync(Actor actor, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var available = (await AvailableAsync(actor, cancellationToken).ConfigureAwait(false)).Select(w => w.Id).ToHashSet(StringComparer.Ordinal);
if (DashboardLayout.Parse(await settings.GetAsync(actor, LayoutKey, cancellationToken).ConfigureAwait(false)) is { } own)
{
return new DashboardView(own.Where(available.Contains), DashboardLayoutSource.User);
}
if (await RoleDefaultAsync(actor, cancellationToken).ConfigureAwait(false) is { } fromRole)
{
return new DashboardView(fromRole.Layout.Where(available.Contains), DashboardLayoutSource.Role, fromRole.RoleCode);
}
return new DashboardView(WidgetCatalog.BuiltIn.Where(available.Contains), DashboardLayoutSource.BuiltIn);
}
/// <summary>Saves the user's layout.</summary>
/// <param name="actor">The user.</param>
/// <param name="layout">The layout.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task SaveAsync(Actor actor, DashboardLayout layout, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(layout);
return settings.SetAsync(actor, LayoutKey, layout.ToJson(), cancellationToken);
}
/// <summary>Forgets the user's layout: the role default or the built-in one comes back.</summary>
/// <param name="actor">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task ResetAsync(Actor actor, CancellationToken cancellationToken = default) =>
settings.SetAsync(actor, LayoutKey, null, cancellationToken);
/// <summary>The roles of the company with their default layout, if they have one.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The roles in name order.</returns>
public async Task<IReadOnlyList<(Role Role, DashboardLayout? Layout)>> RoleDefaultsAsync(string companyCode, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(companyCode);
var defaults = await company.GetAllAsync(companyCode, RolePrefix, cancellationToken).ConfigureAwait(false);
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var roles = (await unitOfWork.Repository<Role, long>().ListAsync(Query.For<Role>(), cancellationToken).ConfigureAwait(false)).Items;
return [.. roles.OrderBy(r => r.Name, StringComparer.CurrentCulture)
.Select(r => (r, defaults.TryGetValue(RoleKey(r.Code), out var json) ? DashboardLayout.Parse(json) : null))];
}
/// <summary>Sets or removes (<see langword="null"/>) the default layout of a role.</summary>
/// <param name="actor">Who sets it: needs <c>company.settings.write</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="roleCode">The role.</param>
/// <param name="layout">The layout, or <see langword="null"/>.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task SaveRoleDefaultAsync(Actor actor, string companyCode, string roleCode, DashboardLayout? layout, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(roleCode);
return company.SetAsync(actor, companyCode, RoleKey(roleCode), layout?.ToJson(), cancellationToken);
}
/// <summary>The personal reminders.</summary>
/// <param name="actor">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The reminders in order.</returns>
public async Task<IReadOnlyList<PersonalNote>> GetNotesAsync(Actor actor, CancellationToken cancellationToken = default)
{
var json = await settings.GetAsync(actor, NotesKey, cancellationToken).ConfigureAwait(false);
var notes = new List<PersonalNote>();
foreach (var node in ReadArray(json))
{
if (node is JsonObject item && item["t"]?.GetValueKind() == JsonValueKind.String)
{
notes.Add(new PersonalNote(item["t"]!.GetValue<string>(), item["d"]?.GetValueKind() == JsonValueKind.True));
}
}
return CleanNotes(notes);
}
/// <summary>Saves the personal reminders (at most <see cref="MaxNotes"/>, each up to <see cref="MaxNoteLength"/> characters).</summary>
/// <param name="actor">The user.</param>
/// <param name="notes">The reminders.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task SaveNotesAsync(Actor actor, IReadOnlyList<PersonalNote> notes, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(notes);
var array = new JsonArray();
foreach (var note in CleanNotes(notes))
{
array.Add(new JsonObject { ["t"] = note.Text, ["d"] = note.Done });
}
return settings.SetAsync(actor, NotesKey, array.Count == 0 ? null : array.ToJsonString(), cancellationToken);
}
/// <summary>The addresses of the shortcut buttons.</summary>
/// <param name="actor">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The addresses in order; <see langword="null"/> when the user never chose them.</returns>
public async Task<IReadOnlyList<string>?> GetShortcutsAsync(Actor actor, CancellationToken cancellationToken = default)
{
var json = await settings.GetAsync(actor, ShortcutsKey, cancellationToken).ConfigureAwait(false);
if (json is null)
{
return null;
}
return CleanShortcuts(ReadArray(json).Where(n => n?.GetValueKind() == JsonValueKind.String).Select(n => n!.GetValue<string>()));
}
/// <summary>Saves the shortcut buttons (local addresses only, at most <see cref="MaxShortcuts"/>).</summary>
/// <param name="actor">The user.</param>
/// <param name="paths">The addresses.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task SaveShortcutsAsync(Actor actor, IReadOnlyList<string> paths, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(paths);
var array = new JsonArray();
foreach (var path in CleanShortcuts(paths))
{
array.Add(path);
}
return settings.SetAsync(actor, ShortcutsKey, array.ToJsonString(), cancellationToken);
}
private static List<PersonalNote> CleanNotes(IEnumerable<PersonalNote> notes) =>
[
.. notes.Select(n => n with { Text = (n.Text ?? string.Empty).Trim() })
.Where(n => n.Text.Length > 0)
.Select(n => n.Text.Length > MaxNoteLength ? n with { Text = n.Text[..MaxNoteLength] } : n)
.Take(MaxNotes),
];
private static List<string> CleanShortcuts(IEnumerable<string> paths) =>
[.. paths.Where(UserPreferences.IsLocalPath).Distinct(StringComparer.OrdinalIgnoreCase).Take(MaxShortcuts)];
private static JsonArray ReadArray(string? json)
{
if (string.IsNullOrWhiteSpace(json))
{
return [];
}
try
{
return JsonNode.Parse(json) as JsonArray ?? [];
}
catch (JsonException)
{
return [];
}
}
// The default of the first of the user's roles (in role order) that has one. Instance accounts have no roles.
private async Task<(DashboardLayout Layout, string RoleCode)?> RoleDefaultAsync(Actor actor, CancellationToken cancellationToken)
{
if (actor.CompanyCode is not { } companyCode || actor.CompanyUserId is not { } userId)
{
return null;
}
var defaults = await company.GetAllAsync(companyCode, RolePrefix, cancellationToken).ConfigureAwait(false);
if (defaults.Count == 0)
{
return null;
}
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var roleIds = (await unitOfWork.Repository<UserRole, long>().ListAsync(Query.For<UserRole>().Where(r => r.UserId == userId), cancellationToken).ConfigureAwait(false))
.Items.Select(r => r.RoleId).ToHashSet();
var roles = (await unitOfWork.Repository<Role, long>().ListAsync(Query.For<Role>(), cancellationToken).ConfigureAwait(false)).Items;
foreach (var role in roles.Where(r => roleIds.Contains(r.Id)).OrderBy(r => r.Id))
{
if (defaults.TryGetValue(RoleKey(role.Code), out var json) && DashboardLayout.Parse(json) is { } layout)
{
return (layout, role.Code);
}
}
return null;
}
}
@@ -0,0 +1,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;
/// <summary>Text keys of the dashboard areas (the label at the side of a line).</summary>
public static class FeedAreas
{
/// <summary>System and administration.</summary>
public const string System = "Dashboard.Areas.System";
/// <summary>Messages for the user.</summary>
public const string Notifications = "Dashboard.Areas.Notifications";
}
/// <summary>
/// The licence on the dashboard of the administrators: the expiry among the deadlines, and renewing it among the
/// things to do once it is near, in grace or expired.
/// </summary>
/// <param name="licenses">The licence in force.</param>
/// <param name="texts">The texts.</param>
public sealed class LicenseFeedSource(ILicenseGate licenses, ITexts texts) : ITodoSource, IDeadlineSource
{
/// <summary>Days before the expiry when renewing becomes a thing to do.</summary>
public const int RenewDays = 7;
private const string Href = "/amministrazione/licenze";
/// <inheritdoc />
public Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
var license = licenses.Current;
if (!context.Actor.IsInstanceAccount || license.IsTestMode)
{
return Task.FromResult<IReadOnlyList<FeedItem>>([]);
}
var days = license.DaysLeft(context.Now.UtcDateTime);
FeedItem? item = license.Status switch
{
LicenseStatus.Expired => new FeedItem("license", texts["Dashboard.Feed.LicenseExpired"], FeedAreas.System, FeedTone.Error) { Priority = 100, Href = Href },
LicenseStatus.Grace => new FeedItem("license", texts["Dashboard.Feed.LicenseGrace"], FeedAreas.System, FeedTone.Error) { Priority = 90, Href = Href },
_ when days is { } left && left <= RenewDays => new FeedItem("license", texts.Format("Dashboard.Feed.LicenseRenew", left), FeedAreas.System, FeedTone.Warning)
{
Priority = 50,
Href = Href,
},
_ => null,
};
return Task.FromResult<IReadOnlyList<FeedItem>>(item is null ? [] : [item]);
}
/// <inheritdoc />
public Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, DateOnly until, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
var license = licenses.Current;
if (!context.Actor.IsInstanceAccount || license.IsTestMode || license.ExpiresAt is not { } expires || license.Status != LicenseStatus.Valid)
{
return Task.FromResult<IReadOnlyList<FeedItem>>([]);
}
var when = new DateTimeOffset(DateTime.SpecifyKind(expires, DateTimeKind.Utc)).ToOffset(context.Now.Offset);
if (DateOnly.FromDateTime(when.DateTime) > until)
{
return Task.FromResult<IReadOnlyList<FeedItem>>([]);
}
var key = license.Kind == LicenseKind.Trial ? "Dashboard.Feed.TrialEnds" : "Dashboard.Feed.LicenseEnds";
var near = license.DaysLeft(context.Now.UtcDateTime) <= RenewDays;
return Task.FromResult<IReadOnlyList<FeedItem>>(
[
new FeedItem("license-expiry", texts[key], FeedAreas.System, near ? FeedTone.Warning : FeedTone.Info) { When = when, Href = Href },
]);
}
}
/// <summary>The unread warnings and errors addressed to the user, until they are read.</summary>
/// <param name="notifications">The notifications.</param>
public sealed class NotificationTodoSource(NotificationDispatcher notifications) : ITodoSource
{
/// <inheritdoc />
public async Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
IReadOnlyList<NotificationRecord> 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),
})];
}
}
/// <summary>
/// The scheduled tasks of today for the administrators: those that ran fine among the things done (one line per task),
/// those that failed among the things to do.
/// </summary>
/// <param name="factory">Opens the system database.</param>
/// <param name="texts">The texts.</param>
public sealed class JobRunFeedSource(IUnitOfWorkFactory factory, ITexts texts) : IDoneSource, ITodoSource
{
private const string Href = "/amministrazione/attivita";
/// <inheritdoc />
async Task<IReadOnlyList<FeedItem>> IDoneSource.GetAsync(FeedContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
if (!context.Actor.IsInstanceAccount)
{
return [];
}
var (runs, names) = await TodayAsync(context, cancellationToken).ConfigureAwait(false);
return [.. runs
.Where(r => r.Outcome == JobOutcome.Succeeded)
.GroupBy(r => r.TaskCode, StringComparer.Ordinal)
.Select(g =>
{
var last = g.MaxBy(r => r.FinishedAt ?? r.StartedAt)!;
var when = Local(last.FinishedAt ?? last.StartedAt, context);
// The widget shows the time of the last run at the side: the detail says how many.
var detail = g.Count() == 1 ? texts["Dashboard.Feed.JobRanOnce"] : texts.Format("Dashboard.Feed.JobRanTimes", g.Count());
return new FeedItem("job-" + g.Key, names.GetValueOrDefault(g.Key, g.Key), FeedAreas.System, FeedTone.Ok) { Detail = detail, When = when, Href = Href };
})];
}
/// <inheritdoc />
async Task<IReadOnlyList<FeedItem>> ITodoSource.GetAsync(FeedContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
if (!context.Actor.IsInstanceAccount)
{
return [];
}
var (runs, names) = await TodayAsync(context, cancellationToken).ConfigureAwait(false);
// A task that failed and has not succeeded since is still a thing to do.
return [.. runs
.GroupBy(r => r.TaskCode, StringComparer.Ordinal)
.Select(g => g.MaxBy(r => r.StartedAt)!)
.Where(r => r.Outcome == JobOutcome.Failed)
.Select(r => new FeedItem("job-failed-" + r.TaskCode, texts.Format("Dashboard.Feed.JobFailed", names.GetValueOrDefault(r.TaskCode, r.TaskCode)), FeedAreas.System, FeedTone.Error)
{
Detail = r.Message,
When = Local(r.StartedAt, context),
Href = Href,
Priority = 70,
})];
}
private static DateTimeOffset Local(DateTime utc, FeedContext context) =>
new DateTimeOffset(DateTime.SpecifyKind(utc, DateTimeKind.Utc)).ToOffset(context.Now.Offset);
private async Task<(IReadOnlyList<JobRun> Runs, IReadOnlyDictionary<string, string> Names)> TodayAsync(FeedContext context, CancellationToken cancellationToken)
{
var since = context.StartOfToday.UtcDateTime;
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var runs = (await unitOfWork.Repository<JobRun, long>().ListAsync(Query.For<JobRun>().Where(r => r.StartedAt >= since), cancellationToken).ConfigureAwait(false)).Items;
var tasks = (await unitOfWork.Repository<ScheduledTask, long>().ListAsync(Query.For<ScheduledTask>(), cancellationToken).ConfigureAwait(false)).Items;
return (runs, tasks.ToDictionary(t => t.Code, t => t.Name, StringComparer.Ordinal));
}
}
@@ -0,0 +1,42 @@
using Khaemhat.Application.Instance;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Dashboard;
/// <summary>What the <em>Stato del sistema</em> widget shows besides version, cache and licence.</summary>
/// <param name="Engine">The database engine.</param>
/// <param name="Companies">The companies that are not disabled.</param>
/// <param name="FailedCompanies">Those that failed to open at start-up.</param>
/// <param name="JobsSucceeded">Scheduled task runs of today that succeeded.</param>
/// <param name="JobsFailed">Those that failed.</param>
public sealed record SystemStatus(DbEngine Engine, int Companies, int FailedCompanies, int JobsSucceeded, int JobsFailed);
/// <summary>Reads the state of the instance for the administrators' widget.</summary>
/// <param name="factory">Opens the system database.</param>
/// <param name="system">The system database.</param>
/// <param name="companies">The companies.</param>
/// <param name="bootstrap">What happened at start-up.</param>
/// <param name="clock">The clock.</param>
public sealed class SystemStatusService(IUnitOfWorkFactory factory, DatabaseTarget system, ICompanyRegistry companies, BootstrapState bootstrap, TimeProvider clock)
{
/// <summary>The state now.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The state.</returns>
public async Task<SystemStatus> GetAsync(CancellationToken cancellationToken = default)
{
var all = await companies.ListAsync(cancellationToken).ConfigureAwait(false);
var now = clock.GetLocalNow();
var since = new DateTimeOffset(now.Date, now.Offset).UtcDateTime;
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var runs = (await unitOfWork.Repository<JobRun, long>().ListAsync(Query.For<JobRun>().Where(r => r.StartedAt >= since), cancellationToken).ConfigureAwait(false)).Items;
return new SystemStatus(
system.Engine,
all.Count(c => c.Status != CompanyStatus.Disabled),
bootstrap.FailedCompanies.Count,
runs.Count(r => r.Outcome == JobOutcome.Succeeded),
runs.Count(r => r.Outcome == JobOutcome.Failed));
}
}
@@ -0,0 +1,132 @@
using Khaemhat.Application.Modules;
namespace Khaemhat.Application.Dashboard;
/// <summary>
/// A widget of the dashboard (SPEC §10.3, mockup 004): what it is, how wide it starts and who may see it. The
/// <see cref="Milestone"/> of a widget whose data comes from a later module says where its data will come from; until
/// then the widget shows that instead of invented numbers.
/// </summary>
/// <param name="Id">The id, kept in the layouts.</param>
/// <param name="TitleKey">The text key of the title.</param>
/// <param name="Icon">The icon.</param>
/// <param name="DefaultWidth">The starting width in columns of twelve.</param>
/// <param name="Module">The licensed module it needs.</param>
/// <param name="Permission">The permission it needs, if any.</param>
/// <param name="InstanceOnly">Only for administrators of the instance.</param>
/// <param name="Milestone">The milestone that brings its data, if still to come.</param>
public sealed record WidgetDefinition(
string Id,
string TitleKey,
string Icon,
int DefaultWidth,
string Module,
string? Permission = null,
bool InstanceOnly = false,
string? Milestone = null)
{
/// <summary>The widths a widget can take, in columns of twelve.</summary>
public static readonly IReadOnlyList<int> Widths = [3, 4, 6, 8, 12];
/// <summary>The text key of the description shown in the customize panel.</summary>
public string DescriptionKey => TitleKey[..TitleKey.LastIndexOf('.')] + ".Description";
/// <summary>The nearest allowed width.</summary>
/// <param name="width">Any number.</param>
/// <returns>One of <see cref="Widths"/>.</returns>
public static int Snap(int width) => Widths.OrderBy(w => Math.Abs(w - width)).ThenByDescending(w => w).First();
/// <summary>The next width up or down, staying at the ends.</summary>
/// <param name="width">The current width.</param>
/// <param name="step">+1 wider, -1 narrower.</param>
/// <returns>The width.</returns>
public static int Step(int width, int step)
{
var index = Math.Clamp(Widths.ToList().IndexOf(Snap(width)) + Math.Sign(step), 0, Widths.Count - 1);
return Widths[index];
}
}
/// <summary>The ids of the widgets.</summary>
public static class WidgetIds
{
/// <summary>Indicators chosen by the user.</summary>
public const string Kpi = "kpi";
/// <summary>What to do today.</summary>
public const string Todo = "todo";
/// <summary>What was done today.</summary>
public const string Done = "done";
/// <summary>Deadlines of the next 30 days.</summary>
public const string Deadlines = "deadlines";
/// <summary>Orders and delivery notes still to fulfil.</summary>
public const string ToFulfil = "to-fulfil";
/// <summary>Revenue of the last 12 months.</summary>
public const string Revenue = "revenue";
/// <summary>CRM activities.</summary>
public const string CrmActivities = "crm-activities";
/// <summary>Personal reminders.</summary>
public const string Notes = "notes";
/// <summary>Shortcut buttons.</summary>
public const string Shortcuts = "shortcuts";
/// <summary>Items under the minimum stock.</summary>
public const string Understock = "understock";
/// <summary>The CRM pipeline.</summary>
public const string Pipeline = "pipeline";
/// <summary>The last documents.</summary>
public const string RecentDocuments = "recent-documents";
/// <summary>State of the system (administrators).</summary>
public const string SystemStatus = "system";
}
/// <summary>Every widget, in the order of the customize panel (SPEC §10.3).</summary>
public static class WidgetCatalog
{
/// <summary>The widgets.</summary>
public static IReadOnlyList<WidgetDefinition> All { get; } =
[
new(WidgetIds.Kpi, "Dashboard.Widgets.Kpi.Title", "chart", 12, ModuleCodes.Core, "sales.invoice.read", Milestone: "M5"),
new(WidgetIds.Todo, "Dashboard.Widgets.Todo.Title", "check-circle", 4, ModuleCodes.Core),
new(WidgetIds.Done, "Dashboard.Widgets.Done.Title", "check", 4, ModuleCodes.Core),
new(WidgetIds.Deadlines, "Dashboard.Widgets.Deadlines.Title", "calendar", 4, ModuleCodes.Core),
new(WidgetIds.ToFulfil, "Dashboard.Widgets.ToFulfil.Title", "truck", 8, ModuleCodes.Core, "sales.order.read", Milestone: "M5"),
new(WidgetIds.Revenue, "Dashboard.Widgets.Revenue.Title", "chart", 4, ModuleCodes.Core, "sales.invoice.read", Milestone: "M5"),
new(WidgetIds.CrmActivities, "Dashboard.Widgets.CrmActivities.Title", "target", 6, ModuleCodes.Crm, "crm.lead.read", Milestone: "M11"),
new(WidgetIds.Notes, "Dashboard.Widgets.Notes.Title", "edit", 4, ModuleCodes.Core),
new(WidgetIds.Shortcuts, "Dashboard.Widgets.Shortcuts.Title", "zap", 4, ModuleCodes.Core),
new(WidgetIds.Understock, "Dashboard.Widgets.Understock.Title", "box", 6, ModuleCodes.Core, "inventory.stock.read", Milestone: "M6"),
new(WidgetIds.Pipeline, "Dashboard.Widgets.Pipeline.Title", "target", 6, ModuleCodes.Crm, "crm.lead.read", Milestone: "M11"),
new(WidgetIds.RecentDocuments, "Dashboard.Widgets.RecentDocuments.Title", "file", 6, ModuleCodes.Core, "sales.invoice.read", Milestone: "M5"),
new(WidgetIds.SystemStatus, "Dashboard.Widgets.System.Title", "shield", 4, ModuleCodes.Core, InstanceOnly: true),
];
/// <summary>
/// The layout of whoever never customized it and has no default from a role: the widgets that already have data.
/// Those that wait for a later module stay in the panel, ready to be switched on.
/// </summary>
public static DashboardLayout BuiltIn { get; } = new(
[
new(WidgetIds.Todo, 4),
new(WidgetIds.Done, 4),
new(WidgetIds.Deadlines, 4),
new(WidgetIds.Shortcuts, 4),
new(WidgetIds.Notes, 4),
new(WidgetIds.SystemStatus, 4),
]);
/// <summary>Finds a widget.</summary>
/// <param name="id">The id.</param>
/// <returns>The widget, or <see langword="null"/>.</returns>
public static WidgetDefinition? Find(string? id) => All.FirstOrDefault(w => string.Equals(w.Id, id, StringComparison.Ordinal));
}
@@ -0,0 +1,126 @@
using Khaemhat.Application.Security;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Instance;
/// <summary>
/// Reads and writes the preferences of a company as a whole (<c>company_settings</c>, SPEC §11.12): the default
/// dashboard of each role today, the company options of the later modules tomorrow. Reading is open to the company
/// code (the callers check what they show); writing needs <c>company.settings.write</c>.
/// </summary>
/// <param name="factory">Opens the databases.</param>
/// <param name="permissions">Checks the permission to write.</param>
public sealed class CompanySettingsService(IUnitOfWorkFactory factory, PermissionService permissions)
{
/// <summary>The permission to change the settings.</summary>
public const string WritePermission = "company.settings.write";
/// <summary>The longest value accepted (layouts are JSON).</summary>
public const int MaxValueLength = 64 * 1024;
/// <summary>Reads the settings of a company, all or those whose key starts with a prefix.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="prefix">The start of the keys, or <see langword="null"/> for all.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The values by key.</returns>
public async Task<IReadOnlyDictionary<string, string?>> GetAllAsync(string companyCode, string? prefix = null, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(companyCode);
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var rows = await ListAsync(unitOfWork, cancellationToken).ConfigureAwait(false);
return rows.Where(r => prefix is null || r.Key.StartsWith(prefix, StringComparison.Ordinal))
.ToDictionary(r => r.Key, r => r.Value, StringComparer.Ordinal);
}
/// <summary>Reads one setting.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="key">The key.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The value, or <see langword="null"/>.</returns>
public async Task<string?> GetAsync(string companyCode, string key, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(key);
var all = await GetAllAsync(companyCode, key, cancellationToken).ConfigureAwait(false);
return all.TryGetValue(key, out var value) ? value : null;
}
/// <summary>Writes one setting; <see langword="null"/> removes it.</summary>
/// <param name="actor">Who writes: needs <see cref="WritePermission"/> in that company.</param>
/// <param name="companyCode">The company.</param>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task SetAsync(Actor actor, string companyCode, string key, string? value, CancellationToken cancellationToken = default) =>
SetManyAsync(actor, companyCode, new Dictionary<string, string?>(StringComparer.Ordinal) { [key] = value }, cancellationToken);
/// <summary>Writes several settings in one transaction; <see langword="null"/> values remove the key.</summary>
/// <param name="actor">Who writes: needs <see cref="WritePermission"/> in that company.</param>
/// <param name="companyCode">The company.</param>
/// <param name="values">The values by key.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
/// <exception cref="AccessDeniedException">The actor may not change this company's settings.</exception>
public async Task SetManyAsync(Actor actor, string companyCode, IReadOnlyDictionary<string, string?> values, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentException.ThrowIfNullOrWhiteSpace(companyCode);
ArgumentNullException.ThrowIfNull(values);
if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, companyCode, StringComparison.OrdinalIgnoreCase))
{
throw new AccessDeniedException("Settings of another company.");
}
await permissions.DemandAsync(actor, WritePermission, cancellationToken).ConfigureAwait(false);
foreach (var (key, value) in values)
{
if (string.IsNullOrWhiteSpace(key) || key.Length > 200)
{
throw new ValidationFailedException("settings.key_invalid");
}
if (value is { Length: > MaxValueLength })
{
throw new ValidationFailedException("settings.value_too_long");
}
}
if (values.Count == 0)
{
return;
}
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
await unitOfWork.InTransactionAsync(ct => WriteAsync(unitOfWork, values, ct), cancellationToken).ConfigureAwait(false);
}
private static async Task<IReadOnlyList<CompanySetting>> ListAsync(IUnitOfWork unitOfWork, CancellationToken cancellationToken) =>
(await unitOfWork.Repository<CompanySetting, long>().ListAsync(Query.For<CompanySetting>(), cancellationToken).ConfigureAwait(false)).Items;
private static async Task WriteAsync(IUnitOfWork unitOfWork, IReadOnlyDictionary<string, string?> values, CancellationToken cancellationToken)
{
var repository = unitOfWork.Repository<CompanySetting, long>();
var existing = (await ListAsync(unitOfWork, cancellationToken).ConfigureAwait(false)).ToDictionary(r => r.Key, StringComparer.Ordinal);
foreach (var (key, value) in values)
{
if (existing.TryGetValue(key, out var row))
{
if (value is null)
{
await repository.DeleteAsync(row.Id, cancellationToken).ConfigureAwait(false);
}
else if (!string.Equals(row.Value, value, StringComparison.Ordinal))
{
row.Value = value;
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
}
}
else if (value is not null)
{
await repository.InsertAsync(new CompanySetting { Key = key, Value = value }, cancellationToken).ConfigureAwait(false);
}
}
}
}
@@ -0,0 +1,16 @@
using Khaemhat.Core.Entities;
namespace Khaemhat.Core.Instance;
/// <summary>
/// A preference of the whole company (<c>company_settings</c>), such as the default dashboard of a role: one value per
/// key, written by whoever holds <c>company.settings.write</c>.
/// </summary>
public sealed class CompanySetting : Entity<long>
{
/// <summary>The key, such as <c>dashboard.layout.role.SALES</c>.</summary>
public string Key { get; set; } = string.Empty;
/// <summary>The value, often JSON.</summary>
public string? Value { get; set; }
}
@@ -108,6 +108,17 @@ public sealed class UserSettingMap : EntityMap<UserSetting>
}
}
/// <summary>Map of <see cref="CompanySetting"/> to <c>company_settings</c>.</summary>
public sealed class CompanySettingMap : EntityMap<CompanySetting>
{
/// <summary>Creates the map.</summary>
public CompanySettingMap()
{
ToTable("company_settings");
Map(x => x.Key).MaxLength(200);
}
}
/// <summary>Map of <see cref="Attachment"/> to <c>attachments</c>.</summary>
public sealed class AttachmentMap : EntityMap<Attachment>
{
@@ -0,0 +1,23 @@
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.CompanyDatabase.Migrations;
/// <summary>The preferences of the company as a whole, such as the default dashboard of each role (SPEC §10.3).</summary>
[Migration(20261111_008, "create_company_settings")]
public sealed class M20261111_008_CreateCompanySettings : IMigration
{
/// <inheritdoc />
public void Up(ISchemaBuilder schema)
{
ArgumentNullException.ThrowIfNull(schema);
schema.CreateTable("company_settings", t =>
{
t.Id();
t.String("key", 200).NotNull();
t.Text("value");
t.AuditColumns();
t.Unique("ux_company_settings_key", "key");
});
}
}
@@ -0,0 +1,18 @@
@* A widget whose data comes from a module still to come (SPEC §10.3): it can already be placed and sized, and says
which milestone fills it. *@
<KhWidget Id="@Definition.Id" Title="@T[Definition.TitleKey]" Icon="@Definition.Icon">
<div class="kh-wcoming">
<KhIcon Name="clock" />
<p class="muted">@T[Definition.DescriptionKey]</p>
@if (Definition.Milestone is { } milestone)
{
<p class="s">@T.Format("Dashboard.Coming.Text", T["Dashboard.Coming." + milestone], milestone)</p>
}
</div>
</KhWidget>
@code {
/// <summary>The widget.</summary>
[Parameter, EditorRequired]
public WidgetDefinition Definition { get; set; } = default!;
}
@@ -0,0 +1,31 @@
@* Picks the component of a widget of the layout. *@
@switch (Definition.Id)
{
case WidgetIds.Todo:
<FeedWidget Definition="Definition" Kind="FeedKind.Todo" />
break;
case WidgetIds.Done:
<FeedWidget Definition="Definition" Kind="FeedKind.Done" />
break;
case WidgetIds.Deadlines:
<FeedWidget Definition="Definition" Kind="FeedKind.Deadlines" />
break;
case WidgetIds.Notes:
<NotesWidget Definition="Definition" />
break;
case WidgetIds.Shortcuts:
<ShortcutsWidget Definition="Definition" />
break;
case WidgetIds.SystemStatus:
<SystemStatusWidget Definition="Definition" />
break;
default:
<ComingWidget Definition="Definition" />
break;
}
@code {
/// <summary>The widget.</summary>
[Parameter, EditorRequired]
public WidgetDefinition Definition { get; set; } = default!;
}
@@ -0,0 +1,140 @@
@inject ShellSession Session
@inject TodoAggregator Todos
@inject DoneAggregator Dones
@inject DeadlineAggregator Deadlines
@inject TimeProvider Clock
@* Da fare oggi, Fatto oggi and Scadenze 30 giorni (SPEC §10.3): the lines the sources of the modules give, with the
area at the side. Mockup 004. *@
<KhWidget Id="@Definition.Id" Title="@T[Definition.TitleKey]" Icon="@Definition.Icon" Tight="true">
<Actions>
@if (_items is { Count: > 0 })
{
<span class="badge @(Kind == FeedKind.Todo && _items.Any(i => i.Tone >= FeedTone.Warning) ? "red" : "gray")">@T.Number(_items.Count)</span>
}
</Actions>
<ChildContent>
@if (_failed)
{
<p class="kh-wempty"><KhIcon Name="alert" /> @T["Dashboard.Feed.Error"]</p>
}
else if (_items is null)
{
<p class="kh-wempty muted">@T["Dashboard.Feed.Loading"]</p>
}
else if (_items.Count == 0)
{
<p class="kh-wempty"><KhIcon Name="check-circle" /> @T[EmptyKey]</p>
}
else if (Kind == FeedKind.Deadlines)
{
<div class="kh-wlist">
@foreach (var item in _items)
{
<a class="deadline" href="@HrefOf(item)" aria-disabled="@(item.Href is null ? "true" : null)">
<div class="dd @DayClass(item)">
<b>@item.When!.Value.ToString("dd", T.Culture)</b>
<span>@item.When!.Value.ToString("MMM", T.Culture)</span>
</div>
<div>
<div class="dt">@item.Text</div>
<div class="ds">@Relative(item)@(item.Detail is null ? null : " · " + item.Detail)</div>
</div>
<span class="badge gray">@T[item.AreaKey]</span>
</a>
}
</div>
}
else
{
<div class="list kh-wlist">
@foreach (var item in _items)
{
<a class="li" href="@HrefOf(item)" aria-disabled="@(item.Href is null ? "true" : null)">
<span class="kh-tone @ToneClass(item.Tone)" aria-hidden="true"></span>
<div class="grow">
<div class="t">@item.Text</div>
@if (item.Detail is not null)
{
<div class="s">@item.Detail</div>
}
</div>
<span class="badge gray">@T[item.AreaKey]</span>
@if (Kind == FeedKind.Done && item.When is { } when)
{
<span class="s num">@when.ToString("HH:mm", T.Culture)</span>
}
</a>
}
</div>
}
</ChildContent>
</KhWidget>
@code {
private IReadOnlyList<FeedItem>? _items;
private bool _failed;
/// <summary>The widget.</summary>
[Parameter, EditorRequired]
public WidgetDefinition Definition { get; set; } = default!;
/// <summary>Which list.</summary>
[Parameter]
public FeedKind Kind { get; set; }
private string EmptyKey => Definition.TitleKey[..Definition.TitleKey.LastIndexOf('.')] + ".Empty";
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
if (Session.Actor is not { } actor)
{
_items = [];
return;
}
try
{
_items = Kind switch
{
FeedKind.Todo => await Todos.GetAsync(actor),
FeedKind.Done => await Dones.GetAsync(actor),
_ => await Deadlines.GetAsync(actor),
};
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_failed = true;
}
}
private static string? HrefOf(FeedItem item) => item.Href?.TrimStart('/') is { } href ? (href.Length == 0 ? "./" : href) : null;
private static string ToneClass(FeedTone tone) => tone switch
{
FeedTone.Ok => "ok",
FeedTone.Info => "info",
FeedTone.Warning => "warn",
FeedTone.Error => "err",
_ => "neutral",
};
private int DaysTo(FeedItem item) =>
DateOnly.FromDateTime(item.When!.Value.DateTime).DayNumber - DateOnly.FromDateTime(Clock.GetLocalNow().DateTime).DayNumber;
private string? DayClass(FeedItem item) => DaysTo(item) switch
{
<= 1 => "hot",
<= 7 => "warm",
_ => null,
};
private string Relative(FeedItem item) => DaysTo(item) switch
{
<= 0 => T["Dashboard.Feed.Today"],
1 => T["Dashboard.Feed.Tomorrow"],
var days => T.Format("Dashboard.Feed.InDays", days),
};
}
@@ -0,0 +1,110 @@
@inject ShellSession Session
@inject DashboardService Dashboard
@inject ToastService Toasts
@* Promemoria personali (SPEC §10.3): free notes of the user, ticked when done, saved as they change. *@
<KhWidget Id="@Definition.Id" Title="@T[Definition.TitleKey]" Icon="@Definition.Icon" Tight="true">
<Actions>
@if (_notes.Any(n => n.Done))
{
<button type="button" class="ib" title="@T["Dashboard.Widgets.Notes.ClearDone"]" aria-label="@T["Dashboard.Widgets.Notes.ClearDone"]"
@onclick="ClearDoneAsync"><KhIcon Name="trash" /></button>
}
</Actions>
<ChildContent>
<div class="kh-wlist">
@for (var i = 0; i < _notes.Count; i++)
{
var index = i;
var note = _notes[i];
<div class="chk-row @(note.Done ? "done" : null)">
<input type="checkbox" checked="@note.Done" aria-label="@T.Format("Dashboard.Widgets.Notes.Toggle", note.Text)"
@onchange="() => ToggleAsync(index)" />
<div class="t">@note.Text</div>
<button type="button" class="ib kh-rowx" title="@T.Format("Dashboard.Widgets.Notes.Remove", note.Text)"
aria-label="@T.Format("Dashboard.Widgets.Notes.Remove", note.Text)" @onclick="() => RemoveAsync(index)"><KhIcon Name="x" /></button>
</div>
}
@if (_loaded && _notes.Count == 0)
{
<p class="kh-wempty muted">@T["Dashboard.Widgets.Notes.Empty"]</p>
}
</div>
<div class="kh-wadd">
<KhIcon Name="plus" Class="sm" />
<input class="kh-input" value="@_text" maxlength="@DashboardService.MaxNoteLength" aria-label="@T["Dashboard.Widgets.Notes.Add"]"
placeholder="@T["Dashboard.Widgets.Notes.Placeholder"]" @oninput="e => _text = e.Value as string" @onkeydown="OnKeyDownAsync" />
</div>
</ChildContent>
</KhWidget>
@code {
private List<PersonalNote> _notes = [];
private string? _text;
private bool _loaded;
/// <summary>The widget.</summary>
[Parameter, EditorRequired]
public WidgetDefinition Definition { get; set; } = default!;
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
if (Session.Actor is { } actor)
{
_notes = [.. await Dashboard.GetNotesAsync(actor)];
}
_loaded = true;
}
private async Task OnKeyDownAsync(KeyboardEventArgs e)
{
if (e.Key != "Enter" || string.IsNullOrWhiteSpace(_text))
{
return;
}
if (_notes.Count >= DashboardService.MaxNotes)
{
Toasts.Show(ToastKind.Warning, T.Format("Dashboard.Widgets.Notes.Full", DashboardService.MaxNotes));
return;
}
// Show the text just typed before clearing, or Blazor would not see the field change and keep it.
_notes.Add(new PersonalNote(_text.Trim(), false));
var typed = _text;
_text = typed;
StateHasChanged();
await Task.Yield();
_text = null;
await SaveAsync();
}
private Task ToggleAsync(int index)
{
_notes[index] = _notes[index] with { Done = !_notes[index].Done };
return SaveAsync();
}
private Task RemoveAsync(int index)
{
_notes.RemoveAt(index);
return SaveAsync();
}
private Task ClearDoneAsync()
{
_notes.RemoveAll(n => n.Done);
return SaveAsync();
}
private async Task SaveAsync()
{
if (Session.Actor is { } actor)
{
await Dashboard.SaveNotesAsync(actor, _notes);
}
}
}
@@ -0,0 +1,105 @@
@inject ShellSession Session
@inject DashboardService Dashboard
@* Scorciatoie (SPEC §10.3): buttons to the pages the user opens most, chosen among the menu entries they can see.
Until chosen, the first areas of the menu. *@
<KhWidget Id="@Definition.Id" Title="@T[Definition.TitleKey]" Icon="@Definition.Icon">
<Actions>
<button type="button" class="ib" title="@T["Dashboard.Widgets.Shortcuts.Edit"]" aria-label="@T["Dashboard.Widgets.Shortcuts.Edit"]"
@onclick="Edit"><KhIcon Name="edit" /></button>
</Actions>
<ChildContent>
@if (Shortcuts.Count == 0)
{
<p class="kh-wempty muted">@T["Dashboard.Widgets.Shortcuts.Empty"]</p>
}
else
{
<div class="kh-shortcuts">
@foreach (var item in Shortcuts)
{
<a class="kh-shortcut" href="@(item.Href == "/" ? "./" : item.Href.TrimStart('/'))">
<span class="ico-box"><KhIcon Name="@item.Icon" /></span>
<span>@T[item.Key]</span>
</a>
}
</div>
}
</ChildContent>
</KhWidget>
<KhDialog Open="_editing" Title="@T["Dashboard.Widgets.Shortcuts.Edit"]" Icon="zap" Size="sm" OnClose="() => _editing = false">
<ChildContent>
<p class="muted">@T.Format("Dashboard.Widgets.Shortcuts.Hint", DashboardService.MaxShortcuts)</p>
<div class="kh-picklist">
@foreach (var item in Choices)
{
var chosen = _draft.Contains(item.Href);
<label class="chk">
<input type="checkbox" checked="@chosen" disabled="@(!chosen && _draft.Count >= DashboardService.MaxShortcuts)"
@onchange="() => Toggle(item.Href)" />
<KhIcon Name="@item.Icon" Class="sm" /> @T[item.Key]
</label>
}
</div>
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _editing = false">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" @onclick="SaveAsync"><KhIcon Name="check" /> @T["Common.Save"]</button>
</Footer>
</KhDialog>
@code {
private IReadOnlyList<string>? _paths;
private List<string> _draft = [];
private bool _editing;
/// <summary>The widget.</summary>
[Parameter, EditorRequired]
public WidgetDefinition Definition { get; set; } = default!;
private IEnumerable<MenuItem> Choices => MenuCatalog.All.Where(i => i.Href != "/" && Session.CanSee(i));
private IReadOnlyList<MenuItem> Shortcuts =>
_paths is null
? [.. MenuCatalog.Sections.SelectMany(s => s.Items).Where(i => i.Href != "/" && Session.CanSee(i)).Take(6)]
: [.. _paths.Select(p => Choices.FirstOrDefault(i => string.Equals(i.Href, p, StringComparison.OrdinalIgnoreCase))).OfType<MenuItem>()];
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
if (Session.Actor is { } actor)
{
_paths = await Dashboard.GetShortcutsAsync(actor);
}
}
private void Edit()
{
_draft = [.. Shortcuts.Select(i => i.Href)];
_editing = true;
}
private void Toggle(string href)
{
if (!_draft.Remove(href) && _draft.Count < DashboardService.MaxShortcuts)
{
_draft.Add(href);
}
}
private async Task SaveAsync()
{
// Keep the menu order: the buttons read like the menu.
var order = Choices.Select(i => i.Href).ToList();
var chosen = _draft.OrderBy(order.IndexOf).ToList();
if (Session.Actor is { } actor)
{
await Dashboard.SaveShortcutsAsync(actor, chosen);
}
_paths = chosen;
_editing = false;
}
}
@@ -0,0 +1,86 @@
@using Khaemhat.Application.Licensing
@using Khaemhat.Core.Caching
@using Khaemhat.Core.Common
@using Khaemhat.Data
@inject SystemStatusService Status
@inject ProductVersion Version
@inject ICacheProvider Cache
@inject ILicenseGate Licenses
@inject TimeProvider Clock
@* Stato del sistema (SPEC §10.3, administrators only): version, database, cache, licence, companies and the scheduled
tasks of today, each with a dot that turns yellow or red when something needs a look. *@
<KhWidget Id="@Definition.Id" Title="@T[Definition.TitleKey]" Icon="@Definition.Icon" Tight="true">
<div class="list kh-wlist kh-status">
<div class="li">
<span class="kh-tone ok" aria-hidden="true"></span>
<span class="grow">@T["Dashboard.Widgets.System.Version"]</span>
<span class="s num" title="@Version.Full">@Version.Version@(ShortRevision.Length == 0 ? null : " (" + ShortRevision + ")")</span>
</div>
<div class="li">
<span class="kh-tone ok" aria-hidden="true"></span>
<span class="grow">@T["Dashboard.Widgets.System.Database"]</span>
<span class="s">@(_status?.Engine == DbEngine.PostgreSql ? "PostgreSQL" : "SQLite")</span>
</div>
<div class="li">
<span class="kh-tone ok" aria-hidden="true"></span>
<span class="grow">@T["Dashboard.Widgets.System.Cache"]</span>
<span class="s">@(Cache.IsDistributed ? T["Dashboard.Widgets.System.Redis"] : T["Dashboard.Widgets.System.LocalCache"])</span>
</div>
<div class="li">
<span class="kh-tone @LicenseTone" aria-hidden="true"></span>
<span class="grow">@T["Dashboard.Widgets.System.License"]</span>
<span class="s">@LicenseText</span>
</div>
@if (_status is { } status)
{
<div class="li">
<span class="kh-tone @(status.FailedCompanies > 0 ? "err" : "ok")" aria-hidden="true"></span>
<span class="grow">@T["Dashboard.Widgets.System.Companies"]</span>
<span class="s">@(status.FailedCompanies > 0
? T.Format("Dashboard.Widgets.System.CompaniesFailed", status.Companies, status.FailedCompanies)
: T.Format("Dashboard.Widgets.System.CompaniesOk", status.Companies))</span>
</div>
<div class="li">
<span class="kh-tone @(status.JobsFailed > 0 ? "err" : "ok")" aria-hidden="true"></span>
<span class="grow">@T["Dashboard.Widgets.System.Jobs"]</span>
<span class="s">@T.Format("Dashboard.Widgets.System.JobsSummary", status.JobsSucceeded, status.JobsFailed)</span>
</div>
}
</div>
</KhWidget>
@code {
private SystemStatus? _status;
/// <summary>The widget.</summary>
[Parameter, EditorRequired]
public WidgetDefinition Definition { get; set; } = default!;
private string ShortRevision => Version.Revision.Length > 7 ? Version.Revision[..7] : Version.Revision;
private LicenseState License => Licenses.Current;
private int? DaysLeft => License.DaysLeft(Clock.GetUtcNow().UtcDateTime);
private string LicenseTone => License.Status switch
{
LicenseStatus.Expired => "err",
LicenseStatus.Grace => "err",
_ when DaysLeft <= LicenseFeedSource.RenewDays => "warn",
_ => "ok",
};
private string LicenseText => License switch
{
{ IsTestMode: true } => T["Dashboard.Widgets.System.LicenseTest"],
{ Status: LicenseStatus.Expired } => T["Dashboard.Widgets.System.LicenseExpired"],
{ Status: LicenseStatus.Grace } => T["Dashboard.Widgets.System.LicenseGrace"],
{ Kind: LicenseKind.Trial } => T.Format("Dashboard.Widgets.System.LicenseTrial", DaysLeft ?? 0),
_ when DaysLeft is { } days => T.Format("Dashboard.Widgets.System.LicenseDays", days),
_ => T["Dashboard.Widgets.System.LicenseUnlimited"],
};
/// <inheritdoc />
protected override async Task OnInitializedAsync() => _status = await Status.GetAsync();
}
+312 -46
View File
@@ -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. *@
<KhPageTitle Text="@T["Pages.Home.Title"]" Icon="home" />
<div class="phead">
<div>
<h1>@Greeting</h1>
<div class="sub">@T.Format("Pages.Home.Today", Today)</div>
</div>
</div>
<div class="cols cols-3 kh-home-tiles">
<div class="tile acc">
<div class="t"><KhIcon Name="key" Class="sm" /> @T["Pages.Home.LicenseTile"]</div>
<div class="v">@(License.Kind == LicenseKind.Trial ? T["Pages.Home.LicenseTrial"] : T["Pages.Home.LicenseFull"])</div>
<div class="d">@LicenseDetail</div>
</div>
<div class="tile">
<div class="t"><KhIcon Name="layers" Class="sm" /> @T["Pages.Home.ModulesTile"]</div>
<div class="v">@T.Format("Pages.Home.ModulesText", License.Modules.Count, ModuleRegistry.Default.Modules.Count)</div>
<div class="d">@(License.Modules.Count == 0 ? T["Pages.Home.ModulesNone"] : string.Join(" · ", License.Modules.Order(StringComparer.Ordinal)))</div>
</div>
<div class="tile">
<div class="t"><KhIcon Name="building" Class="sm" /> @T["Pages.Home.CompanyTile"]</div>
<div class="v">@(Session.Company?.Name ?? T["Pages.Home.CompanyNone"])</div>
<div class="d">@Session.Company?.Code</div>
</div>
</div>
<section class="panel" aria-labelledby="kh-home-areas">
<div class="ph"><KhIcon Name="grid" /> <span id="kh-home-areas">@T["Pages.Home.AreasTitle"]</span></div>
<div class="pb">
<p class="muted">@T["Pages.Home.AreasHint"]</p>
<div class="kh-areas">
@foreach (var area in Areas)
{
<a class="kh-area" href="@area.Href.TrimStart('/')">
<span class="ico-box"><KhIcon Name="@area.Icon" /></span>
<span class="grow">@T[area.Key]</span>
@if (area.Milestone is { } milestone)
{
<span class="badge gray">@T.Format("Pages.Home.Coming", milestone)</span>
}
</a>
}
<div class="kh-home @(_customizing ? "kh-with-drawer" : null)">
<div class="phead">
<div>
<h1>@Greeting</h1>
<div class="sub">@T.Format("Pages.Home.Today", Today)</div>
</div>
<div class="grow"></div>
@if (_loaded && ShowDashboard)
{
<div class="actions">
<button type="button" class="btn @(_customizing ? "primary" : null)" aria-pressed="@(_customizing ? "true" : "false")"
@onclick="ToggleCustomize"><KhIcon Name="layout" /> @T["Dashboard.Customize"]</button>
</div>
}
</div>
</section>
<div class="callout info"><KhIcon Name="info" /> <span>@T["Pages.Home.DashboardSoon"]</span></div>
@if (!_loaded)
{
<p class="muted">@T["Dashboard.Feed.Loading"]</p>
}
else if (ShowDashboard)
{
@if (_layout.Widgets.Count == 0)
{
<div class="callout info"><KhIcon Name="info" /> <span>@T["Dashboard.Empty"]</span></div>
}
else
{
<KhWidgetGrid Layout="_layout" Editing="_customizing" LayoutChanged="ChangeLayoutAsync" Label="@T["Dashboard.Grid"]">
@foreach (var placement in _layout.Widgets)
{
if (WidgetCatalog.Find(placement.Id) is { } definition)
{
<DashboardWidget @key="placement.Id" Definition="definition" />
}
}
</KhWidgetGrid>
}
}
else
{
<div class="callout info kh-home-off">
<KhIcon Name="info" />
<span class="grow">@T["Dashboard.Off"]</span>
<button type="button" class="btn sm" @onclick="() => ChangeShowAsync(true)">@T["Dashboard.ShowAgain"]</button>
</div>
<div class="cols cols-3 kh-home-tiles">
<div class="tile acc">
<div class="t"><KhIcon Name="key" Class="sm" /> @T["Pages.Home.LicenseTile"]</div>
<div class="v">@(License.Kind == LicenseKind.Trial ? T["Pages.Home.LicenseTrial"] : T["Pages.Home.LicenseFull"])</div>
<div class="d">@LicenseDetail</div>
</div>
<div class="tile">
<div class="t"><KhIcon Name="layers" Class="sm" /> @T["Pages.Home.ModulesTile"]</div>
<div class="v">@T.Format("Pages.Home.ModulesText", License.Modules.Count, ModuleRegistry.Default.Modules.Count)</div>
<div class="d">@(License.Modules.Count == 0 ? T["Pages.Home.ModulesNone"] : string.Join(" · ", License.Modules.Order(StringComparer.Ordinal)))</div>
</div>
<div class="tile">
<div class="t"><KhIcon Name="building" Class="sm" /> @T["Pages.Home.CompanyTile"]</div>
<div class="v">@(Session.Company?.Name ?? T["Pages.Home.CompanyNone"])</div>
<div class="d">@Session.Company?.Code</div>
</div>
</div>
<section class="panel" aria-labelledby="kh-home-areas">
<div class="ph"><KhIcon Name="grid" /> <span id="kh-home-areas">@T["Pages.Home.AreasTitle"]</span></div>
<div class="pb">
<p class="muted">@T["Pages.Home.AreasHint"]</p>
<div class="kh-areas">
@foreach (var area in Areas)
{
<a class="kh-area" href="@area.Href.TrimStart('/')">
<span class="ico-box"><KhIcon Name="@area.Icon" /></span>
<span class="grow">@T[area.Key]</span>
@if (area.Milestone is { } milestone)
{
<span class="badge gray">@T.Format("Pages.Home.Coming", milestone)</span>
}
</a>
}
</div>
</div>
</section>
}
</div>
<KhDrawer Open="_customizing" Title="@T["Dashboard.CustomizeTitle"]" Icon="layout" OnClose="CloseCustomize">
<ChildContent>
<section class="kh-dsec" aria-labelledby="kh-dash-start-h">
<h3 class="fgh" id="kh-dash-start-h"><KhIcon Name="home" /> @T["Dashboard.Panel.Start"]</h3>
<div class="f">
<label for="kh-dash-start">@T["Dashboard.Panel.StartPage"]</label>
<select id="kh-dash-start" class="kh-input" value="@StartValue" @onchange="ChangeStartAsync">
<option value="@nameof(StartPage.Dashboard)">@T["Pages.Profile.Start.Dashboard"]</option>
<option value="@nameof(StartPage.LastTab)">@T["Pages.Profile.Start.LastTab"]</option>
@foreach (var item in StartChoices)
{
<option value="@item.Href">@T[item.Key]</option>
}
</select>
</div>
<KhSwitchRow Label="@T["Dashboard.Panel.Show"]" Value="Session.Preferences.ShowDashboard" ValueChanged="ChangeShowAsync" />
</section>
<section class="kh-dsec" aria-labelledby="kh-dash-widgets-h">
<h3 class="fgh" id="kh-dash-widgets-h"><KhIcon Name="grid" /> @T["Dashboard.Panel.Widgets"]</h3>
<p class="muted s">@T["Dashboard.Panel.WidgetsHint"] @SourceText</p>
<div class="kh-wpick">
@foreach (var definition in _available)
{
var on = _layout.Contains(definition.Id);
var title = T[definition.TitleKey];
<div class="kh-wpick-row @(on ? null : "off")" @key="definition.Id">
<KhSwitchRow Label="@title" Hint="@HintOf(definition)" Value="on" ValueChanged="v => ToggleAsync(definition.Id, v)" />
@if (on)
{
<div class="kh-wpick-tools">
<select class="kh-input" aria-label="@T.Format("Dashboard.Panel.Width", title)" value="@_layout.WidthOf(definition.Id)"
@onchange="e => ResizeAsync(definition.Id, e.Value as string)">
@foreach (var width in WidgetDefinition.Widths)
{
<option value="@width">@T["Dashboard.Widths." + width]</option>
}
</select>
<button type="button" class="ib" title="@T.Format("Dashboard.Panel.MoveUp", title)" aria-label="@T.Format("Dashboard.Panel.MoveUp", title)"
disabled="@(_layout.Widgets[0].Id == definition.Id)" @onclick="() => MoveAsync(definition.Id, -1)"><KhIcon Name="chevron-up" /></button>
<button type="button" class="ib" title="@T.Format("Dashboard.Panel.MoveDown", title)" aria-label="@T.Format("Dashboard.Panel.MoveDown", title)"
disabled="@(_layout.Widgets[^1].Id == definition.Id)" @onclick="() => MoveAsync(definition.Id, 1)"><KhIcon Name="chevron-down" /></button>
</div>
}
</div>
}
</div>
</section>
@if (CanSetRoleDefaults)
{
<section class="kh-dsec" aria-labelledby="kh-dash-role-h">
<h3 class="fgh" id="kh-dash-role-h"><KhIcon Name="users" /> @T["Dashboard.Panel.Role"]</h3>
<p class="muted s">@T["Dashboard.Panel.RoleHint"]</p>
@if (_roles.Count == 0)
{
<p class="muted s">@T["Dashboard.Panel.RoleNone"]</p>
}
else
{
<div class="f">
<label for="kh-dash-role">@T["Dashboard.Panel.RolePick"]</label>
<select id="kh-dash-role" class="kh-input" value="@_role" @onchange="e => _role = e.Value as string">
@foreach (var (role, layout) in _roles)
{
<option value="@role.Code">@(layout is null ? role.Name : T.Format("Dashboard.Panel.RoleHas", role.Name))</option>
}
</select>
</div>
<div class="kh-row">
<button type="button" class="btn" @onclick="SaveRoleAsync"><KhIcon Name="users" /> @T["Dashboard.Panel.RoleSave"]</button>
@if (SelectedRole is { Layout: not null })
{
<button type="button" class="btn ghost" @onclick="RemoveRoleAsync"><KhIcon Name="x" /> @T["Dashboard.Panel.RoleRemove"]</button>
}
</div>
}
</section>
}
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="ResetAsync"><KhIcon Name="refresh" /> @T["Dashboard.Panel.Reset"]</button>
<button type="button" class="btn primary" @onclick="CloseCustomize"><KhIcon Name="check" /> @T["Dashboard.Panel.Done"]</button>
</Footer>
</KhDrawer>
@code {
private DashboardLayout _layout = WidgetCatalog.BuiltIn;
private DashboardView? _view;
private IReadOnlyList<WidgetDefinition> _available = [];
private IReadOnlyList<(Role Role, DashboardLayout? Layout)> _roles = [];
private string? _role;
private bool _loaded;
private bool _customizing;
private LicenseState License => Session.Licenses.Current;
private bool ShowDashboard => Session.Preferences.ShowDashboard;
private bool CanSetRoleDefaults => Session.Company is not null && Session.Permissions.Allows(CompanySettingsService.WritePermission);
private (Role Role, DashboardLayout? Layout)? SelectedRole =>
_roles.Where(r => r.Role.Code == _role).Select(r => ((Role, DashboardLayout?)?)r).FirstOrDefault();
private IEnumerable<MenuItem> Areas =>
MenuCatalog.Sections.SelectMany(s => s.Items).Where(i => i.Href != "/" && Session.CanSee(i));
private IEnumerable<MenuItem> StartChoices => MenuCatalog.All.Where(i => i.Href != "/" && i.Milestone is null && Session.CanSee(i));
private string StartValue => Session.Preferences.StartPage switch
{
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 @@
}
/// <inheritdoc />
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));
}
}
@@ -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. *@
<section class="widget w@(Width) @(Editing ? "editing" : null) @(_over ? "kh-over" : null)" role="listitem" aria-labelledby="@(_id + "-t")"
data-widget="@Id" data-kh-drag="@(Editing ? "true" : null)" draggable="@(Editing ? "true" : null)"
@ondragstart="StartDrag" @ondragend="EndDrag" @ondragenter="() => SetOver(true)" @ondragleave="() => SetOver(false)"
@ondragover:preventDefault="Editing" @ondrop="DropAsync">
<div class="wh">
@if (Editing)
{
<span class="drag" title="@T["Dashboard.Edit.Drag"]" aria-hidden="true"><KhIcon Name="grip" /></span>
}
else if (Icon is not null)
{
<KhIcon Name="@Icon" />
}
<span class="grow" id="@(_id + "-t")">@Title</span>
<div class="wa">
@if (Editing && Grid is not null)
{
<button type="button" class="ib" title="@T["Dashboard.Edit.Before"]" aria-label="@T["Dashboard.Edit.Before"]"
disabled="@Grid.IsAtEnd(Id, last: false)" @onclick="() => Grid.MoveAsync(Id, -1)"><KhIcon Name="chevron-left" /></button>
<button type="button" class="ib" title="@T["Dashboard.Edit.After"]" aria-label="@T["Dashboard.Edit.After"]"
disabled="@Grid.IsAtEnd(Id, last: true)" @onclick="() => Grid.MoveAsync(Id, 1)"><KhIcon Name="chevron-right" /></button>
<button type="button" class="ib" title="@T["Dashboard.Edit.Narrower"]" aria-label="@T["Dashboard.Edit.Narrower"]"
disabled="@(Width <= 3)" @onclick="() => Grid.ResizeAsync(Id, -1)"><KhIcon Name="minus" /></button>
<button type="button" class="ib" title="@T["Dashboard.Edit.Wider"]" aria-label="@T["Dashboard.Edit.Wider"]"
disabled="@(Width >= 12)" @onclick="() => Grid.ResizeAsync(Id, 1)"><KhIcon Name="plus" /></button>
<button type="button" class="ib" title="@T["Dashboard.Edit.Hide"]" aria-label="@T["Dashboard.Edit.Hide"]"
@onclick="() => Grid.HideAsync(Id)"><KhIcon Name="x" /></button>
}
else
{
@Actions
}
</div>
</div>
<div class="wb @(Tight ? "tight" : null)">
@ChildContent
</div>
</section>
@code {
private static int _next;
private readonly string _id = "kh-wdg" + Interlocked.Increment(ref _next).ToString(System.Globalization.CultureInfo.InvariantCulture);
private bool _over;
/// <summary>The grid around, which knows the width and handles the changes.</summary>
[CascadingParameter]
public KhWidgetGrid? Grid { get; set; }
/// <summary>The widget id, as in the layout.</summary>
[Parameter, EditorRequired]
public string Id { get; set; } = string.Empty;
/// <summary>The title.</summary>
[Parameter]
public string? Title { get; set; }
/// <summary>The icon before the title.</summary>
[Parameter]
public string? Icon { get; set; }
/// <summary>Buttons at the right of the title (hidden while customizing).</summary>
[Parameter]
public RenderFragment? Actions { get; set; }
/// <summary>The content.</summary>
[Parameter]
public RenderFragment? ChildContent { get; set; }
/// <summary>Content without padding (lists that run to the edges).</summary>
[Parameter]
public bool Tight { get; set; }
/// <summary>The width when there is no grid around.</summary>
[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);
}
}
}
@@ -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. *@
<CascadingValue Value="this" IsFixed="true">
<div class="wgrid kh-wgrid @(Editing ? "kh-editing" : null)" role="list" aria-label="@Label">
@ChildContent
</div>
</CascadingValue>
@code {
private string? _dragging;
/// <summary>The widgets in order, with their width.</summary>
[Parameter, EditorRequired]
public DashboardLayout Layout { get; set; } = WidgetCatalog.BuiltIn;
/// <summary>Whether the widgets can be moved, resized and hidden.</summary>
[Parameter]
public bool Editing { get; set; }
/// <summary>Called with the new layout after a move, resize or hide.</summary>
[Parameter]
public EventCallback<DashboardLayout> LayoutChanged { get; set; }
/// <summary>The name of the grid for screen readers.</summary>
[Parameter]
public string? Label { get; set; }
/// <summary>The KhWidget components, one per widget of the layout.</summary>
[Parameter]
public RenderFragment? ChildContent { get; set; }
/// <summary>The width of a widget, in columns of twelve.</summary>
/// <param name="id">The widget id.</param>
/// <returns>The width.</returns>
public int WidthOf(string id) => Layout.WidthOf(id);
/// <summary>Whether a widget is the first or the last.</summary>
/// <param name="id">The widget id.</param>
/// <param name="last">Ask about the last one.</param>
/// <returns><see langword="true"/> at that end.</returns>
public bool IsAtEnd(string id, bool last) =>
Layout.Widgets.Count > 0 && (last ? Layout.Widgets[^1].Id : Layout.Widgets[0].Id) == id;
/// <summary>Moves a widget by one place.</summary>
/// <param name="id">The widget id.</param>
/// <param name="offset">-1 before, +1 after.</param>
/// <returns>A task.</returns>
public Task MoveAsync(string id, int offset) => ChangeAsync(Layout.Move(id, offset));
/// <summary>Makes a widget narrower or wider by one step.</summary>
/// <param name="id">The widget id.</param>
/// <param name="step">-1 narrower, +1 wider.</param>
/// <returns>A task.</returns>
public Task ResizeAsync(string id, int step) => ChangeAsync(Layout.Resize(id, WidgetDefinition.Step(WidthOf(id), step)));
/// <summary>Hides a widget.</summary>
/// <param name="id">The widget id.</param>
/// <returns>A task.</returns>
public Task HideAsync(string id) => ChangeAsync(Layout.Toggle(id, false));
/// <summary>A widget starts being dragged.</summary>
/// <param name="id">The widget id.</param>
public void StartDrag(string id) => _dragging = id;
/// <summary>The dragged widget is dropped on another one: it takes that one's place.</summary>
/// <param name="target">The widget dropped on.</param>
/// <returns>A task.</returns>
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));
}
/// <summary>The drag ended without a drop.</summary>
public void EndDrag() => _dragging = null;
private async Task ChangeAsync(DashboardLayout next)
{
if (!next.SameAs(Layout))
{
await LayoutChanged.InvokeAsync(next);
}
}
}
@@ -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
@@ -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<ITexts>(JsonTextProvider.FromAssembly(typeof(KhaemhatServices).Assembly, ItalianCulture));
services.AddSingleton<UserSettingsService>();
services.AddSingleton<CompanySettingsService>();
// Dashboard (SPEC §10.3): the sources of the lists join from the modules that feed them.
services.AddSingleton<DashboardService>();
services.AddSingleton<LicenseFeedSource>();
services.AddSingleton<ITodoSource>(sp => sp.GetRequiredService<LicenseFeedSource>());
services.AddSingleton<IDeadlineSource>(sp => sp.GetRequiredService<LicenseFeedSource>());
services.AddSingleton<ITodoSource, NotificationTodoSource>();
services.AddSingleton<JobRunFeedSource>();
services.AddSingleton<ITodoSource>(sp => sp.GetRequiredService<JobRunFeedSource>());
services.AddSingleton<IDoneSource>(sp => sp.GetRequiredService<JobRunFeedSource>());
services.AddSingleton<SystemStatusService>();
services.AddSingleton<TodoAggregator>();
services.AddSingleton<DoneAggregator>();
services.AddSingleton<DeadlineAggregator>();
services.AddScoped<ShellSession>();
services.AddScoped<ThemeService>();
services.AddScoped<TabService>();
@@ -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"
}
}
}
}
+1 -4
View File
@@ -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",
+14
View File
@@ -0,0 +1,14 @@
namespace Khaemhat.Web.Ui;
/// <summary>Which list a feed widget of the dashboard shows.</summary>
public enum FeedKind
{
/// <summary>Da fare oggi.</summary>
Todo = 0,
/// <summary>Fatto oggi.</summary>
Done = 1,
/// <summary>Scadenze 30 giorni.</summary>
Deadlines = 2,
}
+52
View File
@@ -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; } }
+8
View File
@@ -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();
@@ -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;
/// <summary>The widget dashboard (SPEC §10.3, issue #30): the saved layout and the lists the widgets read.</summary>
[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<TodoAggregator>.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<DeadlineAggregator>.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<DoneAggregator>.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<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, CancellationToken cancellationToken) =>
Task.FromResult<IReadOnlyList<FeedItem>>(items);
public Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, DateOnly until, CancellationToken cancellationToken) =>
Task.FromResult<IReadOnlyList<FeedItem>>(items);
}
private sealed class FailingSource : ITodoSource
{
public Task<IReadOnlyList<FeedItem>> 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;
}
}
+1 -1
View File
@@ -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());
}
@@ -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;
/// <summary>The dashboard of each user, the default of a role and the company settings behind it (issues #30 and #31).</summary>
[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<DashboardService>();
var users = app.Services.GetRequiredService<UserService>();
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<DashboardService>().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<AccessDeniedException>(() => 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<DashboardService>();
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<CompanySettingsService>();
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<string, string?> { ["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<AccessDeniedException>(() => settings.SetAsync(stranger, company, "test.gamma", "tre"));
await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => settings.SetAsync(root, company, " ", "x"));
await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => settings.SetAsync(root, company, "test.big", new string('x', CompanySettingsService.MaxValueLength + 1)));
await app.StopAsync();
}
}
}
@@ -62,7 +62,9 @@ public sealed partial class LocalizationRulesTests
public void EveryTextKeyInTheCode_Exists()
{
var missing = new List<string>();
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();
}