From f415dc37a82b002aa8980c330bb0b7ed45ec186b Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 11 Nov 2026 19:39:17 +0100 Subject: [PATCH] feat: in-app help, notifications panel and global search (#32) F1 and "?" now open the wiki page of the screen inside the application (/aiuto, mockup 011) from a copy of the wiki shipped next to the program, so help works offline and always matches the installed version. Markdown is converted in-house and fully encoded; images of the repository are served from the copy. KHAEMHAT_HELP_URL sets the online wiki behind "Apri nel wiki"; "Segnala un problema" opens a new issue of that repo. A test checks that every page and menu entry has an existing wiki page. The bell opens a notifications panel (mockup 010) with all/unread filters and mark read. Broadcast notifications are now read per user through sys_notification_reads / notification_reads instead of one shared read_at. The global search asks ISearchProvider implementations through GlobalSearchService after a short pause; the first provider finds help pages and sections, # and @ say which modules will fill them. Escape also closes a side panel when the focus fell out of it. Decisions in ADR 0023. Co-Authored-By: Claude Opus 5.5 --- .dockerignore | 4 + CHANGELOG.md | 9 + deploy/unraid/khaemhat.xml | 1 + docs/DATA-MODEL.md | 34 ++ docs/adr/0023-aiuto-in-app-e-notifiche.md | 55 +++ docs/wiki/Installazione-Docker.md | 1 + docs/wiki/Interfaccia-e-scorciatoie.md | 29 +- .../EnvironmentConfigurationReader.cs | 1 + .../Configuration/KhaemhatOptions.cs | 11 + .../Dashboard/SystemFeedSources.cs | 7 +- .../Notifications/NotificationDispatcher.cs | 135 ++++- .../Search/GlobalSearchService.cs | 133 +++++ src/Khaemhat.Core/Instance/InstanceRecords.cs | 20 + .../CompanyDatabase/CompanyMaps.cs | 7 + .../M20261111_009_CreateNotificationReads.cs | 24 + ...20261111_013_CreateSysNotificationReads.cs | 24 + .../SystemDatabase/SecurityMaps.cs | 7 + .../Components/Layout/MainLayout.razor | 12 +- .../Components/Pages/ComingSoon.razor | 2 +- src/Khaemhat.Web/Components/Pages/Help.razor | 73 +++ .../Components/Shell/KhCommandPalette.razor | 96 +++- .../Components/Shell/NotificationPanel.razor | 167 +++++++ .../Components/Shell/TopBar.razor | 89 ++-- src/Khaemhat.Web/Help/HelpSearchProvider.cs | 27 + src/Khaemhat.Web/Help/WikiLibrary.cs | 172 +++++++ src/Khaemhat.Web/Help/WikiMarkdown.cs | 465 ++++++++++++++++++ src/Khaemhat.Web/Hosting/KhaemhatApp.cs | 23 + src/Khaemhat.Web/Hosting/KhaemhatServices.cs | 5 + src/Khaemhat.Web/Khaemhat.Web.csproj | 10 + src/Khaemhat.Web/Resources/it-IT/Pages.json | 11 + src/Khaemhat.Web/Resources/it-IT/Shell.json | 30 +- src/Khaemhat.Web/Shell/HelpLinks.cs | 20 + src/Khaemhat.Web/wwwroot/app.css | 50 ++ src/Khaemhat.Web/wwwroot/js/khaemhat.js | 10 +- .../GlobalSearchTests.cs | 69 +++ .../SystemRulesTests.cs | 14 + tests/Khaemhat.Data.Tests/MappingTests.cs | 4 +- tests/Khaemhat.Web.Tests/Shell/HelpTests.cs | 162 ++++++ .../Shell/NotificationInboxTests.cs | 70 +++ 39 files changed, 1976 insertions(+), 107 deletions(-) create mode 100644 docs/adr/0023-aiuto-in-app-e-notifiche.md create mode 100644 src/Khaemhat.Application/Search/GlobalSearchService.cs create mode 100644 src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_009_CreateNotificationReads.cs create mode 100644 src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_013_CreateSysNotificationReads.cs create mode 100644 src/Khaemhat.Web/Components/Pages/Help.razor create mode 100644 src/Khaemhat.Web/Components/Shell/NotificationPanel.razor create mode 100644 src/Khaemhat.Web/Help/HelpSearchProvider.cs create mode 100644 src/Khaemhat.Web/Help/WikiLibrary.cs create mode 100644 src/Khaemhat.Web/Help/WikiMarkdown.cs create mode 100644 tests/Khaemhat.Application.Tests/GlobalSearchTests.cs create mode 100644 tests/Khaemhat.Web.Tests/Shell/HelpTests.cs create mode 100644 tests/Khaemhat.Web.Tests/Shell/NotificationInboxTests.cs diff --git a/.dockerignore b/.dockerignore index 77d3f55..afc0e07 100644 --- a/.dockerignore +++ b/.dockerignore @@ -10,6 +10,10 @@ .data/ out/ docs/ +# ...except the copy of the wiki and the images it shows, shipped as the in-app help (ADR 0023). +!docs/wiki/ +!docs/mockups/thumbs/ +!docs/mockups/png/ deploy/ *.md !README.md diff --git a/CHANGELOG.md b/CHANGELOG.md index d8dd3b4..7b87950 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +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. +- Aiuto in app (mockup 011): `F1` e `?` aprono in una scheda la pagina wiki della maschera dalla copia della wiki + contenuta nell'immagine (`/aiuto`, funziona senza Internet), con indice, *Apri nel wiki* e *Segnala un problema*; + Markdown convertito in casa; nuova variabile facoltativa `KHAEMHAT_HELP_URL` per la wiki online (ADR 0023). +- Pannello notifiche (mockup 010): filtri *Tutte* e *Non lette*, segna come letta, *Segna tutte come lette*, + conteggio aggiornato ogni minuto; le notifiche per tutti si segnano lette per ciascun utente (tabelle + `sys_notification_reads` e `notification_reads`). +- Ricerca globale a fornitori (`GlobalSearchService`, `ISearchProvider`): oltre a pagine e comandi trova le pagine e + le sezioni dell'aiuto; prefissi `#` documenti e `@` persone pronti per i moduli successivi. - 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, @@ -38,6 +46,7 @@ M3 — Framework UI, prima parte: la shell dell'applicazione, i testi localizzat in chiaro. ### Changed +- `Esc` chiude anche un pannello laterale aperto quando il focus non è in un campo. - Pagine di accesso, errori e riconnessione con i testi localizzati e i colori del tema. ## [0.2.0] - 2026-11-11 diff --git a/deploy/unraid/khaemhat.xml b/deploy/unraid/khaemhat.xml index e887789..4abd6a7 100644 --- a/deploy/unraid/khaemhat.xml +++ b/deploy/unraid/khaemhat.xml @@ -32,6 +32,7 @@ production false + Europe/Rome 99 diff --git a/docs/DATA-MODEL.md b/docs/DATA-MODEL.md index d88e4c2..eaf4f5d 100644 --- a/docs/DATA-MODEL.md +++ b/docs/DATA-MODEL.md @@ -386,6 +386,7 @@ Migrazioni applicate in ordine: - `core` 20261111010 `create_sys_scheduler` (M20261111_010_CreateSysScheduler) - `core` 20261111011 `create_sys_notifications` (M20261111_011_CreateSysNotifications) - `core` 20261111012 `create_sys_user_settings` (M20261111_012_CreateSysUserSettings) +- `core` 20261111013 `create_sys_notification_reads` (M20261111_013_CreateSysNotificationReads) #### `schema_version` @@ -518,6 +519,22 @@ Chiave primaria: `module`, `version`. - indice `ix_sys_log_section_at` su `section`, `at` - indice `ix_sys_log_trace_id` su `trace_id` +#### `sys_notification_reads` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `notification_id` | Int64 | no | | | +| `user_id` | Int64 | no | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_sys_notification_reads_user_id` su `user_id` +- indice unico `ux_sys_notification_reads_notification_user` su `notification_id`, `user_id` + #### `sys_notifications` | Colonna | Tipo | Null | Default | Note | @@ -703,6 +720,7 @@ Migrazioni applicate in ordine: - `core` 20261111006 `create_user_settings` (M20261111_006_CreateUserSettings) - `core` 20261111007 `create_attachments` (M20261111_007_CreateAttachments) - `core` 20261111008 `create_company_settings` (M20261111_008_CreateCompanySettings) +- `core` 20261111009 `create_notification_reads` (M20261111_009_CreateNotificationReads) #### `attachments` @@ -764,6 +782,22 @@ Migrazioni applicate in ordine: - indice unico `ux_company_settings_key` su `key` +#### `notification_reads` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `notification_id` | Int64 | no | | | +| `user_id` | Int64 | no | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_notification_reads_user_id` su `user_id` +- indice unico `ux_notification_reads_notification_user` su `notification_id`, `user_id` + #### `notifications` | Colonna | Tipo | Null | Default | Note | diff --git a/docs/adr/0023-aiuto-in-app-e-notifiche.md b/docs/adr/0023-aiuto-in-app-e-notifiche.md new file mode 100644 index 0000000..834773b --- /dev/null +++ b/docs/adr/0023-aiuto-in-app-e-notifiche.md @@ -0,0 +1,55 @@ +# ADR 0023 - Aiuto in app dalla copia della wiki, notifiche lette per utente, ricerca a fornitori + +- **Stato:** accettata +- **Data:** 2026-11-11 +- **Modifica:** SPEC §10.2, §17; milestone M3, issue #32 (mockup 009, 010, 011) + +## Contesto + +La specifica chiede che `F1` apra la pagina wiki della maschera dentro l'applicazione (mockup 011), con indice, +*Apri nel wiki* e *Segnala un problema*, e che l'aiuto funzioni anche nelle installazioni senza Internet servendo +una copia della wiki "all'indirizzo `/help`". Non dice come la copia arriva nell'immagine, come si converte il +Markdown senza librerie esterne (SPEC §1.2), né come una notifica "per tutti" diventa letta per un utente e non per +gli altri. Per la ricerca globale (mockup 009) dice cosa trovare, ma i dati (clienti, articoli, documenti) arrivano +con le milestone successive. + +## Decisione + +1. **La wiki viaggia con il programma.** La compilazione copia `docs/wiki/*.md` in `help/wiki/` accanto al + programma, e in `help/media/` le immagini che le pagine mostrano (miniature e PNG dei mockup, icone, `img/` della + wiki), con lo stesso percorso che hanno nel repository. `.dockerignore` lascia entrare solo quelle cartelle di + `docs/`. Nessun download all'avvio, nessuna scrittura: la copia è di sola lettura e corrisponde alla versione. +2. **Markdown in casa.** `WikiMarkdown` converte il sottoinsieme che la wiki usa: titoli con ancora, paragrafi, + elenchi annidati, tabelle, citazioni, blocchi di codice, linee, immagini, collegamenti, grassetto, corsivo, + codice. Tutto il testo è codificato (niente HTML grezzo); diventano collegamenti solo indirizzi `http(s)`, + ancore `#` e nomi di pagina. La citazione `> **Stato:** …` in testa a ogni pagina è lo stato della pagina e si + mostra come tale, riga per riga; le altre citazioni sono riquadri informativi. +3. **Indirizzi.** L'aiuto è la pagina Blazor `/aiuto/{Pagina}` (nelle schede come ogni altra maschera); le immagini + sono servite da `/aiuto/media/{percorso}` solo se il percorso è fra quelli copiati e ha un'estensione d'immagine. + L'indirizzo `/help` della specifica resta come rinvio a `/aiuto`. Le immagini che puntano ai file del repository + (`…/raw/branch/main/`) si servono dalla copia locale; le altre restano sul web. +4. **Una pagina per ogni maschera.** `HelpLinks` associa a ogni prefisso di percorso una pagina wiki; un test + controlla che ogni pagina dell'applicazione e ogni voce di menu porti a una pagina che esiste, e che tutti i + collegamenti fra pagine della wiki trovino la loro pagina. +5. **Wiki online configurabile.** `KHAEMHAT_HELP_URL` (facoltativa, indirizzo assoluto `http(s)`) è la wiki aperta da + *Apri nel wiki*; predefinita la wiki del progetto. *Segnala un problema* apre `…/issues/new` del repository della + wiki quando l'indirizzo finisce con `/wiki/` (Gitea e GitHub), altrimenti non compare. +6. **Notifiche lette per utente.** Una notifica personale (con destinatario) usa la sua colonna `read_at`. Una + notifica per tutti resta una riga sola; chi la legge aggiunge una riga in `sys_notification_reads` (notifiche di + sistema) o `notification_reads` (notifiche dell'azienda), con vincolo unico su notifica e utente. Il pannello + mostra le ultime 100 notifiche dell'utente, filtri *Tutte* e *Non lette*, *Segna tutte come lette*; la campanella + aggiorna il conteggio ogni minuto. +7. **Ricerca a fornitori.** Pagine del menu e comandi si cercano subito nel browser. I record arrivano da + `ISearchProvider` registrati nel contenitore e interrogati in parallelo da `GlobalSearchService` dopo una pausa di + 200 ms e almeno 2 caratteri: ognuno dichiara gli ambiti (tutto, `#` documenti, `@` persone), dà al massimo 8 + risultati, e uno lento (oltre 3 secondi) o in errore si scrive nel log e si salta. In M3 c'è il fornitore delle + pagine dell'aiuto (titoli e sezioni); `#` e `@` dicono con quali moduli arriveranno i risultati. + +## Conseguenze + +- L'aiuto funziona senza Internet ed è sempre quello della versione installata; l'immagine cresce delle sole pagine + e immagini citate (qualche MB). +- Il convertitore copre solo la sintassi usata dalla wiki: una pagina nuova con sintassi diversa si vede come testo, + e il test di conversione di tutte le pagine la segnala. +- I moduli successivi aggiungono i propri fornitori di ricerca e le proprie sorgenti di notifiche senza toccare la + shell. diff --git a/docs/wiki/Installazione-Docker.md b/docs/wiki/Installazione-Docker.md index be683b0..838e65d 100644 --- a/docs/wiki/Installazione-Docker.md +++ b/docs/wiki/Installazione-Docker.md @@ -189,6 +189,7 @@ obbligatoria, termina con un messaggio che indica quale. | `KHAEMHAT_SEED_DEMO` | no | `false` | dati di esempio, solo su database vuoto | | `KHAEMHAT_UPDATE_FEED` | no | `https://gitea.encke-hake.ts.net/api/v1/packages/BalboSoft?type=container&q=khaemhat` | API dei pacchetti Gitea per il controllo aggiornamenti | | `KHAEMHAT_UPDATE_TOKEN` | no | token Gitea in sola lettura | solo se il pacchetto non è pubblico | +| `KHAEMHAT_HELP_URL` | no | `https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/` | wiki online aperta da **Apri nel wiki** nell'aiuto; l'aiuto (F1) usa la copia della wiki contenuta nell'immagine e funziona anche senza Internet | | `TZ` | no | `Europe/Rome` | fuso orario | | `PUID` / `PGID` | no | `1654` / `1654` (Unraid: `99` / `100`) | utente e gruppo proprietari dei file in `/data`; l'applicazione non gira mai come root | diff --git a/docs/wiki/Interfaccia-e-scorciatoie.md b/docs/wiki/Interfaccia-e-scorciatoie.md index 3208010..f0b98f5 100644 --- a/docs/wiki/Interfaccia-e-scorciatoie.md +++ b/docs/wiki/Interfaccia-e-scorciatoie.md @@ -98,9 +98,9 @@ e la **versione** del software con il commit (es. `v1.0.0 (a3f9c1e)`). ![009 · Ricerca globale](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/009-ricerca-globale.png) *Mockup 009 — ricerca "rossi": risultati raggruppati per clienti, articoli, documenti, contabilità e azioni (anteprima ridotta).* -> **In questa versione** la ricerca trova le **pagine** del menu e i **comandi** (tema, menu, profilo, sessioni, -> scorciatoie); clienti, articoli e documenti si aggiungono con le milestone che li introducono. Il prefisso `>` -> mostra solo i comandi. +> **In questa versione** la ricerca trova le **pagine** del menu, i **comandi** (tema, menu, profilo, sessioni, +> scorciatoie) e le **pagine dell'aiuto** (titoli e sezioni, che si aprono al punto giusto). Clienti, articoli e +> documenti si aggiungono con le milestone che li introducono: per ora `#` e `@` dicono con quali moduli arrivano. Premi `Ctrl+K` (o fai clic sulla casella di ricerca) e digita. I risultati arrivano mentre scrivi, raggruppati per tipo: **clienti e fornitori**, **articoli**, **documenti**, **registrazioni e conti** contabili, **azioni** (ad @@ -114,7 +114,8 @@ esempio *Nuova fattura per Rossi Impianti*, *Registra incasso*, *Scheda cliente | `@` | persone (contatti, utenti) | `@ verdi` | Con le frecce `↑` `↓` ti sposti tra i risultati, con `Invio` apri quello evidenziato; il piede della finestra ricorda -anche l'apertura in una nuova scheda (`Ctrl+Invio`) e i prefissi. `Esc` chiude. +i prefissi. `Esc` chiude. Pagine e comandi compaiono subito; gli altri risultati arrivano un attimo dopo che hai +smesso di scrivere, da almeno due caratteri. ## Notifiche @@ -126,9 +127,16 @@ programmate, SDI (scarti, notifiche), scadenze, magazzino (sottoscorta) e sicure dispositivo sconosciuto). Ogni voce ha icona, titolo, dettaglio e, se serve, un'etichetta d'urgenza (*Nuova*, *Da gestire*, *Verifica*); un clic apre il documento o la maschera collegata. -In alto i filtri **Tutte**, **Non lette**, **Errori**; in basso **Segna tutte come lette** e **Impostazioni notifiche** -(che porta alla scheda *Notifiche* di [Il mio profilo](Preferenze-utente), dove si attiva anche il riepilogo via -e-mail). +In alto i filtri **Tutte** e **Non lette**, con il numero di voci; in basso **Segna tutte come lette**. Ogni voce ha +il segno di spunta per segnarla come letta; il clic sul titolo la segna e apre la maschera collegata. Il numero +sulla campanella si aggiorna da solo ogni minuto. + +Chi legge una notifica rivolta a tutti la segna come letta **solo per sé**: per i colleghi resta da leggere. Gli +account di istanza vedono le notifiche di sistema (backup, attività programmate, licenza), gli utenti aziendali +quelle della propria azienda. Il pannello mostra le ultime 100 notifiche. + +> **In questa versione** mancano il filtro *Errori* e *Impostazioni notifiche* (riepilogo via e-mail), che arrivano +> con le automazioni. ## Aiuto in app (F1) @@ -138,10 +146,11 @@ e-mail). `F1` o il pulsante `?` aprono, in una nuova scheda, **la pagina wiki della maschera** su cui stai lavorando (ogni maschera ha il proprio collegamento). La pagina mostra in testa lo stato (*bozza*, *completa*), la revisione e la data di aggiornamento; a sinistra c'è l'indice delle pagine. In alto a destra: **Apri nel wiki** (apre la wiki completa -nel browser) e **Segnala un problema**. +nel browser) e **Segnala un problema** (apre una nuova segnalazione nel repository della wiki). -L'indirizzo della wiki è configurabile; per le installazioni senza accesso a Internet Khaemhat serve una copia della -wiki all'indirizzo `/help` della propria istanza. +L'aiuto è una **copia della wiki contenuta nell'immagine Docker**, all'indirizzo `/aiuto` dell'istanza (`/help` porta +lì): funziona anche senza Internet e corrisponde sempre alla versione installata, immagini comprese. La variabile +`KHAEMHAT_HELP_URL` cambia solo la wiki aperta da *Apri nel wiki* (vedi [Installazione Docker](Installazione-Docker)). ## Toolbar a icone diff --git a/src/Khaemhat.Application/Configuration/EnvironmentConfigurationReader.cs b/src/Khaemhat.Application/Configuration/EnvironmentConfigurationReader.cs index bec0f5a..f946a18 100644 --- a/src/Khaemhat.Application/Configuration/EnvironmentConfigurationReader.cs +++ b/src/Khaemhat.Application/Configuration/EnvironmentConfigurationReader.cs @@ -65,6 +65,7 @@ public sealed class EnvironmentConfigurationReader SeedDemo = Get("KHAEMHAT_SEED_DEMO"), UpdateFeed = Get("KHAEMHAT_UPDATE_FEED"), UpdateToken = Get("KHAEMHAT_UPDATE_TOKEN"), + HelpUrl = Get("KHAEMHAT_HELP_URL"), TimeZone = Get("TZ"), ReadErrors = errors, }; diff --git a/src/Khaemhat.Application/Configuration/KhaemhatOptions.cs b/src/Khaemhat.Application/Configuration/KhaemhatOptions.cs index 0a71204..5ea9916 100644 --- a/src/Khaemhat.Application/Configuration/KhaemhatOptions.cs +++ b/src/Khaemhat.Application/Configuration/KhaemhatOptions.cs @@ -150,6 +150,12 @@ public sealed class KhaemhatOptions /// KHAEMHAT_UPDATE_TOKEN: a read-only token for the feed. public string? UpdateToken { get; init; } + /// + /// KHAEMHAT_HELP_URL: the online wiki opened by "Apri nel wiki" (default the project wiki). The help itself + /// is the copy of the wiki shipped in the image, so it works offline. + /// + public string? HelpUrl { get; init; } + /// TZ: the time zone of the container. public string? TimeZone { get; init; } @@ -265,6 +271,11 @@ public sealed class KhaemhatOptions errors.Add("KHAEMHAT_PUBLIC_URL must be an absolute http or https address, for example https://gestionale.example.com."); } + if (HelpUrl is not null && !IsHttpUrl(HelpUrl)) + { + errors.Add("KHAEMHAT_HELP_URL must be an absolute http or https address, for example https://gitea.example.com/owner/khaemhat/wiki/."); + } + if (SmtpPort is not null && !(int.TryParse(SmtpPort, NumberStyles.None, CultureInfo.InvariantCulture, out var port) && port is > 0 and < 65536)) { errors.Add("KHAEMHAT_SMTP_PORT must be a port number between 1 and 65535."); diff --git a/src/Khaemhat.Application/Dashboard/SystemFeedSources.cs b/src/Khaemhat.Application/Dashboard/SystemFeedSources.cs index 51a958e..05cfb0d 100644 --- a/src/Khaemhat.Application/Dashboard/SystemFeedSources.cs +++ b/src/Khaemhat.Application/Dashboard/SystemFeedSources.cs @@ -90,12 +90,7 @@ public sealed class NotificationTodoSource(NotificationDispatcher notifications) public async Task> GetAsync(FeedContext context, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(context); - IReadOnlyList unread = context.Actor switch - { - { SystemUserId: { } id } => await notifications.UnreadForInstanceAsync(id, cancellationToken).ConfigureAwait(false), - { CompanyUserId: { } id, CompanyCode: { } company } => await notifications.UnreadForUserAsync(company, id, cancellationToken).ConfigureAwait(false), - _ => [], - }; + var unread = await notifications.InboxAsync(context.Actor, unreadOnly: true, cancellationToken).ConfigureAwait(false); return [.. unread .Where(n => n.Severity >= NotificationSeverity.Warning) diff --git a/src/Khaemhat.Application/Notifications/NotificationDispatcher.cs b/src/Khaemhat.Application/Notifications/NotificationDispatcher.cs index cad2ebe..23e7d1b 100644 --- a/src/Khaemhat.Application/Notifications/NotificationDispatcher.cs +++ b/src/Khaemhat.Application/Notifications/NotificationDispatcher.cs @@ -1,3 +1,4 @@ +using Khaemhat.Application.Security; using Khaemhat.Core.Instance; using Khaemhat.Data; using Khaemhat.Data.Querying; @@ -13,14 +14,27 @@ namespace Khaemhat.Application.Notifications; /// A link inside the application. public sealed record NotificationMessage(string Category, NotificationSeverity Severity, string Title, string? Body = null, string? Link = null); +/// A notification as its recipient sees it. +/// The id. +/// The area. +/// The weight. +/// The title. +/// The text. +/// A link inside the application. +/// When it was sent (UTC). +/// Whether this user read it. +/// Addressed to this user only, not to everyone. +public sealed record InboxItem(long Id, string Category, NotificationSeverity Severity, string Title, string? Body, string? Link, DateTime CreatedAt, bool Read, bool Personal); + /// /// Delivers in-app notifications (SPEC §9; mockup 010): to instance accounts in sys_notifications, to company /// users in the company's notifications. A notification without recipient goes to everyone in the scope. /// Delivery never breaks the caller: a failure is logged. /// /// Opens the databases. +/// The clock. /// The log. -public sealed class NotificationDispatcher(IUnitOfWorkFactory factory, ILogger logger) +public sealed class NotificationDispatcher(IUnitOfWorkFactory factory, TimeProvider clock, ILogger logger) { /// Notifies instance accounts. /// The notification. @@ -61,29 +75,114 @@ public sealed class NotificationDispatcher(IUnitOfWorkFactory factory, ILoggerThe unread notifications of an instance account (its own and those for everyone). - /// The account. + /// The most notifications a user sees: the newest ones. + public const int InboxSize = 100; + + /// The notifications of a user, newest first (mockup 010). + /// The user: instance accounts read the system ones, company users those of their company. + /// Only those not read yet. /// Cancellation. - /// The notifications, newest first. - public async Task> UnreadForInstanceAsync(long userId, CancellationToken cancellationToken = default) + /// The notifications, at most . + public Task> InboxAsync(Actor actor, bool unreadOnly = false, CancellationToken cancellationToken = default) => + ScopeOf(actor) switch + { + ({ } scope, { } user, true) => InboxAsync(scope, user, unreadOnly, cancellationToken), + ({ } scope, { } user, false) => InboxAsync(scope, user, unreadOnly, cancellationToken), + _ => Task.FromResult>([]), + }; + + /// Marks a notification as read by the user. A notification for everyone stays unread for the others. + /// The user. + /// The notification. + /// Cancellation. + /// A task. + public Task MarkReadAsync(Actor actor, long notificationId, CancellationToken cancellationToken = default) => + MarkAsync(actor, [notificationId], cancellationToken); + + /// Marks every notification of the user as read. + /// The user. + /// Cancellation. + /// A task. + public async Task MarkAllReadAsync(Actor actor, CancellationToken cancellationToken = default) { - await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false); - return (await unitOfWork.Repository().ListAsync( - Query.For().Where(n => n.ReadAt == null && (n.RecipientUserId == null || n.RecipientUserId == userId)).OrderByDescending(n => n.Id).Take(100), - cancellationToken).ConfigureAwait(false)).Items; + var unread = await InboxAsync(actor, unreadOnly: true, cancellationToken).ConfigureAwait(false); + await MarkAsync(actor, [.. unread.Select(n => n.Id)], cancellationToken).ConfigureAwait(false); } - /// The unread notifications of a company user. - /// The company. - /// The user. - /// Cancellation. - /// The notifications, newest first. - public async Task> UnreadForUserAsync(string companyCode, long userId, CancellationToken cancellationToken = default) + private Task MarkAsync(Actor actor, IReadOnlyList ids, CancellationToken cancellationToken) => + ids.Count == 0 + ? Task.CompletedTask + : ScopeOf(actor) switch + { + ({ } scope, { } user, true) => MarkAsync(scope, user, ids, cancellationToken), + ({ } scope, { } user, false) => MarkAsync(scope, user, ids, cancellationToken), + _ => Task.CompletedTask, + }; + + private static (DatabaseScope? Scope, long? User, bool System) ScopeOf(Actor actor) { - await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); - return (await unitOfWork.Repository().ListAsync( - Query.For().Where(n => n.ReadAt == null && (n.RecipientUserId == null || n.RecipientUserId == userId)).OrderByDescending(n => n.Id).Take(100), + ArgumentNullException.ThrowIfNull(actor); + return actor switch + { + { SystemUserId: { } id } => (DatabaseScope.System, id, true), + { CompanyUserId: { } id, CompanyCode: { } company } => (DatabaseScope.Company(company), id, false), + _ => (null, null, false), + }; + } + + private async Task> InboxAsync(DatabaseScope scope, long userId, bool unreadOnly, CancellationToken cancellationToken) + where TNotification : NotificationRecord, new() + where TRead : NotificationReadRecord, new() + { + await using var unitOfWork = await factory.CreateAsync(scope, cancellationToken).ConfigureAwait(false); + var notifications = (await unitOfWork.Repository().ListAsync( + Query.For().Where(n => n.RecipientUserId == null || n.RecipientUserId == userId).OrderByDescending(n => n.Id).Take(InboxSize), cancellationToken).ConfigureAwait(false)).Items; + var everyone = notifications.Where(n => n.RecipientUserId == null).Select(n => n.Id).ToList(); + var read = everyone.Count == 0 + ? [] + : (await unitOfWork.Repository().ListAsync( + Query.For().Where(r => r.UserId == userId && everyone.Contains(r.NotificationId)), cancellationToken).ConfigureAwait(false)).Items + .Select(r => r.NotificationId).ToHashSet(); + return [.. notifications + .Select(n => new InboxItem(n.Id, n.Category, n.Severity, n.Title, n.Body, n.Link, n.CreatedAt, + n.RecipientUserId is null ? read.Contains(n.Id) : n.ReadAt is not null, n.RecipientUserId is not null)) + .Where(n => !unreadOnly || !n.Read)]; + } + + private async Task MarkAsync(DatabaseScope scope, long userId, IReadOnlyList ids, CancellationToken cancellationToken) + where TNotification : NotificationRecord, new() + where TRead : NotificationReadRecord, new() + { + await using var unitOfWork = await factory.CreateAsync(scope, cancellationToken).ConfigureAwait(false); + var list = ids.ToList(); + var repository = unitOfWork.Repository(); + var notifications = (await repository.ListAsync( + Query.For().Where(n => list.Contains(n.Id) && (n.RecipientUserId == null || n.RecipientUserId == userId)), cancellationToken).ConfigureAwait(false)).Items; + var reads = unitOfWork.Repository(); + var already = (await reads.ListAsync(Query.For().Where(r => r.UserId == userId && list.Contains(r.NotificationId)), cancellationToken).ConfigureAwait(false)).Items + .Select(r => r.NotificationId).ToHashSet(); + var now = clock.GetUtcNow().UtcDateTime; + await unitOfWork.InTransactionAsync( + async ct => + { + foreach (var notification in notifications) + { + if (notification.RecipientUserId is null) + { + if (already.Add(notification.Id)) + { + await reads.InsertAsync(new TRead { NotificationId = notification.Id, UserId = userId }, ct).ConfigureAwait(false); + } + } + else if (notification.ReadAt is null) + { + notification.ReadAt = now; + await repository.UpdateAsync(notification, ct).ConfigureAwait(false); + } + } + }, + cancellationToken).ConfigureAwait(false); } private static T Fill(T notification, NotificationMessage message, long? recipient) diff --git a/src/Khaemhat.Application/Search/GlobalSearchService.cs b/src/Khaemhat.Application/Search/GlobalSearchService.cs new file mode 100644 index 0000000..fdf03de --- /dev/null +++ b/src/Khaemhat.Application/Search/GlobalSearchService.cs @@ -0,0 +1,133 @@ +using Khaemhat.Application.Security; +using Microsoft.Extensions.Logging; + +namespace Khaemhat.Application.Search; + +/// What the search looks for, from the first character of the query (SPEC §10.2, mockup 009). +public enum SearchScope +{ + /// Everything: pages, records, help. + All, + + /// >: only the commands. + Commands, + + /// #: only the documents. + Documents, + + /// @: only the people. + People, +} + +/// A search, split into scope and words. +/// What it looks for. +/// The words, without the prefix. +public sealed record SearchQuery(SearchScope Scope, string Text) +{ + /// The fewest characters before records are searched. + public const int MinimumLength = 2; + + /// The words of the query. + public IReadOnlyList Words { get; } = Text.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + + /// Reads what the user typed. + /// The text of the search box. + /// The query. + public static SearchQuery Parse(string? input) + { + var text = (input ?? string.Empty).Trim(); + var scope = text.Length == 0 ? SearchScope.All : text[0] switch + { + '>' => SearchScope.Commands, + '#' => SearchScope.Documents, + '@' => SearchScope.People, + _ => SearchScope.All, + }; + return new SearchQuery(scope, scope == SearchScope.All ? text : text[1..].Trim()); + } + + /// Whether a text contains every word, ignoring case. + /// The text. + /// if it does; always for an empty query. + public bool Matches(string? value) => + Words.Count == 0 || (value is not null && Words.All(w => value.Contains(w, StringComparison.CurrentCultureIgnoreCase))); +} + +/// A search result. +/// The text key of the group shown above it, such as Shell.Search.Help. +/// The icon. +/// The title. +/// A second line, such as the page a heading belongs to. +/// Where it opens, relative to the application. +public sealed record SearchHit(string Group, string Icon, string Title, string? Detail, string Href); + +/// A source of search results: each module adds its own (parties, items, documents, accounts...). +public interface ISearchProvider +{ + /// The scopes it answers: and, for example, . + IReadOnlyCollection Scopes { get; } + + /// Searches. + /// Who searches: results respect permissions and company. + /// The query, at least characters. + /// Cancellation: the user typed something else. + /// At most results, best first. + Task> SearchAsync(Actor actor, SearchQuery query, CancellationToken cancellationToken); +} + +/// +/// The records part of the global search (SPEC §10.2): asks every provider of the scope, in parallel, and puts the +/// results together. A provider that fails or is slow is left out, the others are shown. +/// +public sealed class GlobalSearchService(IEnumerable providers, ILogger logger) +{ + /// The most results of one provider. + public const int PerProvider = 8; + + private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(3); + + private readonly ISearchProvider[] _providers = [.. providers]; + + /// Whether something answers a scope: without, the search says what it will find in a later version. + /// The scope. + /// if a provider does. + public bool Covers(SearchScope scope) => _providers.Any(p => p.Scopes.Contains(scope)); + + /// Searches the records. + /// Who searches. + /// The query. + /// Cancellation. + /// The results, grouped by provider in registration order. + public async Task> SearchAsync(Actor actor, SearchQuery query, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(query); + if (query.Scope == SearchScope.Commands || query.Text.Length < SearchQuery.MinimumLength) + { + return []; + } + + var results = await Task.WhenAll(_providers.Where(p => p.Scopes.Contains(query.Scope)).Select(p => AskAsync(p, actor, query, cancellationToken))).ConfigureAwait(false); + return [.. results.SelectMany(r => r)]; + } + + private async Task> AskAsync(ISearchProvider provider, Actor actor, SearchQuery query, CancellationToken cancellationToken) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(Timeout); + try + { + return [.. (await provider.SearchAsync(actor, query, timeout.Token).ConfigureAwait(false)).Take(PerProvider)]; + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + logger.LogWarning("Search provider {Provider} took longer than {Timeout} and was left out", provider.GetType().Name, Timeout); + return []; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + logger.LogError(ex, "Search provider {Provider} failed", provider.GetType().Name); + return []; + } + } +} diff --git a/src/Khaemhat.Core/Instance/InstanceRecords.cs b/src/Khaemhat.Core/Instance/InstanceRecords.cs index 84c5518..4376d0d 100644 --- a/src/Khaemhat.Core/Instance/InstanceRecords.cs +++ b/src/Khaemhat.Core/Instance/InstanceRecords.cs @@ -347,3 +347,23 @@ public sealed class SystemNotification : NotificationRecord; /// A notification for company users (notifications). public sealed class Notification : NotificationRecord; + +/// +/// That a user read a notification addressed to everyone: each user reads it for themselves (notification_reads, +/// sys_notification_reads). A notification for one user keeps its own . +/// The audit column created_at is when it was read. +/// +public abstract class NotificationReadRecord : Entity +{ + /// The notification. + public long NotificationId { get; set; } + + /// The user who read it. + public long UserId { get; set; } +} + +/// An instance account read a notification for everyone (sys_notification_reads). +public sealed class SystemNotificationRead : NotificationReadRecord; + +/// A company user read a notification for everyone (notification_reads). +public sealed class NotificationRead : NotificationReadRecord; diff --git a/src/Khaemhat.Data/CompanyDatabase/CompanyMaps.cs b/src/Khaemhat.Data/CompanyDatabase/CompanyMaps.cs index 32e3a73..84a9199 100644 --- a/src/Khaemhat.Data/CompanyDatabase/CompanyMaps.cs +++ b/src/Khaemhat.Data/CompanyDatabase/CompanyMaps.cs @@ -97,6 +97,13 @@ public sealed class NotificationMap : EntityMap } } +/// Map of to notification_reads. +public sealed class NotificationReadMap : EntityMap +{ + /// Creates the map. + public NotificationReadMap() => ToTable("notification_reads"); +} + /// Map of to user_settings. public sealed class UserSettingMap : EntityMap { diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_009_CreateNotificationReads.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_009_CreateNotificationReads.cs new file mode 100644 index 0000000..ca9cdd0 --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_009_CreateNotificationReads.cs @@ -0,0 +1,24 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// Who read a notification addressed to everyone (SPEC §9, mockup 010): each user marks it for themselves. +[Migration(20261111_009, "create_notification_reads")] +public sealed class M20261111_009_CreateNotificationReads : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("notification_reads", t => + { + t.Id(); + t.Int64("notification_id").NotNull(); + t.Int64("user_id").NotNull(); + t.AuditColumns(); + t.Unique("ux_notification_reads_notification_user", "notification_id", "user_id"); + t.Index("ix_notification_reads_user_id", "user_id"); + }); + } +} diff --git a/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_013_CreateSysNotificationReads.cs b/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_013_CreateSysNotificationReads.cs new file mode 100644 index 0000000..7d8a8fd --- /dev/null +++ b/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_013_CreateSysNotificationReads.cs @@ -0,0 +1,24 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.SystemDatabase.Migrations; + +/// Who read a notification addressed to everyone (SPEC §9, mockup 010): each user marks it for themselves. +[Migration(20261111_013, "create_sys_notification_reads", Target = MigrationTarget.System)] +public sealed class M20261111_013_CreateSysNotificationReads : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("sys_notification_reads", t => + { + t.Id(); + t.Int64("notification_id").NotNull(); + t.Int64("user_id").NotNull(); + t.AuditColumns(); + t.Unique("ux_sys_notification_reads_notification_user", "notification_id", "user_id"); + t.Index("ix_sys_notification_reads_user_id", "user_id"); + }); + } +} diff --git a/src/Khaemhat.Data/SystemDatabase/SecurityMaps.cs b/src/Khaemhat.Data/SystemDatabase/SecurityMaps.cs index 4f80b64..0633a0b 100644 --- a/src/Khaemhat.Data/SystemDatabase/SecurityMaps.cs +++ b/src/Khaemhat.Data/SystemDatabase/SecurityMaps.cs @@ -197,6 +197,13 @@ public sealed class SystemNotificationMap : EntityMap } } +/// Map of to sys_notification_reads. +public sealed class SystemNotificationReadMap : EntityMap +{ + /// Creates the map. + public SystemNotificationReadMap() => ToTable("sys_notification_reads"); +} + /// The notification columns shared by sys_notifications and notifications. internal static class NotificationColumns { diff --git a/src/Khaemhat.Web/Components/Layout/MainLayout.razor b/src/Khaemhat.Web/Components/Layout/MainLayout.razor index 3e8a836..787f701 100644 --- a/src/Khaemhat.Web/Components/Layout/MainLayout.razor +++ b/src/Khaemhat.Web/Components/Layout/MainLayout.razor @@ -217,10 +217,16 @@ } } - private async Task OpenHelpAsync() + // F1 and the "?" open the help of the screen in a tab of its own (mockup 011); on a help page they stay there. + private Task OpenHelpAsync() { - var path = TabService.PathOf(Navigation.ToBaseRelativePath(Navigation.Uri)); - await Js.InvokeVoidAsync("khaemhat.openWindow", HelpLinks.UrlFor(HelpLinks.DefaultBaseUrl, path)); + var path = TabService.PathOf("/" + Navigation.ToBaseRelativePath(Navigation.Uri)); + if (!path.StartsWith(Khaemhat.Web.Help.WikiLibrary.BasePath, StringComparison.OrdinalIgnoreCase)) + { + Navigation.NavigateTo(HelpLinks.LocalFor(path)); + } + + return Task.CompletedTask; } private async Task OnShortcutAsync(string command) diff --git a/src/Khaemhat.Web/Components/Pages/ComingSoon.razor b/src/Khaemhat.Web/Components/Pages/ComingSoon.razor index 424700a..dc42fc8 100644 --- a/src/Khaemhat.Web/Components/Pages/ComingSoon.razor +++ b/src/Khaemhat.Web/Components/Pages/ComingSoon.razor @@ -48,7 +48,7 @@ else } } diff --git a/src/Khaemhat.Web/Components/Pages/Help.razor b/src/Khaemhat.Web/Components/Pages/Help.razor new file mode 100644 index 0000000..2326ff3 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Help.razor @@ -0,0 +1,73 @@ +@page "/aiuto" +@page "/aiuto/{Name}" +@attribute [Authorize] +@using Khaemhat.Application.Configuration +@using Khaemhat.Web.Help +@inject WikiLibrary Wiki +@inject KhaemhatOptions Options + +@* The help of SPEC §17 (mockup 011): the wiki page of the screen, from the copy shipped with the application, with + the wiki index at the side, "Apri nel wiki" for the online version and "Segnala un problema". F1 and the "?" of the + top bar open it on the page of the current screen. *@ + + +
+
+
@T["Pages.Help.Crumb"]@if (Section is { } section){ › @section.Title} › @(Current?.Title ?? Name)
+

@T.Format("Pages.Help.Heading", Current?.Title ?? T["Pages.Help.Title"])

+
+
+ @T["Pages.Help.OpenWiki"] + @if (IssuesUrl is { } issues) + { + @T["Pages.Help.Report"] + } +
+ +
+ +
+ @if (!Wiki.IsAvailable) + { +
@T["Pages.Help.Missing"]
+ } + else if (Current is null) + { +
@T.Format("Pages.Help.NotFound", Name ?? string.Empty)
+ } + else + { + @((MarkupString)Current.Html) + } +
+
+ +@code { + /// The wiki page, such as Interfaccia-e-scorciatoie; empty for the wiki home. + [Parameter] + public string? Name { get; set; } + + private string PageName => string.IsNullOrWhiteSpace(Name) ? "Home" : Name; + + private WikiPage? Current => Wiki.Get(PageName); + + private WikiSection? Section => Wiki.Sidebar.FirstOrDefault(s => s.Pages.Any(p => string.Equals(p.Page, PageName, StringComparison.OrdinalIgnoreCase))); + + private string BaseUrl => HelpLinks.BaseUrl(Options.HelpUrl); + + private string OnlineUrl => BaseUrl + (Current?.Name ?? PageName); + + private string? IssuesUrl => HelpLinks.IssuesUrl(BaseUrl); +} diff --git a/src/Khaemhat.Web/Components/Shell/KhCommandPalette.razor b/src/Khaemhat.Web/Components/Shell/KhCommandPalette.razor index 781003c..53a8576 100644 --- a/src/Khaemhat.Web/Components/Shell/KhCommandPalette.razor +++ b/src/Khaemhat.Web/Components/Shell/KhCommandPalette.razor @@ -1,10 +1,14 @@ @inject ShellSession Session @inject NavigationManager Navigation @inject ThemeService Theme +@inject GlobalSearchService Search +@implements IDisposable +@using Khaemhat.Application.Search -@* The global search of SPEC §10.2 (Ctrl+K, mockup 009). Today it finds pages of the menu and commands (prefix >); - records (parties, items, documents with #, people with @) join as their modules arrive, through - GlobalSearchService. Arrows move, Enter opens, Escape closes. *@ +@* The global search of SPEC §10.2 (Ctrl+K, mockup 009). Pages of the menu and commands (prefix >) are found at once; + records come from the providers of GlobalSearchService (today the help pages; parties, items, documents with # + and people with @ join as their modules arrive), a moment after the user stops typing. Arrows move, Enter opens, + Escape closes. *@ @if (Open) {
@@ -17,7 +21,11 @@ @T["Shell.Keys.Escape"]
- @if (Hits.Count == 0) + @if (Soon is { } soon) + { +
@T[soon]
+ } + else if (Hits.Count == 0 && !_searching) {
@T["Shell.Search.NoResults"]
} @@ -38,6 +46,10 @@ @onclick="() => RunAsync(hit)" @onmouseover="() => _selected = i"> @hit.Title + @if (hit.Detail is not null) + { + @hit.Detail + } @if (hit.Hint is not null) { @hit.Hint @@ -49,18 +61,24 @@ ↑↓ @T["Shell.Search.Move"] ↵ @T["Shell.Search.Open"] > @T["Shell.Search.Commands"] + # @T["Shell.Search.Documents"] + @@ @T["Shell.Search.People"]
} @code { - private sealed record Hit(string Group, string Icon, string Title, string? Hint, Func Run); + private sealed record Hit(string Group, string Icon, string Title, string? Hint, Func Run, string? Detail = null); + + private static readonly TimeSpan Pause = TimeSpan.FromMilliseconds(200); private ElementReference _input; private string _query = string.Empty; private int _selected; private bool _focus; + private bool _searching; + private CancellationTokenSource? _pending; /// Whether the search is open. [Parameter] @@ -76,6 +94,14 @@ private List Hits { get; set; } = []; + // # and @ before their modules: say when they will find something instead of "no results". + private string? Soon => SearchQuery.Parse(_query) switch + { + { Scope: SearchScope.Documents } when !Search.Covers(SearchScope.Documents) => "Shell.Search.DocumentsSoon", + { Scope: SearchScope.People } when !Search.Covers(SearchScope.People) => "Shell.Search.PeopleSoon", + _ => null, + }; + /// protected override void OnParametersSet() { @@ -84,10 +110,11 @@ _query = string.Empty; _selected = 0; _focus = true; - Hits = Search(_query); + Hits = Local(_query); } else if (!Open) { + Cancel(); Hits = []; } } @@ -102,13 +129,52 @@ } } - private void OnInput(ChangeEventArgs e) + private async Task OnInput(ChangeEventArgs e) { _query = e.Value?.ToString() ?? string.Empty; _selected = 0; - Hits = Search(_query); + Hits = Local(_query); + Cancel(); + var query = SearchQuery.Parse(_query); + if (Session.Actor is not { } actor || query.Scope == SearchScope.Commands || query.Text.Length < SearchQuery.MinimumLength) + { + _searching = false; + return; + } + + // Wait for a pause in the typing, then ask the providers; a newer input cancels this one. + var pending = _pending = new CancellationTokenSource(); + _searching = true; + try + { + await Task.Delay(Pause, pending.Token); + var found = await Search.SearchAsync(actor, query, pending.Token); + if (pending.IsCancellationRequested || !Open) + { + return; + } + + var local = Local(_query); + Hits = [.. (query.Scope == SearchScope.All ? local : []).Concat(found.Select(h => new Hit(h.Group, h.Icon, h.Title, null, () => Go(h.Href), h.Detail)))]; + _selected = Math.Min(_selected, Math.Max(0, Hits.Count - 1)); + _searching = false; + } + catch (OperationCanceledException) + { + // The user typed something else. + } } + private void Cancel() + { + _pending?.Cancel(); + _pending?.Dispose(); + _pending = null; + } + + /// + public void Dispose() => Cancel(); + private async Task OnKeyDownAsync(KeyboardEventArgs e) { switch (e.Key) @@ -136,21 +202,23 @@ private Task CloseAsync() { + Cancel(); + _searching = false; Hits = []; return OpenChanged.InvokeAsync(false); } - private List Search(string query) + private List Local(string input) { - var text = query.Trim(); - var commandsOnly = text.StartsWith('>'); - if (commandsOnly) + var query = SearchQuery.Parse(input); + if (query.Scope is SearchScope.Documents or SearchScope.People) { - text = text[1..].Trim(); + return []; } + var text = query.Text; var hits = new List(); - if (!commandsOnly) + if (query.Scope == SearchScope.All) { foreach (var item in MenuCatalog.All.Where(Session.CanSee)) { diff --git a/src/Khaemhat.Web/Components/Shell/NotificationPanel.razor b/src/Khaemhat.Web/Components/Shell/NotificationPanel.razor new file mode 100644 index 0000000..823d93b --- /dev/null +++ b/src/Khaemhat.Web/Components/Shell/NotificationPanel.razor @@ -0,0 +1,167 @@ +@using Khaemhat.Application.Notifications +@using Khaemhat.Application.Preferences +@using Khaemhat.Core.Instance +@inject ShellSession Session +@inject NotificationDispatcher Notifications +@inject NavigationManager Navigation +@inject TimeProvider Clock + +@* The notifications of SPEC §9 (mockup 010): a side panel from the bell with all or only the unread ones, newest + first. A click marks one as read and opens its page; "Segna tutte come lette" clears the bell. A notification for + everyone is read by each user for themselves. *@ + + +
+ + +
+ @if (!_loaded) + { +

@T["Common.Loading"]

+ } + else if (!Shown.Any()) + { +

@T[_unreadOnly ? "Shell.Notifications.NoneUnread" : "Shell.Notifications.None"]

+ } + else + { +
    + @foreach (var item in Shown) + { +
  • + + + @if (!item.Read) + { + + } +
  • + } +
+ } +
+
+ +
+
+ +@code { + private IReadOnlyList _items = []; + private bool _unreadOnly; + private bool _loaded; + private bool _wasOpen; + + /// Whether the panel is shown. + [Parameter] + public bool Open { get; set; } + + /// Opens or closes it. + [Parameter] + public EventCallback OpenChanged { get; set; } + + /// Told the unread count after every change. + [Parameter] + public EventCallback UnreadChanged { get; set; } + + private int Unread => _items.Count(i => !i.Read); + + private IEnumerable Shown => _unreadOnly ? _items.Where(i => !i.Read) : _items; + + /// + protected override async Task OnParametersSetAsync() + { + if (Open && !_wasOpen) + { + _loaded = false; + await LoadAsync(); + } + + _wasOpen = Open; + } + + private async Task LoadAsync() + { + _items = Session.Actor is { } actor ? await Notifications.InboxAsync(actor) : []; + _loaded = true; + await UnreadChanged.InvokeAsync(Unread); + } + + private Task CloseAsync() => OpenChanged.InvokeAsync(false); + + private async Task MarkReadAsync(InboxItem item) + { + if (Session.Actor is { } actor && !item.Read) + { + await Notifications.MarkReadAsync(actor, item.Id); + await LoadAsync(); + } + } + + private async Task OpenAsync(InboxItem item) + { + await MarkReadAsync(item); + if (UserPreferences.IsLocalPath(item.Link)) + { + await CloseAsync(); + Navigation.NavigateTo(item.Link!.TrimStart('/')); + } + } + + private async Task MarkAllAsync() + { + if (Session.Actor is { } actor) + { + await Notifications.MarkAllReadAsync(actor); + await LoadAsync(); + } + } + + private string CategoryOf(string category) => + T.Contains("Shell.Notifications.Categories." + category) ? T["Shell.Notifications.Categories." + category] : category; + + private string When(DateTime createdAt) + { + var at = new DateTimeOffset(DateTime.SpecifyKind(createdAt, DateTimeKind.Utc)).ToOffset(Clock.GetLocalNow().Offset); + var now = Clock.GetLocalNow(); + var minutes = (int)(now - at).TotalMinutes; + return minutes switch + { + < 1 => T["Shell.Notifications.Now"], + < 60 => T.Format("Shell.Notifications.MinutesAgo", minutes), + _ when at.Date == now.Date => at.ToString("HH:mm", T.Culture), + _ when at.Date == now.Date.AddDays(-1) => T.Format("Shell.Notifications.Yesterday", at.ToString("HH:mm", T.Culture)), + _ => at.ToString("d MMM HH:mm", T.Culture), + }; + } + + private static string IconOf(NotificationSeverity severity) => severity switch + { + NotificationSeverity.Error => "x-circle", + NotificationSeverity.Warning => "alert", + NotificationSeverity.Success => "check-circle", + _ => "info", + }; + + private static string? ToneOf(NotificationSeverity severity) => severity switch + { + NotificationSeverity.Error => "err", + NotificationSeverity.Warning => "warn", + NotificationSeverity.Success => "ok", + _ => null, + }; +} diff --git a/src/Khaemhat.Web/Components/Shell/TopBar.razor b/src/Khaemhat.Web/Components/Shell/TopBar.razor index b413306..681827d 100644 --- a/src/Khaemhat.Web/Components/Shell/TopBar.razor +++ b/src/Khaemhat.Web/Components/Shell/TopBar.razor @@ -54,34 +54,15 @@ } -
- - @if (_open == Popup.Notifications) +
+ @T["Shell.TopBar.Notifications"] +