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 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 19:39:17 +01:00
1 parent acb7e598d1
commit f415dc37a8
39 files changed
+1976 -107

No files matched your search

+4
View File
@@ -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
+9
View File
@@ -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
+1
View File
@@ -32,6 +32,7 @@
<Config Name="KHAEMHAT_LICENSE_MODE" Target="KHAEMHAT_LICENSE_MODE" Default="production" Mode="" Description="production oppure test (abilita i codici di licenza fittizi)" Type="Variable" Display="advanced" Required="false" Mask="false">production</Config>
<Config Name="KHAEMHAT_LICENSE" Target="KHAEMHAT_LICENSE" Default="" Mode="" Description="Licenza firmata (.khl, testo). Vuoto = Trial" Type="Variable" Display="advanced" Required="false" Mask="true"></Config>
<Config Name="KHAEMHAT_SEED_DEMO" Target="KHAEMHAT_SEED_DEMO" Default="false" Mode="" Description="true = dati dimostrativi al primo avvio (solo database vuoto)" Type="Variable" Display="advanced" Required="false" Mask="false">false</Config>
<Config Name="KHAEMHAT_HELP_URL" Target="KHAEMHAT_HELP_URL" Default="" Mode="" Description="Opzionale: wiki online aperta da Apri nel wiki (predefinita https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/)" Type="Variable" Display="advanced" Required="false" Mask="false"></Config>
<Config Name="KHAEMHAT_UPDATE_FEED" Target="KHAEMHAT_UPDATE_FEED" Default="" Mode="" Description="Opzionale: URL API pacchetti Gitea per il controllo aggiornamenti (https://gitea.encke-hake.ts.net/api/v1/packages/BalboSoft?type=container&amp;q=khaemhat)" Type="Variable" Display="advanced" Required="false" Mask="false"></Config>
<Config Name="TZ" Target="TZ" Default="Europe/Rome" Mode="" Description="Fuso orario" Type="Variable" Display="advanced" Required="false" Mask="false">Europe/Rome</Config>
<Config Name="PUID" Target="PUID" Default="99" Mode="" Description="UID per i file in /data" Type="Variable" Display="advanced" Required="false" Mask="false">99</Config>
+34
View File
@@ -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 |
+55
View File
@@ -0,0 +1,55 @@
# ADR 0023 - Aiuto in app dalla copia della wiki, notifiche lette per utente, ricerca a fornitori
- **Stato:** accettata
- **Data:** 2026-11-11
- **Modifica:** SPEC §10.2, §17; milestone M3, issue #32 (mockup 009, 010, 011)
## Contesto
La specifica chiede che `F1` apra la pagina wiki della maschera dentro l'applicazione (mockup 011), con indice,
*Apri nel wiki* e *Segnala un problema*, e che l'aiuto funzioni anche nelle installazioni senza Internet servendo
una copia della wiki "all'indirizzo `/help`". Non dice come la copia arriva nell'immagine, come si converte il
Markdown senza librerie esterne (SPEC §1.2), né come una notifica "per tutti" diventa letta per un utente e non per
gli altri. Per la ricerca globale (mockup 009) dice cosa trovare, ma i dati (clienti, articoli, documenti) arrivano
con le milestone successive.
## Decisione
1. **La wiki viaggia con il programma.** La compilazione copia `docs/wiki/*.md` in `help/wiki/` accanto al
programma, e in `help/media/` le immagini che le pagine mostrano (miniature e PNG dei mockup, icone, `img/` della
wiki), con lo stesso percorso che hanno nel repository. `.dockerignore` lascia entrare solo quelle cartelle di
`docs/`. Nessun download all'avvio, nessuna scrittura: la copia è di sola lettura e corrisponde alla versione.
2. **Markdown in casa.** `WikiMarkdown` converte il sottoinsieme che la wiki usa: titoli con ancora, paragrafi,
elenchi annidati, tabelle, citazioni, blocchi di codice, linee, immagini, collegamenti, grassetto, corsivo,
codice. Tutto il testo è codificato (niente HTML grezzo); diventano collegamenti solo indirizzi `http(s)`,
ancore `#` e nomi di pagina. La citazione `> **Stato:** …` in testa a ogni pagina è lo stato della pagina e si
mostra come tale, riga per riga; le altre citazioni sono riquadri informativi.
3. **Indirizzi.** L'aiuto è la pagina Blazor `/aiuto/{Pagina}` (nelle schede come ogni altra maschera); le immagini
sono servite da `/aiuto/media/{percorso}` solo se il percorso è fra quelli copiati e ha un'estensione d'immagine.
L'indirizzo `/help` della specifica resta come rinvio a `/aiuto`. Le immagini che puntano ai file del repository
(`…/raw/branch/main/<percorso>`) si servono dalla copia locale; le altre restano sul web.
4. **Una pagina per ogni maschera.** `HelpLinks` associa a ogni prefisso di percorso una pagina wiki; un test
controlla che ogni pagina dell'applicazione e ogni voce di menu porti a una pagina che esiste, e che tutti i
collegamenti fra pagine della wiki trovino la loro pagina.
5. **Wiki online configurabile.** `KHAEMHAT_HELP_URL` (facoltativa, indirizzo assoluto `http(s)`) è la wiki aperta da
*Apri nel wiki*; predefinita la wiki del progetto. *Segnala un problema* apre `…/issues/new` del repository della
wiki quando l'indirizzo finisce con `/wiki/` (Gitea e GitHub), altrimenti non compare.
6. **Notifiche lette per utente.** Una notifica personale (con destinatario) usa la sua colonna `read_at`. Una
notifica per tutti resta una riga sola; chi la legge aggiunge una riga in `sys_notification_reads` (notifiche di
sistema) o `notification_reads` (notifiche dell'azienda), con vincolo unico su notifica e utente. Il pannello
mostra le ultime 100 notifiche dell'utente, filtri *Tutte* e *Non lette*, *Segna tutte come lette*; la campanella
aggiorna il conteggio ogni minuto.
7. **Ricerca a fornitori.** Pagine del menu e comandi si cercano subito nel browser. I record arrivano da
`ISearchProvider` registrati nel contenitore e interrogati in parallelo da `GlobalSearchService` dopo una pausa di
200 ms e almeno 2 caratteri: ognuno dichiara gli ambiti (tutto, `#` documenti, `@` persone), dà al massimo 8
risultati, e uno lento (oltre 3 secondi) o in errore si scrive nel log e si salta. In M3 c'è il fornitore delle
pagine dell'aiuto (titoli e sezioni); `#` e `@` dicono con quali moduli arriveranno i risultati.
## Conseguenze
- L'aiuto funziona senza Internet ed è sempre quello della versione installata; l'immagine cresce delle sole pagine
e immagini citate (qualche MB).
- Il convertitore copre solo la sintassi usata dalla wiki: una pagina nuova con sintassi diversa si vede come testo,
e il test di conversione di tutte le pagine la segnala.
- I moduli successivi aggiungono i propri fornitori di ricerca e le proprie sorgenti di notifiche senza toccare la
shell.
+1
View File
@@ -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 |
+19 -10
View File
@@ -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
@@ -65,6 +65,7 @@ public sealed class EnvironmentConfigurationReader
SeedDemo = Get("KHAEMHAT_SEED_DEMO"),
UpdateFeed = Get("KHAEMHAT_UPDATE_FEED"),
UpdateToken = Get("KHAEMHAT_UPDATE_TOKEN"),
HelpUrl = Get("KHAEMHAT_HELP_URL"),
TimeZone = Get("TZ"),
ReadErrors = errors,
};
@@ -150,6 +150,12 @@ public sealed class KhaemhatOptions
/// <summary><c>KHAEMHAT_UPDATE_TOKEN</c>: a read-only token for the feed.</summary>
public string? UpdateToken { get; init; }
/// <summary>
/// <c>KHAEMHAT_HELP_URL</c>: the online wiki opened by "Apri nel wiki" (default the project wiki). The help itself
/// is the copy of the wiki shipped in the image, so it works offline.
/// </summary>
public string? HelpUrl { get; init; }
/// <summary><c>TZ</c>: the time zone of the container.</summary>
public string? TimeZone { get; init; }
@@ -265,6 +271,11 @@ public sealed class KhaemhatOptions
errors.Add("KHAEMHAT_PUBLIC_URL must be an absolute http or https address, for example https://gestionale.example.com.");
}
if (HelpUrl is not null && !IsHttpUrl(HelpUrl))
{
errors.Add("KHAEMHAT_HELP_URL must be an absolute http or https address, for example https://gitea.example.com/owner/khaemhat/wiki/.");
}
if (SmtpPort is not null && !(int.TryParse(SmtpPort, NumberStyles.None, CultureInfo.InvariantCulture, out var port) && port is > 0 and < 65536))
{
errors.Add("KHAEMHAT_SMTP_PORT must be a port number between 1 and 65535.");
@@ -90,12 +90,7 @@ public sealed class NotificationTodoSource(NotificationDispatcher notifications)
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),
_ => [],
};
var unread = await notifications.InboxAsync(context.Actor, unreadOnly: true, cancellationToken).ConfigureAwait(false);
return [.. unread
.Where(n => n.Severity >= NotificationSeverity.Warning)
@@ -1,3 +1,4 @@
using Khaemhat.Application.Security;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
@@ -13,14 +14,27 @@ namespace Khaemhat.Application.Notifications;
/// <param name="Link">A link inside the application.</param>
public sealed record NotificationMessage(string Category, NotificationSeverity Severity, string Title, string? Body = null, string? Link = null);
/// <summary>A notification as its recipient sees it.</summary>
/// <param name="Id">The id.</param>
/// <param name="Category">The area.</param>
/// <param name="Severity">The weight.</param>
/// <param name="Title">The title.</param>
/// <param name="Body">The text.</param>
/// <param name="Link">A link inside the application.</param>
/// <param name="CreatedAt">When it was sent (UTC).</param>
/// <param name="Read">Whether this user read it.</param>
/// <param name="Personal">Addressed to this user only, not to everyone.</param>
public sealed record InboxItem(long Id, string Category, NotificationSeverity Severity, string Title, string? Body, string? Link, DateTime CreatedAt, bool Read, bool Personal);
/// <summary>
/// Delivers in-app notifications (SPEC §9; mockup 010): to instance accounts in <c>sys_notifications</c>, to company
/// users in the company's <c>notifications</c>. A notification without recipient goes to everyone in the scope.
/// Delivery never breaks the caller: a failure is logged.
/// </summary>
/// <param name="factory">Opens the databases.</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log.</param>
public sealed class NotificationDispatcher(IUnitOfWorkFactory factory, ILogger<NotificationDispatcher> logger)
public sealed class NotificationDispatcher(IUnitOfWorkFactory factory, TimeProvider clock, ILogger<NotificationDispatcher> logger)
{
/// <summary>Notifies instance accounts.</summary>
/// <param name="message">The notification.</param>
@@ -61,29 +75,114 @@ public sealed class NotificationDispatcher(IUnitOfWorkFactory factory, ILogger<N
}
}
/// <summary>The unread notifications of an instance account (its own and those for everyone).</summary>
/// <param name="userId">The account.</param>
/// <summary>The most notifications a user sees: the newest ones.</summary>
public const int InboxSize = 100;
/// <summary>The notifications of a user, newest first (mockup 010).</summary>
/// <param name="actor">The user: instance accounts read the system ones, company users those of their company.</param>
/// <param name="unreadOnly">Only those not read yet.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The notifications, newest first.</returns>
public async Task<IReadOnlyList<SystemNotification>> UnreadForInstanceAsync(long userId, CancellationToken cancellationToken = default)
/// <returns>The notifications, at most <see cref="InboxSize"/>.</returns>
public Task<IReadOnlyList<InboxItem>> InboxAsync(Actor actor, bool unreadOnly = false, CancellationToken cancellationToken = default) =>
ScopeOf(actor) switch
{
({ } scope, { } user, true) => InboxAsync<SystemNotification, SystemNotificationRead>(scope, user, unreadOnly, cancellationToken),
({ } scope, { } user, false) => InboxAsync<Notification, NotificationRead>(scope, user, unreadOnly, cancellationToken),
_ => Task.FromResult<IReadOnlyList<InboxItem>>([]),
};
/// <summary>Marks a notification as read by the user. A notification for everyone stays unread for the others.</summary>
/// <param name="actor">The user.</param>
/// <param name="notificationId">The notification.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task MarkReadAsync(Actor actor, long notificationId, CancellationToken cancellationToken = default) =>
MarkAsync(actor, [notificationId], cancellationToken);
/// <summary>Marks every notification of the user as read.</summary>
/// <param name="actor">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task MarkAllReadAsync(Actor actor, CancellationToken cancellationToken = default)
{
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
return (await unitOfWork.Repository<SystemNotification, long>().ListAsync(
Query.For<SystemNotification>().Where(n => n.ReadAt == null && (n.RecipientUserId == null || n.RecipientUserId == userId)).OrderByDescending(n => n.Id).Take(100),
cancellationToken).ConfigureAwait(false)).Items;
var unread = await InboxAsync(actor, unreadOnly: true, cancellationToken).ConfigureAwait(false);
await MarkAsync(actor, [.. unread.Select(n => n.Id)], cancellationToken).ConfigureAwait(false);
}
/// <summary>The unread notifications of a company user.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="userId">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The notifications, newest first.</returns>
public async Task<IReadOnlyList<Notification>> UnreadForUserAsync(string companyCode, long userId, CancellationToken cancellationToken = default)
private Task MarkAsync(Actor actor, IReadOnlyList<long> ids, CancellationToken cancellationToken) =>
ids.Count == 0
? Task.CompletedTask
: ScopeOf(actor) switch
{
({ } scope, { } user, true) => MarkAsync<SystemNotification, SystemNotificationRead>(scope, user, ids, cancellationToken),
({ } scope, { } user, false) => MarkAsync<Notification, NotificationRead>(scope, user, ids, cancellationToken),
_ => Task.CompletedTask,
};
private static (DatabaseScope? Scope, long? User, bool System) ScopeOf(Actor actor)
{
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
return (await unitOfWork.Repository<Notification, long>().ListAsync(
Query.For<Notification>().Where(n => n.ReadAt == null && (n.RecipientUserId == null || n.RecipientUserId == userId)).OrderByDescending(n => n.Id).Take(100),
ArgumentNullException.ThrowIfNull(actor);
return actor switch
{
{ SystemUserId: { } id } => (DatabaseScope.System, id, true),
{ CompanyUserId: { } id, CompanyCode: { } company } => (DatabaseScope.Company(company), id, false),
_ => (null, null, false),
};
}
private async Task<IReadOnlyList<InboxItem>> InboxAsync<TNotification, TRead>(DatabaseScope scope, long userId, bool unreadOnly, CancellationToken cancellationToken)
where TNotification : NotificationRecord, new()
where TRead : NotificationReadRecord, new()
{
await using var unitOfWork = await factory.CreateAsync(scope, cancellationToken).ConfigureAwait(false);
var notifications = (await unitOfWork.Repository<TNotification, long>().ListAsync(
Query.For<TNotification>().Where(n => n.RecipientUserId == null || n.RecipientUserId == userId).OrderByDescending(n => n.Id).Take(InboxSize),
cancellationToken).ConfigureAwait(false)).Items;
var everyone = notifications.Where(n => n.RecipientUserId == null).Select(n => n.Id).ToList();
var read = everyone.Count == 0
? []
: (await unitOfWork.Repository<TRead, long>().ListAsync(
Query.For<TRead>().Where(r => r.UserId == userId && everyone.Contains(r.NotificationId)), cancellationToken).ConfigureAwait(false)).Items
.Select(r => r.NotificationId).ToHashSet();
return [.. notifications
.Select(n => new InboxItem(n.Id, n.Category, n.Severity, n.Title, n.Body, n.Link, n.CreatedAt,
n.RecipientUserId is null ? read.Contains(n.Id) : n.ReadAt is not null, n.RecipientUserId is not null))
.Where(n => !unreadOnly || !n.Read)];
}
private async Task MarkAsync<TNotification, TRead>(DatabaseScope scope, long userId, IReadOnlyList<long> ids, CancellationToken cancellationToken)
where TNotification : NotificationRecord, new()
where TRead : NotificationReadRecord, new()
{
await using var unitOfWork = await factory.CreateAsync(scope, cancellationToken).ConfigureAwait(false);
var list = ids.ToList();
var repository = unitOfWork.Repository<TNotification, long>();
var notifications = (await repository.ListAsync(
Query.For<TNotification>().Where(n => list.Contains(n.Id) && (n.RecipientUserId == null || n.RecipientUserId == userId)), cancellationToken).ConfigureAwait(false)).Items;
var reads = unitOfWork.Repository<TRead, long>();
var already = (await reads.ListAsync(Query.For<TRead>().Where(r => r.UserId == userId && list.Contains(r.NotificationId)), cancellationToken).ConfigureAwait(false)).Items
.Select(r => r.NotificationId).ToHashSet();
var now = clock.GetUtcNow().UtcDateTime;
await unitOfWork.InTransactionAsync(
async ct =>
{
foreach (var notification in notifications)
{
if (notification.RecipientUserId is null)
{
if (already.Add(notification.Id))
{
await reads.InsertAsync(new TRead { NotificationId = notification.Id, UserId = userId }, ct).ConfigureAwait(false);
}
}
else if (notification.ReadAt is null)
{
notification.ReadAt = now;
await repository.UpdateAsync(notification, ct).ConfigureAwait(false);
}
}
},
cancellationToken).ConfigureAwait(false);
}
private static T Fill<T>(T notification, NotificationMessage message, long? recipient)
@@ -0,0 +1,133 @@
using Khaemhat.Application.Security;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Application.Search;
/// <summary>What the search looks for, from the first character of the query (SPEC §10.2, mockup 009).</summary>
public enum SearchScope
{
/// <summary>Everything: pages, records, help.</summary>
All,
/// <summary><c>&gt;</c>: only the commands.</summary>
Commands,
/// <summary><c>#</c>: only the documents.</summary>
Documents,
/// <summary><c>@</c>: only the people.</summary>
People,
}
/// <summary>A search, split into scope and words.</summary>
/// <param name="Scope">What it looks for.</param>
/// <param name="Text">The words, without the prefix.</param>
public sealed record SearchQuery(SearchScope Scope, string Text)
{
/// <summary>The fewest characters before records are searched.</summary>
public const int MinimumLength = 2;
/// <summary>The words of the query.</summary>
public IReadOnlyList<string> Words { get; } = Text.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
/// <summary>Reads what the user typed.</summary>
/// <param name="input">The text of the search box.</param>
/// <returns>The query.</returns>
public static SearchQuery Parse(string? input)
{
var text = (input ?? string.Empty).Trim();
var scope = text.Length == 0 ? SearchScope.All : text[0] switch
{
'>' => SearchScope.Commands,
'#' => SearchScope.Documents,
'@' => SearchScope.People,
_ => SearchScope.All,
};
return new SearchQuery(scope, scope == SearchScope.All ? text : text[1..].Trim());
}
/// <summary>Whether a text contains every word, ignoring case.</summary>
/// <param name="value">The text.</param>
/// <returns><see langword="true"/> if it does; always for an empty query.</returns>
public bool Matches(string? value) =>
Words.Count == 0 || (value is not null && Words.All(w => value.Contains(w, StringComparison.CurrentCultureIgnoreCase)));
}
/// <summary>A search result.</summary>
/// <param name="Group">The text key of the group shown above it, such as <c>Shell.Search.Help</c>.</param>
/// <param name="Icon">The icon.</param>
/// <param name="Title">The title.</param>
/// <param name="Detail">A second line, such as the page a heading belongs to.</param>
/// <param name="Href">Where it opens, relative to the application.</param>
public sealed record SearchHit(string Group, string Icon, string Title, string? Detail, string Href);
/// <summary>A source of search results: each module adds its own (parties, items, documents, accounts...).</summary>
public interface ISearchProvider
{
/// <summary>The scopes it answers: <see cref="SearchScope.All"/> and, for example, <see cref="SearchScope.Documents"/>.</summary>
IReadOnlyCollection<SearchScope> Scopes { get; }
/// <summary>Searches.</summary>
/// <param name="actor">Who searches: results respect permissions and company.</param>
/// <param name="query">The query, at least <see cref="SearchQuery.MinimumLength"/> characters.</param>
/// <param name="cancellationToken">Cancellation: the user typed something else.</param>
/// <returns>At most <see cref="GlobalSearchService.PerProvider"/> results, best first.</returns>
Task<IReadOnlyList<SearchHit>> SearchAsync(Actor actor, SearchQuery query, CancellationToken cancellationToken);
}
/// <summary>
/// The records part of the global search (SPEC §10.2): asks every provider of the scope, in parallel, and puts the
/// results together. A provider that fails or is slow is left out, the others are shown.
/// </summary>
public sealed class GlobalSearchService(IEnumerable<ISearchProvider> providers, ILogger<GlobalSearchService> logger)
{
/// <summary>The most results of one provider.</summary>
public const int PerProvider = 8;
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(3);
private readonly ISearchProvider[] _providers = [.. providers];
/// <summary>Whether something answers a scope: without, the search says what it will find in a later version.</summary>
/// <param name="scope">The scope.</param>
/// <returns><see langword="true"/> if a provider does.</returns>
public bool Covers(SearchScope scope) => _providers.Any(p => p.Scopes.Contains(scope));
/// <summary>Searches the records.</summary>
/// <param name="actor">Who searches.</param>
/// <param name="query">The query.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The results, grouped by provider in registration order.</returns>
public async Task<IReadOnlyList<SearchHit>> SearchAsync(Actor actor, SearchQuery query, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(query);
if (query.Scope == SearchScope.Commands || query.Text.Length < SearchQuery.MinimumLength)
{
return [];
}
var results = await Task.WhenAll(_providers.Where(p => p.Scopes.Contains(query.Scope)).Select(p => AskAsync(p, actor, query, cancellationToken))).ConfigureAwait(false);
return [.. results.SelectMany(r => r)];
}
private async Task<IReadOnlyList<SearchHit>> AskAsync(ISearchProvider provider, Actor actor, SearchQuery query, CancellationToken cancellationToken)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(Timeout);
try
{
return [.. (await provider.SearchAsync(actor, query, timeout.Token).ConfigureAwait(false)).Take(PerProvider)];
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
logger.LogWarning("Search provider {Provider} took longer than {Timeout} and was left out", provider.GetType().Name, Timeout);
return [];
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
logger.LogError(ex, "Search provider {Provider} failed", provider.GetType().Name);
return [];
}
}
}
@@ -347,3 +347,23 @@ public sealed class SystemNotification : NotificationRecord;
/// <summary>A notification for company users (<c>notifications</c>).</summary>
public sealed class Notification : NotificationRecord;
/// <summary>
/// That a user read a notification addressed to everyone: each user reads it for themselves (<c>notification_reads</c>,
/// <c>sys_notification_reads</c>). A notification for one user keeps its own <see cref="NotificationRecord.ReadAt"/>.
/// The audit column <c>created_at</c> is when it was read.
/// </summary>
public abstract class NotificationReadRecord : Entity<long>
{
/// <summary>The notification.</summary>
public long NotificationId { get; set; }
/// <summary>The user who read it.</summary>
public long UserId { get; set; }
}
/// <summary>An instance account read a notification for everyone (<c>sys_notification_reads</c>).</summary>
public sealed class SystemNotificationRead : NotificationReadRecord;
/// <summary>A company user read a notification for everyone (<c>notification_reads</c>).</summary>
public sealed class NotificationRead : NotificationReadRecord;
@@ -97,6 +97,13 @@ public sealed class NotificationMap : EntityMap<Notification>
}
}
/// <summary>Map of <see cref="NotificationRead"/> to <c>notification_reads</c>.</summary>
public sealed class NotificationReadMap : EntityMap<NotificationRead>
{
/// <summary>Creates the map.</summary>
public NotificationReadMap() => ToTable("notification_reads");
}
/// <summary>Map of <see cref="UserSetting"/> to <c>user_settings</c>.</summary>
public sealed class UserSettingMap : EntityMap<UserSetting>
{
@@ -0,0 +1,24 @@
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.CompanyDatabase.Migrations;
/// <summary>Who read a notification addressed to everyone (SPEC §9, mockup 010): each user marks it for themselves.</summary>
[Migration(20261111_009, "create_notification_reads")]
public sealed class M20261111_009_CreateNotificationReads : IMigration
{
/// <inheritdoc />
public void Up(ISchemaBuilder schema)
{
ArgumentNullException.ThrowIfNull(schema);
schema.CreateTable("notification_reads", t =>
{
t.Id();
t.Int64("notification_id").NotNull();
t.Int64("user_id").NotNull();
t.AuditColumns();
t.Unique("ux_notification_reads_notification_user", "notification_id", "user_id");
t.Index("ix_notification_reads_user_id", "user_id");
});
}
}
@@ -0,0 +1,24 @@
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.SystemDatabase.Migrations;
/// <summary>Who read a notification addressed to everyone (SPEC §9, mockup 010): each user marks it for themselves.</summary>
[Migration(20261111_013, "create_sys_notification_reads", Target = MigrationTarget.System)]
public sealed class M20261111_013_CreateSysNotificationReads : IMigration
{
/// <inheritdoc />
public void Up(ISchemaBuilder schema)
{
ArgumentNullException.ThrowIfNull(schema);
schema.CreateTable("sys_notification_reads", t =>
{
t.Id();
t.Int64("notification_id").NotNull();
t.Int64("user_id").NotNull();
t.AuditColumns();
t.Unique("ux_sys_notification_reads_notification_user", "notification_id", "user_id");
t.Index("ix_sys_notification_reads_user_id", "user_id");
});
}
}
@@ -197,6 +197,13 @@ public sealed class SystemNotificationMap : EntityMap<SystemNotification>
}
}
/// <summary>Map of <see cref="SystemNotificationRead"/> to <c>sys_notification_reads</c>.</summary>
public sealed class SystemNotificationReadMap : EntityMap<SystemNotificationRead>
{
/// <summary>Creates the map.</summary>
public SystemNotificationReadMap() => ToTable("sys_notification_reads");
}
/// <summary>The notification columns shared by <c>sys_notifications</c> and <c>notifications</c>.</summary>
internal static class NotificationColumns
{
@@ -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)
@@ -48,7 +48,7 @@ else
}
<div class="kh-actions">
<a class="btn" href="./">@T["Common.BackHome"]</a>
<a class="btn ghost" href="@(HelpLinks.DefaultBaseUrl + "Roadmap")" target="_blank" rel="noopener">@T["Pages.ComingSoon.Roadmap"]</a>
<a class="btn ghost" href="@Khaemhat.Web.Help.WikiLibrary.Href("Roadmap")">@T["Pages.ComingSoon.Roadmap"]</a>
</div>
</div>
}
@@ -0,0 +1,73 @@
@page "/aiuto"
@page "/aiuto/{Name}"
@attribute [Authorize]
@using Khaemhat.Application.Configuration
@using Khaemhat.Web.Help
@inject WikiLibrary Wiki
@inject KhaemhatOptions Options
@* The help of SPEC §17 (mockup 011): the wiki page of the screen, from the copy shipped with the application, with
the wiki index at the side, "Apri nel wiki" for the online version and "Segnala un problema". F1 and the "?" of the
top bar open it on the page of the current screen. *@
<KhPageTitle Text="@T.Format("Pages.Help.TabTitle", Current?.Title ?? T["Pages.Help.Title"])" Icon="help" />
<div class="phead">
<div>
<div class="crumbs">@T["Pages.Help.Crumb"]@if (Section is { } section){<text> › @section.Title</text>} › <b>@(Current?.Title ?? Name)</b></div>
<h1>@T.Format("Pages.Help.Heading", Current?.Title ?? T["Pages.Help.Title"])</h1>
</div>
<div class="grow"></div>
<a class="btn" href="@OnlineUrl" target="_blank" rel="noopener"><KhIcon Name="external" /> @T["Pages.Help.OpenWiki"]</a>
@if (IssuesUrl is { } issues)
{
<a class="btn" href="@issues" target="_blank" rel="noopener"><KhIcon Name="alert" /> @T["Pages.Help.Report"]</a>
}
</div>
<div class="kh-help">
<nav class="panel kh-help-index" aria-label="@T["Pages.Help.Index"]">
@foreach (var group in Wiki.Sidebar)
{
<div class="kh-help-group">@group.Title</div>
@foreach (var (page, label) in group.Pages)
{
<a class="kh-help-link @(string.Equals(page, PageName, StringComparison.OrdinalIgnoreCase) ? "on" : null)" href="@WikiLibrary.Href(page)"
aria-current="@(string.Equals(page, PageName, StringComparison.OrdinalIgnoreCase) ? "page" : null)">
<KhIcon Name="file" Class="sm" /> @label
</a>
}
}
</nav>
<article class="panel kh-help-body">
@if (!Wiki.IsAvailable)
{
<div class="callout warn"><KhIcon Name="alert" /> <span>@T["Pages.Help.Missing"]</span></div>
}
else if (Current is null)
{
<div class="callout warn"><KhIcon Name="alert" /> <span>@T.Format("Pages.Help.NotFound", Name ?? string.Empty)</span></div>
}
else
{
@((MarkupString)Current.Html)
}
</article>
</div>
@code {
/// <summary>The wiki page, such as <c>Interfaccia-e-scorciatoie</c>; empty for the wiki home.</summary>
[Parameter]
public string? Name { get; set; }
private string PageName => string.IsNullOrWhiteSpace(Name) ? "Home" : Name;
private WikiPage? Current => Wiki.Get(PageName);
private WikiSection? Section => Wiki.Sidebar.FirstOrDefault(s => s.Pages.Any(p => string.Equals(p.Page, PageName, StringComparison.OrdinalIgnoreCase)));
private string BaseUrl => HelpLinks.BaseUrl(Options.HelpUrl);
private string OnlineUrl => BaseUrl + (Current?.Name ?? PageName);
private string? IssuesUrl => HelpLinks.IssuesUrl(BaseUrl);
}
@@ -1,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)
{
<div class="overlay" @onclick="CloseAsync">
@@ -17,7 +21,11 @@
<span class="kbdhint"><kbd>@T["Shell.Keys.Escape"]</kbd></span>
</div>
<div id="kh-palette-hits" role="listbox" class="hits">
@if (Hits.Count == 0)
@if (Soon is { } soon)
{
<div class="grp">@T[soon]</div>
}
else if (Hits.Count == 0 && !_searching)
{
<div class="grp">@T["Shell.Search.NoResults"]</div>
}
@@ -38,6 +46,10 @@
@onclick="() => RunAsync(hit)" @onmouseover="() => _selected = i">
<KhIcon Name="@hit.Icon" />
<span>@hit.Title</span>
@if (hit.Detail is not null)
{
<span class="d">@hit.Detail</span>
}
@if (hit.Hint is not null)
{
<span class="k">@hit.Hint</span>
@@ -49,18 +61,24 @@
<span class="kbdhint"><kbd>↑</kbd><kbd>↓</kbd> @T["Shell.Search.Move"]</span>
<span class="kbdhint"><kbd>↵</kbd> @T["Shell.Search.Open"]</span>
<span class="kbdhint"><kbd>&gt;</kbd> @T["Shell.Search.Commands"]</span>
<span class="kbdhint"><kbd>#</kbd> @T["Shell.Search.Documents"]</span>
<span class="kbdhint"><kbd>@@</kbd> @T["Shell.Search.People"]</span>
</div>
</div>
</div>
}
@code {
private sealed record Hit(string Group, string Icon, string Title, string? Hint, Func<Task> Run);
private sealed record Hit(string Group, string Icon, string Title, string? Hint, Func<Task> 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;
/// <summary>Whether the search is open.</summary>
[Parameter]
@@ -76,6 +94,14 @@
private List<Hit> 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,
};
/// <inheritdoc />
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;
}
/// <inheritdoc />
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<Hit> Search(string query)
private List<Hit> 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<Hit>();
if (!commandsOnly)
if (query.Scope == SearchScope.All)
{
foreach (var item in MenuCatalog.All.Where(Session.CanSee))
{
@@ -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. *@
<KhDrawer Open="Open" Title="@T["Shell.Notifications.Title"]" Icon="bell" OnClose="CloseAsync">
<ChildContent>
<div class="kh-seg kh-notif-filter" role="group" aria-label="@T["Shell.Notifications.Filter"]">
<button type="button" class="@(_unreadOnly ? null : "on")" aria-pressed="@(_unreadOnly ? "false" : "true")" @onclick="() => _unreadOnly = false">
@T.Format("Shell.Notifications.All", _items.Count)
</button>
<button type="button" class="@(_unreadOnly ? "on" : null)" aria-pressed="@(_unreadOnly ? "true" : "false")" @onclick="() => _unreadOnly = true">
@T.Format("Shell.Notifications.Unread", Unread)
</button>
</div>
@if (!_loaded)
{
<p class="muted">@T["Common.Loading"]</p>
}
else if (!Shown.Any())
{
<p class="kh-wempty"><KhIcon Name="check-circle" /> @T[_unreadOnly ? "Shell.Notifications.NoneUnread" : "Shell.Notifications.None"]</p>
}
else
{
<ul class="kh-notifs">
@foreach (var item in Shown)
{
<li class="kh-notif @(item.Read ? null : "unread")" @key="item.Id">
<span class="ico-box @ToneOf(item.Severity)" aria-hidden="true"><KhIcon Name="@IconOf(item.Severity)" /></span>
<button type="button" class="kh-notif-main" @onclick="() => OpenAsync(item)">
<span class="t">@item.Title</span>
@if (item.Body is not null)
{
<span class="s">@item.Body</span>
}
<span class="m">
<span class="badge gray">@CategoryOf(item.Category)</span>
<span>@When(item.CreatedAt)</span>
</span>
</button>
@if (!item.Read)
{
<button type="button" class="ib" title="@T["Shell.Notifications.MarkRead"]" aria-label="@T.Format("Shell.Notifications.MarkReadOf", item.Title)"
@onclick="() => MarkReadAsync(item)"><KhIcon Name="check" /></button>
}
</li>
}
</ul>
}
</ChildContent>
<Footer>
<button type="button" class="btn" disabled="@(Unread == 0)" @onclick="MarkAllAsync"><KhIcon Name="check" /> @T["Shell.Notifications.MarkAll"]</button>
</Footer>
</KhDrawer>
@code {
private IReadOnlyList<InboxItem> _items = [];
private bool _unreadOnly;
private bool _loaded;
private bool _wasOpen;
/// <summary>Whether the panel is shown.</summary>
[Parameter]
public bool Open { get; set; }
/// <summary>Opens or closes it.</summary>
[Parameter]
public EventCallback<bool> OpenChanged { get; set; }
/// <summary>Told the unread count after every change.</summary>
[Parameter]
public EventCallback<int> UnreadChanged { get; set; }
private int Unread => _items.Count(i => !i.Read);
private IEnumerable<InboxItem> Shown => _unreadOnly ? _items.Where(i => !i.Read) : _items;
/// <inheritdoc />
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,
};
}
+40 -49
View File
@@ -54,34 +54,15 @@
}
</div>
<div class="pop">
<button type="button" class="tbtn" aria-haspopup="menu" aria-expanded="@(_open == Popup.Notifications)"
aria-label="@T.Format("Shell.TopBar.NotificationsCount", _unread.Count)" @onclick="ToggleNotificationsAsync">
<KhIcon Name="bell" />
@if (_unread.Count > 0)
{
<span class="dot"></span>
}
<span class="tip">@T["Shell.TopBar.Notifications"]</span>
</button>
@if (_open == Popup.Notifications)
<button type="button" class="tbtn" aria-haspopup="dialog" aria-expanded="@(_notifications ? "true" : "false")"
aria-label="@T.Format("Shell.TopBar.NotificationsCount", _unread)" @onclick="ToggleNotifications">
<KhIcon Name="bell" />
@if (_unread > 0)
{
<div class="popmenu notif" role="menu">
<div class="fh">@T["Shell.TopBar.Notifications"]</div>
@if (_unread.Count == 0)
{
<div class="mi muted">@T["Shell.TopBar.NoNotifications"]</div>
}
@foreach (var n in _unread)
{
<a class="mi" role="menuitem" href="@(n.Link is { } link && UserPreferences.IsLocalPath(link) ? link.TrimStart('/') : "#")" @onclick="Close">
<KhIcon Name="@SeverityIcon(n.Severity)" />
<span class="grow"><b>@n.Title</b>@if (n.Body is not null) {<br /><span class="muted small">@n.Body</span>}</span>
</a>
}
</div>
<span class="dot"></span>
}
</div>
<span class="tip">@T["Shell.TopBar.Notifications"]</span>
</button>
<button type="button" class="tbtn" aria-label="@ThemeLabel" @onclick="Theme.ToggleDarkAsync">
<KhIcon Name="@(Session.Preferences.Theme == ThemeMode.Dark ? "sun" : "moon")" /><span class="tip">@ThemeLabel</span>
@@ -98,18 +79,20 @@
{
<div class="scrim" @onclick="Close"></div>
}
<NotificationPanel Open="_notifications" OpenChanged="open => _notifications = open" UnreadChanged="count => _unread = count" />
@code {
private enum Popup
{
Company,
Recent,
Notifications,
User,
}
private Popup? _open;
private IReadOnlyList<(string Title, string? Body, string? Link, Khaemhat.Core.Instance.NotificationSeverity Severity)> _unread = [];
private readonly CancellationTokenSource _stop = new();
private int _unread;
private bool _notifications;
/// <summary>Opens the global search.</summary>
[Parameter]
@@ -126,7 +109,8 @@
{
Session.Changed += OnChanged;
Tabs.Changed += OnChanged;
await LoadNotificationsAsync();
await CountUnreadAsync();
_ = RefreshAsync(_stop.Token);
}
/// <inheritdoc />
@@ -134,6 +118,8 @@
{
Session.Changed -= OnChanged;
Tabs.Changed -= OnChanged;
_stop.Cancel();
_stop.Dispose();
}
private void OnChanged() => _ = InvokeAsync(StateHasChanged);
@@ -142,39 +128,44 @@
private void Close() => _open = null;
private async Task ToggleNotificationsAsync()
private void ToggleNotifications()
{
Toggle(Popup.Notifications);
if (_open == Popup.Notifications)
_open = null;
_notifications = !_notifications;
}
private async Task CountUnreadAsync()
{
if (Session.Actor is { } actor)
{
await LoadNotificationsAsync();
_unread = (await Notifications.InboxAsync(actor, unreadOnly: true)).Count;
}
}
private async Task LoadNotificationsAsync()
// The bell lights up for notifications that arrive while the page is open: a look every minute.
private async Task RefreshAsync(CancellationToken cancellationToken)
{
if (Session.Actor is not { } actor)
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(1));
try
{
return;
while (await timer.WaitForNextTickAsync(cancellationToken))
{
await InvokeAsync(async () =>
{
await CountUnreadAsync();
StateHasChanged();
});
}
}
if (actor.SystemUserId is { } systemUser)
catch (OperationCanceledException)
{
_unread = [.. (await Notifications.UnreadForInstanceAsync(systemUser)).Select(n => (n.Title, n.Body, n.Link, n.Severity))];
// The page closed.
}
else if (actor is { CompanyCode: { } company, CompanyUserId: { } user })
catch (ObjectDisposedException)
{
_unread = [.. (await Notifications.UnreadForUserAsync(company, user)).Select(n => (n.Title, n.Body, n.Link, n.Severity))];
// The circuit went away.
}
}
private static string Relative(string url) => url.TrimStart('/');
private static string SeverityIcon(Khaemhat.Core.Instance.NotificationSeverity severity) => severity switch
{
Khaemhat.Core.Instance.NotificationSeverity.Error => "x-circle",
Khaemhat.Core.Instance.NotificationSeverity.Warning => "alert",
Khaemhat.Core.Instance.NotificationSeverity.Success => "check-circle",
_ => "info",
};
}
@@ -0,0 +1,27 @@
using Khaemhat.Application.Search;
using Khaemhat.Application.Security;
namespace Khaemhat.Web.Help;
/// <summary>The help pages in the global search: titles first, then the sections of the pages.</summary>
/// <param name="wiki">The wiki shipped with the application.</param>
public sealed class HelpSearchProvider(WikiLibrary wiki) : ISearchProvider
{
/// <summary>The group of the results.</summary>
public const string Group = "Shell.Search.Help";
/// <inheritdoc />
public IReadOnlyCollection<SearchScope> Scopes { get; } = [SearchScope.All];
/// <inheritdoc />
public Task<IReadOnlyList<SearchHit>> SearchAsync(Actor actor, SearchQuery query, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(query);
var pages = wiki.PageNames.Select(wiki.Get).OfType<WikiPage>().ToList();
var titles = pages.Where(p => query.Matches(p.Title))
.Select(p => new SearchHit(Group, "help", p.Title, null, WikiLibrary.Href(p.Name)));
var sections = pages.SelectMany(p => p.Headings.Where(query.Matches)
.Select(h => new SearchHit(Group, "help", h, p.Title, WikiLibrary.Href(p.Name) + "#" + WikiMarkdown.Slug(h))));
return Task.FromResult<IReadOnlyList<SearchHit>>([.. titles.Concat(sections).Take(GlobalSearchService.PerProvider)]);
}
}
+172
View File
@@ -0,0 +1,172 @@
using System.Collections.Concurrent;
using System.Text.RegularExpressions;
namespace Khaemhat.Web.Help;
/// <summary>A page of the help.</summary>
/// <param name="Name">The page name, as in the wiki (<c>Interfaccia-e-scorciatoie</c>).</param>
/// <param name="Title">The first heading.</param>
/// <param name="Html">The content as HTML.</param>
/// <param name="Headings">The second-level headings, for the search.</param>
public sealed record WikiPage(string Name, string Title, string Html, IReadOnlyList<string> Headings);
/// <summary>A group of the help index, from the wiki sidebar.</summary>
/// <param name="Title">The group title.</param>
/// <param name="Pages">The pages: name and label.</param>
public sealed record WikiSection(string Title, IReadOnlyList<(string Page, string Label)> Pages);
/// <summary>
/// The copy of the wiki shipped with the application (SPEC §17: help also for installations without Internet). The
/// build copies <c>docs/wiki/*.md</c> to <c>help/wiki/</c> and the images the pages show (mockups, icons) to
/// <c>help/media/</c> next to the program; pages are converted once and kept in memory.
/// </summary>
public sealed partial class WikiLibrary
{
/// <summary>The address of the help pages inside the application.</summary>
public const string BasePath = "/aiuto";
/// <summary>The address of the images of the help.</summary>
public const string MediaPath = BasePath + "/media";
private const string RawPrefix = "/raw/branch/main/";
private readonly string _wiki;
private readonly string _media;
private readonly Dictionary<string, string> _files;
private readonly ConcurrentDictionary<string, WikiPage> _pages = new(StringComparer.OrdinalIgnoreCase);
private readonly Lazy<IReadOnlyList<WikiSection>> _sidebar;
/// <summary>Reads the wiki next to the program.</summary>
public WikiLibrary()
: this(Path.Combine(AppContext.BaseDirectory, "help"))
{
}
/// <summary>Reads the wiki from a folder.</summary>
/// <param name="root">The folder with <c>wiki/</c> and <c>media/</c>.</param>
public WikiLibrary(string root)
{
_wiki = Path.Combine(root, "wiki");
_media = Path.GetFullPath(Path.Combine(root, "media"));
_files = Directory.Exists(_wiki)
? Directory.EnumerateFiles(_wiki, "*.md").ToDictionary(f => Path.GetFileNameWithoutExtension(f), f => f, StringComparer.OrdinalIgnoreCase)
: new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
_sidebar = new Lazy<IReadOnlyList<WikiSection>>(ReadSidebar);
}
/// <summary>Whether the copy of the wiki is there (it is missing only in a broken build).</summary>
public bool IsAvailable => _files.ContainsKey("Home");
/// <summary>The page names, without the special ones (<c>_Sidebar</c>, <c>_Footer</c>).</summary>
public IEnumerable<string> PageNames => _files.Keys.Where(k => !k.StartsWith('_')).Order(StringComparer.OrdinalIgnoreCase);
/// <summary>The index of the help, from the wiki sidebar.</summary>
public IReadOnlyList<WikiSection> Sidebar => _sidebar.Value;
/// <summary>The address of a help page inside the application.</summary>
/// <param name="page">The page name, optionally with <c>#anchor</c>.</param>
/// <returns>The address.</returns>
public static string Href(string page)
{
ArgumentNullException.ThrowIfNull(page);
return BasePath[1..] + "/" + page;
}
/// <summary>Whether a page exists.</summary>
/// <param name="page">The page name.</param>
/// <returns><see langword="true"/> if it does.</returns>
public bool Exists(string page) => _files.ContainsKey(page) && !page.StartsWith('_');
/// <summary>A page, converted to HTML.</summary>
/// <param name="page">The page name.</param>
/// <returns>The page, or <see langword="null"/> if it does not exist.</returns>
public WikiPage? Get(string page)
{
ArgumentNullException.ThrowIfNull(page);
if (!Exists(page))
{
return null;
}
return _pages.GetOrAdd(page, name =>
{
var file = _files[name];
var markdown = File.ReadAllText(file);
var lines = markdown.Split('\n');
var title = lines.Select(l => l.Trim()).FirstOrDefault(l => l.StartsWith("# ", StringComparison.Ordinal)) is { } h1
? WikiMarkdown.PlainText(h1[2..])
: name.Replace('-', ' ');
var headings = lines.Select(l => l.Trim()).Where(l => l.StartsWith("## ", StringComparison.Ordinal)).Select(l => WikiMarkdown.PlainText(l[3..])).ToList();
return new WikiPage(Path.GetFileNameWithoutExtension(file), title, WikiMarkdown.ToHtml(markdown, Links), headings);
});
}
/// <summary>The file of an image of the help, if it is one of the copied ones.</summary>
/// <param name="path">The path after <see cref="MediaPath"/>, such as <c>docs/mockups/thumbs/004-dashboard.png</c>.</param>
/// <returns>The full file name, or <see langword="null"/>.</returns>
public string? MediaFile(string path)
{
if (string.IsNullOrWhiteSpace(path) || !MediaName().IsMatch(path))
{
return null;
}
var full = Path.GetFullPath(Path.Combine(_media, path));
return full.StartsWith(_media + Path.DirectorySeparatorChar, StringComparison.Ordinal) && File.Exists(full) ? full : null;
}
private WikiLinks Links => new(Href, LocalMedia);
// Images point to the raw files of the repository (".../raw/branch/main/docs/mockups/thumbs/x.png") or to img/
// next to the pages; the copied ones are served from the application, the others stay on the web.
private string? LocalMedia(string url)
{
var raw = url.IndexOf(RawPrefix, StringComparison.Ordinal);
var path = raw >= 0 ? url[(raw + RawPrefix.Length)..] : url.StartsWith("img/", StringComparison.Ordinal) ? "docs/wiki/" + url : null;
return path is not null && MediaFile(path) is not null ? MediaPath[1..] + "/" + path : null;
}
private List<WikiSection> ReadSidebar()
{
var sections = new List<WikiSection>();
if (!_files.TryGetValue("_Sidebar", out var file))
{
return sections;
}
string? title = null;
var pages = new List<(string, string)>();
foreach (var raw in File.ReadAllLines(file))
{
var line = raw.Trim();
if (line.StartsWith("**", StringComparison.Ordinal) && !line.StartsWith("**[", StringComparison.Ordinal))
{
Flush();
title = WikiMarkdown.PlainText(line);
}
else if (SidebarLink().Match(line) is { Success: true } link && Exists(link.Groups[2].Value))
{
pages.Add((link.Groups[2].Value, link.Groups[1].Value));
}
}
Flush();
return sections;
void Flush()
{
if (title is not null && pages.Count > 0)
{
sections.Add(new WikiSection(title, [.. pages]));
}
pages.Clear();
}
}
[GeneratedRegex(@"^-\s*\[([^\]]+)\]\(([A-Za-z0-9-]+)\)")]
private static partial Regex SidebarLink();
[GeneratedRegex(@"^[A-Za-z0-9][A-Za-z0-9_\-/.]*\.(png|jpg|jpeg|svg|gif|webp)$", RegexOptions.IgnoreCase)]
private static partial Regex MediaName();
}
+465
View File
@@ -0,0 +1,465 @@
using System.Globalization;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
namespace Khaemhat.Web.Help;
/// <summary>Where the links and images of a wiki page point inside the application.</summary>
/// <param name="Page">The address of another wiki page (<c>Anagrafiche</c>, <c>Anagrafiche#clienti</c>).</param>
/// <param name="Media">The local address of an image, or <see langword="null"/> to keep the original one.</param>
public sealed record WikiLinks(Func<string, string> Page, Func<string, string?> Media);
/// <summary>
/// Turns the Markdown of <c>docs/wiki/</c> into HTML for the help (SPEC §17, mockup 011), written in house (no external
/// libraries, ADR 0002). It covers what the wiki uses: headings with anchors, paragraphs, bold, italic, code, links,
/// images, nested lists, tables, quotes, code blocks and rules. Every piece of text is encoded and only http, https,
/// anchors and wiki pages become links, so a page cannot inject markup or scripts.
/// </summary>
public static partial class WikiMarkdown
{
/// <summary>Converts a page.</summary>
/// <param name="markdown">The Markdown.</param>
/// <param name="links">Where links and images go.</param>
/// <returns>The HTML.</returns>
public static string ToHtml(string markdown, WikiLinks links)
{
ArgumentNullException.ThrowIfNull(markdown);
ArgumentNullException.ThrowIfNull(links);
var lines = markdown.Replace("\r\n", "\n", StringComparison.Ordinal).Replace('\r', '\n').Split('\n');
var html = new StringBuilder();
new Parser(lines, links, html).Blocks(0, lines.Length);
return html.ToString();
}
/// <summary>The anchor of a heading, as the wiki makes it: lower case, words joined by dashes.</summary>
/// <param name="text">The heading text (Markdown).</param>
/// <returns>The anchor.</returns>
public static string Slug(string text)
{
ArgumentNullException.ThrowIfNull(text);
var plain = PlainText(text).ToLower(CultureInfo.InvariantCulture);
var slug = new StringBuilder();
foreach (var c in plain)
{
if (char.IsLetterOrDigit(c) || c is '-' or '_')
{
slug.Append(c);
}
else if (c == ' ')
{
slug.Append('-');
}
}
return slug.ToString();
}
/// <summary>The text of a line of Markdown without its marks.</summary>
/// <param name="text">The Markdown.</param>
/// <returns>The text.</returns>
public static string PlainText(string text)
{
ArgumentNullException.ThrowIfNull(text);
var plain = LinkPattern().Replace(text, "$1");
return plain.Replace("**", string.Empty, StringComparison.Ordinal).Replace("`", string.Empty, StringComparison.Ordinal)
.Replace("*", string.Empty, StringComparison.Ordinal).Trim();
}
[GeneratedRegex(@"!?\[([^\]]*)\]\([^)]*\)")]
private static partial Regex LinkPattern();
[GeneratedRegex(@"^(\s*)([-*+]|\d+[.)])\s+(.*)$")]
private static partial Regex ListItemPattern();
[GeneratedRegex(@"^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)*\|?\s*$")]
private static partial Regex TableRulePattern();
[GeneratedRegex(@"^(#{1,6})\s+(.*?)\s*#*\s*$")]
private static partial Regex HeadingPattern();
[GeneratedRegex(@"^[A-Za-z0-9][A-Za-z0-9-]*(#[A-Za-z0-9_\-\p{L}]*)?$")]
private static partial Regex PagePattern();
private sealed class Parser(string[] lines, WikiLinks links, StringBuilder html)
{
public void Blocks(int start, int end)
{
var i = start;
while (i < end)
{
var line = lines[i];
var trimmed = line.Trim();
if (trimmed.Length == 0)
{
i++;
}
else if (trimmed.StartsWith("```", StringComparison.Ordinal))
{
i = Fence(i, end);
}
else if (HeadingPattern().Match(trimmed) is { Success: true } heading)
{
var level = heading.Groups[1].Length;
var text = heading.Groups[2].Value;
html.Append(CultureInfo.InvariantCulture, $"<h{level} id=\"{Attr(Slug(text))}\">").Append(Inline(text)).Append(CultureInfo.InvariantCulture, $"</h{level}>\n");
i++;
}
else if (trimmed is "---" or "***" or "___")
{
html.Append("<hr />\n");
i++;
}
else if (trimmed.StartsWith('>'))
{
i = Quote(i, end);
}
else if (trimmed.StartsWith('|') && i + 1 < end && TableRulePattern().IsMatch(lines[i + 1]))
{
i = Table(i, end);
}
else if (ListItemPattern().Match(line) is { Success: true } item)
{
i = List(i, end, item.Groups[1].Value.Length);
}
else
{
i = Paragraph(i, end);
}
}
}
private int Fence(int i, int end)
{
var body = new List<string>();
var j = i + 1;
while (j < end && !lines[j].Trim().StartsWith("```", StringComparison.Ordinal))
{
body.Add(lines[j]);
j++;
}
html.Append("<pre><code>").Append(Encode(string.Join('\n', body))).Append("</code></pre>\n");
return Math.Min(j + 1, end);
}
private int Quote(int i, int end)
{
var inner = new List<string>();
var j = i;
while (j < end && lines[j].TrimStart().StartsWith('>'))
{
var text = lines[j].TrimStart()[1..];
inner.Add(text.StartsWith(' ') ? text[1..] : text);
j++;
}
// "> **Stato:** bozza · ..." at the top of every page is the page state, not a note.
var meta = inner.Count > 0 && inner[0].StartsWith("**Stato:**", StringComparison.Ordinal);
html.Append(meta ? "<div class=\"kh-help-meta\">" : "<div class=\"callout info\"><div>");
// Each line of the page state is a fact of its own: keep them on separate lines.
var nested = new Parser(meta ? [.. inner.Select((l, n) => n < inner.Count - 1 ? l.TrimEnd() + " " : l)] : [.. inner], links, html);
nested.Blocks(0, inner.Count);
html.Append(meta ? "</div>\n" : "</div></div>\n");
return j;
}
private int Table(int i, int end)
{
var header = Cells(lines[i]);
html.Append("<div class=\"kh-help-table\"><table class=\"grid\"><thead><tr>");
foreach (var cell in header)
{
html.Append("<th>").Append(Inline(cell)).Append("</th>");
}
html.Append("</tr></thead><tbody>");
var j = i + 2;
while (j < end && lines[j].Trim().StartsWith('|'))
{
html.Append("<tr>");
var cells = Cells(lines[j]);
for (var c = 0; c < header.Count; c++)
{
html.Append("<td>").Append(c < cells.Count ? Inline(cells[c]) : string.Empty).Append("</td>");
}
html.Append("</tr>");
j++;
}
html.Append("</tbody></table></div>\n");
return j;
}
private static List<string> Cells(string line)
{
var text = line.Trim();
if (text.StartsWith('|'))
{
text = text[1..];
}
if (text.EndsWith('|') && !text.EndsWith("\\|", StringComparison.Ordinal))
{
text = text[..^1];
}
var cells = new List<string>();
var current = new StringBuilder();
var inCode = false;
for (var k = 0; k < text.Length; k++)
{
var c = text[k];
if (c == '\\' && k + 1 < text.Length && text[k + 1] == '|')
{
current.Append('|');
k++;
}
else if (c == '`')
{
inCode = !inCode;
current.Append(c);
}
else if (c == '|' && !inCode)
{
cells.Add(current.ToString().Trim());
current.Clear();
}
else
{
current.Append(c);
}
}
cells.Add(current.ToString().Trim());
return cells;
}
private int List(int i, int end, int indent)
{
var ordered = char.IsDigit(ListItemPattern().Match(lines[i]).Groups[2].Value[0]);
html.Append(ordered ? "<ol>" : "<ul>");
var j = i;
while (j < end)
{
var match = ListItemPattern().Match(lines[j]);
if (!match.Success || match.Groups[1].Value.Length != indent)
{
break;
}
var text = new StringBuilder(match.Groups[3].Value);
j++;
var nested = new StringBuilder();
while (j < end)
{
var line = lines[j];
var lead = line.Length - line.TrimStart().Length;
if (line.Trim().Length == 0)
{
// A blank line ends the item unless the list goes on after it.
var next = j + 1;
if (next < end && lines[next].Trim().Length > 0 && (lines[next].Length - lines[next].TrimStart().Length) > indent)
{
j++;
continue;
}
break;
}
if (ListItemPattern().Match(line) is { Success: true } sub)
{
if (sub.Groups[1].Value.Length > indent)
{
var inner = new StringBuilder();
j = new Parser(lines, links, inner).List(j, end, sub.Groups[1].Value.Length);
nested.Append(inner);
continue;
}
break;
}
if (lead <= indent || IsBlockStart(line))
{
break;
}
text.Append(' ').Append(line.Trim());
j++;
}
html.Append("<li>").Append(Inline(text.ToString())).Append(nested).Append("</li>");
if (j < end && lines[j].Trim().Length == 0 && j + 1 < end && ListItemPattern().Match(lines[j + 1]) is { Success: true } after
&& after.Groups[1].Value.Length == indent)
{
j++;
}
}
html.Append(ordered ? "</ol>\n" : "</ul>\n");
return j;
}
private int Paragraph(int i, int end)
{
var text = new StringBuilder();
var j = i;
while (j < end && lines[j].Trim().Length > 0 && (j == i || !IsBlockStart(lines[j])))
{
// Two spaces at the end of a line are a line break, as in the wiki.
var line = lines[j];
text.Append(Inline(line.Trim())).Append(line.EndsWith(" ", StringComparison.Ordinal) ? "<br />" : " ");
j++;
}
html.Append("<p>").Append(text.ToString().TrimEnd()).Append("</p>\n");
return j;
}
private static bool IsBlockStart(string line)
{
var trimmed = line.Trim();
return trimmed.StartsWith("```", StringComparison.Ordinal) || trimmed.StartsWith('>') || trimmed.StartsWith('|')
|| HeadingPattern().IsMatch(trimmed) || ListItemPattern().IsMatch(line) || trimmed is "---" or "***" or "___";
}
private string Inline(string text)
{
var output = new StringBuilder();
var i = 0;
while (i < text.Length)
{
var c = text[i];
if (c == '\\' && i + 1 < text.Length && char.IsPunctuation(text[i + 1]) || c == '\\' && i + 1 < text.Length && char.IsSymbol(text[i + 1]))
{
output.Append(Encode(text[i + 1].ToString()));
i += 2;
}
else if (c == '`' && text.IndexOf('`', i + 1) is var close && close > i)
{
output.Append("<code>").Append(Encode(text[(i + 1)..close])).Append("</code>");
i = close + 1;
}
else if (c == '!' && i + 1 < text.Length && text[i + 1] == '[' && TryLink(text, i + 1, out var alt, out var src, out var after))
{
var local = links.Media(src);
var url = local ?? (IsWeb(src) ? src : null);
output.Append(url is null
? Encode(alt)
: $"<img src=\"{Attr(url)}\" alt=\"{Attr(PlainText(alt))}\" loading=\"lazy\" />");
i = after;
}
else if (c == '[' && TryLink(text, i, out var label, out var href, out var next))
{
output.Append(Anchor(label, href));
i = next;
}
else if (c == '*' && i + 1 < text.Length && text[i + 1] == '*' && text.IndexOf("**", i + 2, StringComparison.Ordinal) is var bold && bold > i + 2)
{
output.Append("<strong>").Append(Inline(text[(i + 2)..bold])).Append("</strong>");
i = bold + 2;
}
else if (c is '*' or '_' && i + 1 < text.Length && !char.IsWhiteSpace(text[i + 1]) && (c == '*' || i == 0 || !char.IsLetterOrDigit(text[i - 1]))
&& Closing(text, i + 1, c) is var em && em > i + 1)
{
output.Append("<em>").Append(Inline(text[(i + 1)..em])).Append("</em>");
i = em + 1;
}
else if (c == '<' && text.AsSpan(i).StartsWith("<br", StringComparison.OrdinalIgnoreCase) && text.IndexOf('>', i) is var gt && gt > i)
{
output.Append("<br />");
i = gt + 1;
}
else
{
output.Append(Encode(c.ToString()));
i++;
}
}
return output.ToString();
}
private static int Closing(string text, int from, char mark)
{
for (var k = from; k < text.Length; k++)
{
if (text[k] == mark && !char.IsWhiteSpace(text[k - 1]) && (k + 1 >= text.Length || text[k + 1] != mark)
&& (mark == '*' || k + 1 >= text.Length || !char.IsLetterOrDigit(text[k + 1])))
{
return k;
}
}
return -1;
}
private static bool TryLink(string text, int open, out string label, out string href, out int after)
{
label = href = string.Empty;
after = open;
var depth = 0;
var k = open;
for (; k < text.Length; k++)
{
if (text[k] == '[')
{
depth++;
}
else if (text[k] == ']' && --depth == 0)
{
break;
}
}
if (k + 1 >= text.Length || text[k + 1] != '(')
{
return false;
}
var closeParen = text.IndexOf(')', k + 2);
if (closeParen < 0)
{
return false;
}
label = text[(open + 1)..k];
href = text[(k + 2)..closeParen].Trim();
var space = href.IndexOf(' ', StringComparison.Ordinal);
if (space > 0)
{
href = href[..space];
}
after = closeParen + 1;
return true;
}
private string Anchor(string label, string href)
{
var inner = Inline(label);
if (IsWeb(href))
{
return $"<a href=\"{Attr(href)}\" target=\"_blank\" rel=\"noopener\">{inner}</a>";
}
if (href.StartsWith('#'))
{
return $"<a href=\"{Attr("#" + Slug(href[1..].Replace('-', ' ')))}\">{inner}</a>";
}
return PagePattern().IsMatch(href) ? $"<a href=\"{Attr(links.Page(href))}\">{inner}</a>" : inner;
}
private static bool IsWeb(string url) =>
url.StartsWith("https://", StringComparison.OrdinalIgnoreCase) || url.StartsWith("http://", StringComparison.OrdinalIgnoreCase);
private static string Encode(string text) => WebUtility.HtmlEncode(text);
private static string Attr(string text) => WebUtility.HtmlEncode(text);
}
}
+23
View File
@@ -5,6 +5,7 @@ using Khaemhat.Core.Common;
using Khaemhat.Infrastructure.Logging;
using Khaemhat.Infrastructure.Security;
using Khaemhat.Web.Components;
using Khaemhat.Web.Help;
using Khaemhat.Web.Security;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Authentication;
@@ -109,6 +110,7 @@ public static class KhaemhatApp
app.MapStaticAssets();
app.MapSignOut();
app.MapCompanySwitch();
app.MapHelp();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
@@ -130,6 +132,27 @@ public static class KhaemhatApp
}
}
// The images of the help pages (mockups, icons) from the copy of the wiki, and /help, the address of SPEC §17, which
// leads to the help page inside the application (mockup 011).
private static void MapHelp(this IEndpointRouteBuilder endpoints)
{
endpoints.MapGet(WikiLibrary.MediaPath + "/{**path}", (string path, WikiLibrary wiki) =>
wiki.MediaFile(path) is { } file
? Results.File(file, Path.GetExtension(file).ToLowerInvariant() switch
{
".svg" => "image/svg+xml",
".jpg" or ".jpeg" => "image/jpeg",
".gif" => "image/gif",
".webp" => "image/webp",
_ => "image/png",
})
: Results.NotFound())
.AllowAnonymous();
endpoints.MapGet("/help/{**page}", (HttpContext context, string? page) =>
Results.Redirect(context.Request.PathBase + WikiLibrary.BasePath + (string.IsNullOrEmpty(page) ? string.Empty : "/" + Uri.EscapeDataString(page))));
endpoints.MapGet("/help", (HttpContext context) => Results.Redirect(context.Request.PathBase + WikiLibrary.BasePath));
}
// POST /session/company: an instance account chooses the company of its session (top bar, SPEC §10.2). The page
// is reloaded, so the new circuit starts in the new company.
private static void MapCompanySwitch(this IEndpointRouteBuilder endpoints) =>
@@ -10,6 +10,7 @@ using Khaemhat.Application.Localization;
using Khaemhat.Application.Modules;
using Khaemhat.Application.Notifications;
using Khaemhat.Application.Preferences;
using Khaemhat.Application.Search;
using Khaemhat.Application.Security;
using Khaemhat.Core.Caching;
using Khaemhat.Core.Files;
@@ -27,6 +28,7 @@ using Khaemhat.Infrastructure.Files;
using Khaemhat.Infrastructure.Licensing;
using Khaemhat.Infrastructure.Logging;
using Khaemhat.Infrastructure.Security;
using Khaemhat.Web.Help;
using Khaemhat.Web.Security;
using Khaemhat.Web.Shell;
@@ -50,6 +52,9 @@ internal static class KhaemhatServices
{
var dataAssembly = typeof(CompanyRegistry).Assembly;
services.AddSingleton(options);
services.AddSingleton(_ => new WikiLibrary());
services.AddSingleton<ISearchProvider, HelpSearchProvider>();
services.AddSingleton<GlobalSearchService>();
services.AddSingleton(logSink);
services.AddSingleton(TimeProvider.System);
services.AddSingleton<BootstrapState>();
+10
View File
@@ -23,4 +23,14 @@
<Content Remove="Resources/**/*.json" />
</ItemGroup>
<!-- The help (SPEC §17, ADR 0023): a copy of the wiki and of the images it shows, next to the program, so F1 works
without Internet. Read by WikiLibrary from help/. -->
<ItemGroup>
<None Include="../../docs/wiki/*.md" Link="help/wiki/%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
<None Include="../../docs/wiki/img/**/*" Link="help/media/docs/wiki/img/%(RecursiveDir)%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
<None Include="../../docs/mockups/thumbs/*.png" Link="help/media/docs/mockups/thumbs/%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
<None Include="../../docs/mockups/png/*.png" Link="help/media/docs/mockups/png/%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
<None Include="../../assets/*.png" Link="help/media/assets/%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
</ItemGroup>
</Project>
@@ -357,6 +357,17 @@
"OpenCard": "Apri la scheda",
"Block": "Blocca"
}
},
"Help": {
"Title": "Aiuto",
"TabTitle": "Aiuto · {0}",
"Heading": "Aiuto · {0}",
"Crumb": "Aiuto (F1)",
"Index": "Indice dell'aiuto",
"OpenWiki": "Apri nel wiki",
"Report": "Segnala un problema",
"Missing": "La copia della wiki non è presente in questa installazione: apri la wiki online.",
"NotFound": "La pagina «{0}» non esiste nella wiki: scegline una dall'indice."
}
}
}
+27 -3
View File
@@ -17,7 +17,6 @@
"NoRecent": "Nessuna pagina aperta di recente",
"Notifications": "Notifiche",
"NotificationsCount": "Notifiche: {0} non lette",
"NoNotifications": "Nessuna notifica da leggere",
"ThemeDark": "Passa al tema scuro",
"ThemeLight": "Passa al tema chiaro",
"Help": "Aiuto della pagina"
@@ -167,13 +166,18 @@
},
"Search": {
"Title": "Ricerca globale",
"Placeholder": "Cerca una pagina o un comando (> per i comandi)",
"Placeholder": "Cerca pagine, aiuto e comandi (> comandi, # documenti, @ persone)",
"NoResults": "Nessun risultato",
"Pages": "Pagine",
"CommandsGroup": "Comandi",
"Move": "sposta",
"Open": "apri",
"Commands": "comandi"
"Commands": "comandi",
"Help": "Aiuto",
"Documents": "documenti",
"People": "persone",
"DocumentsSoon": "La ricerca dei documenti arriva con i moduli Vendite e Acquisti",
"PeopleSoon": "La ricerca delle persone arriva con le anagrafiche e il CRM"
},
"Commands": {
"ToggleTheme": "Cambia tema chiaro/scuro",
@@ -214,6 +218,26 @@
"Paused": "La sessione è stata sospesa dal server.",
"ResumeFailed": "Impossibile riprendere la sessione.",
"Resume": "Riprendi"
},
"Notifications": {
"Title": "Notifiche",
"Filter": "Quali notifiche",
"All": "Tutte ({0})",
"Unread": "Non lette ({0})",
"None": "Nessuna notifica.",
"NoneUnread": "Hai letto tutto.",
"MarkRead": "Segna come letta",
"MarkReadOf": "Segna come letta: {0}",
"MarkAll": "Segna tutte come lette",
"Now": "Adesso",
"MinutesAgo": "{0} min fa",
"Yesterday": "Ieri {0}",
"Categories": {
"security": "Sicurezza",
"jobs": "Attività",
"system": "Sistema",
"licenses": "Licenza"
}
}
}
}
+20
View File
@@ -62,4 +62,24 @@ public static class HelpLinks
/// <param name="path">The path.</param>
/// <returns>The address.</returns>
public static string UrlFor(string baseUrl, string path) => baseUrl + PageFor(path);
/// <summary>The help page of a path inside the application (F1, mockup 011).</summary>
/// <param name="path">The path.</param>
/// <returns>The relative address, such as <c>aiuto/Anagrafiche</c>.</returns>
public static string LocalFor(string path) => Khaemhat.Web.Help.WikiLibrary.Href(PageFor(path));
/// <summary>The online wiki: <c>KHAEMHAT_HELP_URL</c> or the project wiki, always ending with a slash.</summary>
/// <param name="configured">The configured address, if any.</param>
/// <returns>The address.</returns>
public static string BaseUrl(string? configured) =>
string.IsNullOrWhiteSpace(configured) ? DefaultBaseUrl : configured.EndsWith('/') ? configured : configured + "/";
/// <summary>Where to report a problem: the issues of the repository whose wiki it is (Gitea and GitHub alike).</summary>
/// <param name="baseUrl">The wiki address.</param>
/// <returns>The address of a new issue, or <see langword="null"/> when the wiki is not a repository wiki.</returns>
public static string? IssuesUrl(string baseUrl)
{
ArgumentNullException.ThrowIfNull(baseUrl);
return baseUrl.EndsWith("/wiki/", StringComparison.OrdinalIgnoreCase) ? baseUrl[..^"wiki/".Length] + "issues/new" : null;
}
}
+50
View File
@@ -191,3 +191,53 @@ h1[tabindex="-1"]:focus { outline: none; box-shadow: none; }
@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; } }
/* ---- notifications panel (issue #32, mockup 010) ---- */
.kh-notif-filter { margin-bottom: 4px; }
.kh-notifs { list-style: none; margin: 0 -16px; padding: 0; }
.kh-notif { display: flex; align-items: flex-start; gap: 10px; padding: 10px 16px; border-bottom: 1px solid var(--kh-border); }
.kh-notif.unread { background: var(--kh-accent-soft); }
.kh-notif .ico-box { width: 28px; height: 28px; flex: none; }
.kh-notif-main { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 3px; border: 0; background: none; padding: 0; text-align: left;
font: inherit; color: var(--kh-text); cursor: pointer; }
.kh-notif-main .t { font-size: 12.5px; }
.kh-notif.unread .kh-notif-main .t { font-weight: 600; }
.kh-notif-main .s { font-size: 11.5px; color: var(--kh-text-2); display: -webkit-box; -webkit-line-clamp: 3; line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }
.kh-notif-main .m { display: flex; align-items: center; gap: 8px; font-size: 11px; color: var(--kh-text-3); }
.kh-notif-main:focus-visible { outline: 2px solid var(--kh-accent); outline-offset: 2px; border-radius: 4px; }
/* ---- help (issue #32, mockup 011) ---- */
.kh-help { display: grid; grid-template-columns: 260px minmax(0, 1fr); gap: var(--kh-gap); align-items: start; margin-top: var(--kh-gap); }
.kh-help-index { padding: 8px; display: flex; flex-direction: column; gap: 1px; position: sticky; top: 0; max-height: calc(100vh - 190px); overflow: auto; }
.kh-help-group { font-size: 10.5px; font-weight: 600; letter-spacing: .06em; text-transform: uppercase; color: var(--kh-text-3); padding: 10px 8px 4px; }
.kh-help-link { display: flex; align-items: center; gap: 8px; padding: 6px 8px; border-radius: var(--kh-radius); color: var(--kh-text); text-decoration: none; font-size: 12.5px; }
.kh-help-link svg.i { color: var(--kh-text-3); }
.kh-help-link:hover { background: var(--kh-row-hover); }
.kh-help-link.on { background: var(--kh-accent-soft); color: var(--kh-accent-text); font-weight: 600; }
.kh-help-link.on svg.i { color: var(--kh-accent); }
.kh-help-body { padding: 22px 26px 28px; font-size: 13.5px; line-height: 1.6; color: var(--kh-text); min-width: 0; }
.kh-help-body h1 { font-size: 22px; font-weight: 650; margin: 0 0 10px; }
.kh-help-body h2 { font-size: 16px; font-weight: 600; margin: 26px 0 8px; }
.kh-help-body h3 { font-size: 14px; font-weight: 600; margin: 18px 0 6px; }
.kh-help-body p, .kh-help-body ul, .kh-help-body ol { margin: 0 0 10px; }
.kh-help-body ul, .kh-help-body ol { padding-left: 22px; }
.kh-help-body li { margin: 2px 0; }
.kh-help-body a { color: var(--kh-accent-text); }
.kh-help-body code { font-family: var(--kh-font-mono, ui-monospace, Consolas, monospace); font-size: .92em; background: var(--kh-surface-3); border-radius: 4px; padding: 1px 4px; }
.kh-help-body pre { background: var(--kh-surface-2); border: 1px solid var(--kh-border); border-radius: var(--kh-radius); padding: 10px 12px; overflow: auto; font-size: 12px; line-height: 1.45; }
.kh-help-body pre code { background: none; padding: 0; }
.kh-help-body img { max-width: 100%; border: 1px solid var(--kh-border); border-radius: var(--kh-radius); margin: 6px 0; }
.kh-help-body hr { border: 0; border-top: 1px solid var(--kh-border); margin: 18px 0; }
.kh-help-body .callout { margin: 10px 0; font-size: 13px; }
.kh-help-body .callout p:last-child { margin-bottom: 0; }
.kh-help-meta { font-size: 12px; color: var(--kh-text-3); margin-bottom: 14px; }
.kh-help-meta p { margin: 0; }
.kh-help-table { overflow-x: auto; margin: 6px 0 14px; border: 1px solid var(--kh-border); border-radius: var(--kh-radius); }
.kh-help-table table.grid { width: 100%; }
.kh-help-table table.grid td { white-space: normal; height: auto; padding: 6px 10px; max-width: none; vertical-align: top; }
.kh-help-table table.grid th { white-space: normal; text-align: left; }
/* Global search (mockup 009): the page a help section belongs to. */
.palette .hit .d { color: var(--kh-text-3); font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; }
.palette .hit > span:first-of-type { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.palette .hit .d:last-child { margin-left: auto; }
@media (max-width: 899px) { .kh-help { grid-template-columns: 1fr; } .kh-help-index { position: static; max-height: 240px; } }
+9 -1
View File
@@ -44,7 +44,15 @@
document.addEventListener("keydown", function (e) {
if (e.key !== "Escape" || e.defaultPrevented) return;
const overlays = document.querySelectorAll(".overlay");
if (overlays.length === 0 || (e.target.closest && e.target.closest(".overlay"))) return;
if (overlays.length === 0) {
// No dialog: a side panel closes too, but only when the focus is nowhere (a field keeps its own Escape).
const drawers = document.querySelectorAll(".kh-drawer");
if (drawers.length === 0 || e.target !== document.body) return;
const shut = drawers[drawers.length - 1].querySelector(".kh-close");
if (shut) shut.click();
return;
}
if (e.target.closest && e.target.closest(".overlay")) return;
const close = overlays[overlays.length - 1].querySelector(".kh-close");
if (close) close.click();
});
@@ -0,0 +1,69 @@
using Khaemhat.Application.Search;
using Khaemhat.Application.Security;
using Khaemhat.Core.Security;
using Microsoft.Extensions.Logging.Abstractions;
namespace Khaemhat.Application.Tests;
/// <summary>The global search of SPEC §10.2 (issue #32, mockup 009).</summary>
[TestClass]
public sealed class GlobalSearchTests
{
private static readonly Actor Root = new("root", UserLevel.SuperUser, 1, null, null);
[TestMethod]
[DataRow(" fattura ", SearchScope.All, "fattura")]
[DataRow("> tema", SearchScope.Commands, "tema")]
[DataRow("#FT 12", SearchScope.Documents, "FT 12")]
[DataRow("@rossi", SearchScope.People, "rossi")]
[DataRow("", SearchScope.All, "")]
public void Query_ReadsThePrefix(string input, SearchScope scope, string text)
{
var query = SearchQuery.Parse(input);
Assert.AreEqual(scope, query.Scope);
Assert.AreEqual(text, query.Text);
}
[TestMethod]
public void Query_MatchesEveryWord_IgnoringCase()
{
var query = SearchQuery.Parse("iva liq");
Assert.IsTrue(query.Matches("Liquidazione IVA"));
Assert.IsFalse(query.Matches("Registri IVA"));
Assert.IsFalse(query.Matches(null));
Assert.IsTrue(SearchQuery.Parse(" ").Matches("qualsiasi"));
}
[TestMethod]
public async Task Search_AsksTheProvidersOfTheScope_AndLeavesOutTheOnesThatFail()
{
var search = new GlobalSearchService(
[new Provider([SearchScope.All], "Aiuto"), new Failing(), new Provider([SearchScope.All, SearchScope.Documents], "Documento")],
NullLogger<GlobalSearchService>.Instance);
var all = await search.SearchAsync(Root, SearchQuery.Parse("ab"));
Assert.HasCount(2 * GlobalSearchService.PerProvider, all);
CollectionAssert.AreEqual(new[] { "Aiuto ab", "Documento ab" }, all.Select(h => h.Title).Distinct().ToList());
CollectionAssert.AreEqual(new[] { "Documento ab" }, (await search.SearchAsync(Root, SearchQuery.Parse("#ab"))).Select(h => h.Title).Distinct().ToList());
Assert.IsEmpty(await search.SearchAsync(Root, SearchQuery.Parse("a")), "Too short.");
Assert.IsEmpty(await search.SearchAsync(Root, SearchQuery.Parse(">ab")), "Commands are not records.");
Assert.IsTrue(search.Covers(SearchScope.Documents));
Assert.IsFalse(search.Covers(SearchScope.People));
}
private sealed class Provider(SearchScope[] scopes, string title) : ISearchProvider
{
public IReadOnlyCollection<SearchScope> Scopes => scopes;
public Task<IReadOnlyList<SearchHit>> SearchAsync(Actor actor, SearchQuery query, CancellationToken cancellationToken) =>
Task.FromResult<IReadOnlyList<SearchHit>>([.. Enumerable.Range(0, 20).Select(i => new SearchHit("g", "file", title + " " + query.Text, null, "x"))]);
}
private sealed class Failing : ISearchProvider
{
public IReadOnlyCollection<SearchScope> Scopes => [SearchScope.All];
public Task<IReadOnlyList<SearchHit>> SearchAsync(Actor actor, SearchQuery query, CancellationToken cancellationToken) =>
throw new InvalidOperationException("broken");
}
}
@@ -45,6 +45,20 @@ public sealed class SystemRulesTests
Assert.IsFalse(error.Errors.Any(e => e.Contains(Key, StringComparison.Ordinal)), "Errors never repeat a secret.");
}
[TestMethod]
public void Configuration_HelpUrl_IsAnAbsoluteWebAddress()
{
var variables = Required();
variables["KHAEMHAT_HELP_URL"] = "https://git.example.com/acme/khaemhat/wiki/";
var options = new EnvironmentConfigurationReader(n => variables.GetValueOrDefault(n)).Read();
options.EnsureValid();
Assert.AreEqual("https://git.example.com/acme/khaemhat/wiki/", options.HelpUrl);
variables["KHAEMHAT_HELP_URL"] = "wiki/locale";
var error = Assert.ThrowsExactly<ConfigurationException>(() => new EnvironmentConfigurationReader(n => variables.GetValueOrDefault(n)).Read().EnsureValid());
Assert.IsTrue(error.Errors.Any(e => e.StartsWith("KHAEMHAT_HELP_URL", StringComparison.Ordinal)));
}
[TestMethod]
public void Configuration_ReportsEveryMissingVariableAtOnce()
{
+2 -2
View File
@@ -70,8 +70,8 @@ public sealed class MappingTests
string[] expected =
[
"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", "company_settings", "notifications", "role_permissions", "roles", "user_permission_overrides", "user_roles", "user_sessions", "user_settings", "users",
"sys_notification_reads", "sys_notifications", "sys_roles_templates", "sys_scheduled_tasks", "sys_security_audit", "sys_sessions", "sys_settings", "sys_user_settings", "sys_users",
"attachments", "audit_log", "company_settings", "notification_reads", "notifications", "role_permissions", "roles", "user_permission_overrides", "user_roles", "user_sessions", "user_settings", "users",
];
CollectionAssert.AreEquivalent(expected, registry.Maps.Select(m => m.Table).ToArray());
}
+162
View File
@@ -0,0 +1,162 @@
using System.Reflection;
using System.Text.RegularExpressions;
using Khaemhat.Web.Help;
using Khaemhat.Web.Shell;
using Microsoft.AspNetCore.Components;
namespace Khaemhat.Web.Tests.Shell;
/// <summary>The help of SPEC §17 (issue #32, mockup 011): the wiki shipped with the application and its links.</summary>
[TestClass]
public sealed partial class HelpTests
{
private static readonly WikiLinks Links = new(page => "aiuto/" + page, url => url.EndsWith("local.png", StringComparison.Ordinal) ? "aiuto/media/local.png" : null);
private static readonly WikiLibrary Wiki = new(Path.Combine(AppContext.BaseDirectory, "help"));
[TestMethod]
public void Markdown_Blocks()
{
var html = WikiMarkdown.ToHtml(
"""
# Titolo *pagina*
> **Stato:** bozza · **Revisione:** oggi
Un paragrafo
su due righe.
## Come si usa
1. Primo
2. Secondo
- annidato
- altro
3. Terzo
| Campo | Regola |
|---|---|
| Codice | `a\|b` e **grassetto** |
> Nota importante.
```
<script>alert(1)</script>
```
---
""",
Links);
StringAssert.Contains(html, "<h1 id=\"titolo-pagina\">Titolo <em>pagina</em></h1>");
StringAssert.Contains(html, "<div class=\"kh-help-meta\"><p><strong>Stato:</strong> bozza");
StringAssert.Contains(html, "<p>Un paragrafo su due righe.</p>");
StringAssert.Contains(html, "<h2 id=\"come-si-usa\">Come si usa</h2>");
StringAssert.Contains(html, "<ol><li>Primo</li><li>Secondo<ul><li>annidato</li><li>altro</li></ul>\n</li><li>Terzo</li></ol>");
StringAssert.Contains(html, "<th>Campo</th><th>Regola</th>");
StringAssert.Contains(html, "<td><code>a|b</code> e <strong>grassetto</strong></td>");
StringAssert.Contains(html, "<div class=\"callout info\"><div><p>Nota importante.</p>");
StringAssert.Contains(html, "<pre><code>&lt;script&gt;alert(1)&lt;/script&gt;</code></pre>");
StringAssert.Contains(html, "<hr />");
}
[TestMethod]
public void Markdown_LinksAndImages_AreSafe()
{
var html = WikiMarkdown.ToHtml(
"Vedi [Anagrafiche](Anagrafiche), [clienti](Anagrafiche#clienti), [sito](https://example.com), [qui](#come-si-usa), "
+ "[male](javascript:alert) e <b>non HTML</b>. ![Mockup](https://host/raw/branch/main/local.png) ![Fuori](https://host/x.png) ![Rotta](ftp://x)",
Links);
StringAssert.Contains(html, "<a href=\"aiuto/Anagrafiche\">Anagrafiche</a>");
StringAssert.Contains(html, "<a href=\"aiuto/Anagrafiche#clienti\">clienti</a>");
StringAssert.Contains(html, "<a href=\"https://example.com\" target=\"_blank\" rel=\"noopener\">sito</a>");
StringAssert.Contains(html, "<a href=\"#come-si-usa\">qui</a>");
Assert.DoesNotContain("javascript:", html);
StringAssert.Contains(html, "male e &lt;b&gt;non HTML&lt;/b&gt;");
StringAssert.Contains(html, "<img src=\"aiuto/media/local.png\" alt=\"Mockup\" loading=\"lazy\" />");
StringAssert.Contains(html, "<img src=\"https://host/x.png\" alt=\"Fuori\"");
StringAssert.Contains(html, "Rotta");
Assert.DoesNotContain("ftp://", html);
}
[TestMethod]
public void Wiki_IsShipped_WithItsIndex_AndEveryPageConverts()
{
Assert.IsTrue(Wiki.IsAvailable, "The build copies docs/wiki next to the program.");
Assert.IsNotEmpty(Wiki.Sidebar);
foreach (var name in Wiki.PageNames)
{
var page = Wiki.Get(name);
Assert.IsNotNull(page, name);
Assert.IsFalse(string.IsNullOrWhiteSpace(page.Title), name);
Assert.DoesNotContain("<script", page.Html, name);
}
Assert.IsNotNull(Wiki.MediaFile("docs/mockups/thumbs/004-dashboard.png"));
Assert.IsNull(Wiki.MediaFile("../wiki/Home.md"));
Assert.IsNull(Wiki.MediaFile("../../../../Windows/win.ini"));
}
[TestMethod]
public void EveryLinkBetweenWikiPages_FindsItsPage()
{
var broken = new List<string>();
foreach (var name in Wiki.PageNames)
{
foreach (Match link in PageLink().Matches(Wiki.Get(name)!.Html))
{
if (!Wiki.Exists(link.Groups[1].Value))
{
broken.Add(name + " -> " + link.Groups[1].Value);
}
}
}
Assert.IsEmpty(broken, string.Join(", ", broken));
}
[TestMethod]
public void EveryPage_AndEveryMenuEntry_HasAHelpPageThatExists()
{
var routes = typeof(HelpLinks).Assembly.GetTypes()
.Where(t => typeof(IComponent).IsAssignableFrom(t))
.SelectMany(t => t.GetCustomAttributes<RouteAttribute>())
.Select(r => "/" + r.Template.Split('{')[0].Trim('/'))
.Concat(MenuCatalog.All.Select(i => i.Href))
.Distinct()
.ToList();
Assert.IsGreaterThan(20, routes.Count);
var missing = routes.Where(r => !Wiki.Exists(HelpLinks.PageFor(r))).Select(r => r + " -> " + HelpLinks.PageFor(r)).ToList();
Assert.IsEmpty(missing, string.Join(", ", missing));
Assert.AreEqual("aiuto/Dashboard", HelpLinks.LocalFor("/"));
Assert.AreEqual("aiuto/Anagrafiche", HelpLinks.LocalFor("/anagrafiche/clienti?x=1"));
}
[TestMethod]
public async Task Search_FindsPageTitles_ThenTheirSections()
{
var provider = new HelpSearchProvider(Wiki);
var root = new Khaemhat.Application.Security.Actor("root", Khaemhat.Core.Security.UserLevel.SuperUser, 1, null, null);
var hits = await provider.SearchAsync(root, Khaemhat.Application.Search.SearchQuery.Parse("scorciatoie"), CancellationToken.None);
Assert.AreEqual("aiuto/Interfaccia-e-scorciatoie", hits[0].Href);
Assert.IsTrue(hits.All(h => h.Href.StartsWith("aiuto/", StringComparison.Ordinal)));
Assert.IsTrue(hits.Where(h => h.Detail is not null).All(h => h.Href.Contains('#', StringComparison.Ordinal)));
Assert.IsLessThanOrEqualTo(Khaemhat.Application.Search.GlobalSearchService.PerProvider, hits.Count);
}
[TestMethod]
public void OnlineWiki_AndProblemReports_FollowTheConfiguredAddress()
{
Assert.AreEqual(HelpLinks.DefaultBaseUrl, HelpLinks.BaseUrl(null));
Assert.AreEqual("https://git.example.com/acme/khaemhat/wiki/", HelpLinks.BaseUrl("https://git.example.com/acme/khaemhat/wiki"));
Assert.AreEqual("https://git.example.com/acme/khaemhat/issues/new", HelpLinks.IssuesUrl("https://git.example.com/acme/khaemhat/wiki/"));
Assert.IsNull(HelpLinks.IssuesUrl("https://docs.example.com/"));
}
[GeneratedRegex("href=\"aiuto/([^\"#]+)")]
private static partial Regex PageLink();
}
@@ -0,0 +1,70 @@
using Khaemhat.Application.Modules;
using Khaemhat.Application.Notifications;
using Khaemhat.Application.Security;
using Khaemhat.Core.Instance;
using Khaemhat.Core.Security;
using Khaemhat.Web.Tests.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace Khaemhat.Web.Tests.Shell;
/// <summary>The notification panel of mockup 010 (issue #32): what each user reads is kept per user.</summary>
[TestClass]
public sealed class NotificationInboxTests
{
private const string Category = "test";
[TestMethod]
public async Task ANotificationForEveryone_IsReadByEachUserSeparately()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var notifications = app.Services.GetRequiredService<NotificationDispatcher>();
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.ReadOnly], 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);
await notifications.NotifyCompanyAsync(company, new NotificationMessage(Category, NotificationSeverity.Info, "Per tutti"));
await notifications.NotifyCompanyAsync(company, new NotificationMessage(Category, NotificationSeverity.Warning, "Solo per Anna", "Dettaglio", "/profilo"), anna.Id);
var annaInbox = await Inbox(annaActor);
CollectionAssert.AreEqual(new[] { "Solo per Anna", "Per tutti" }, annaInbox.Select(n => n.Title).ToList(), "Newest first.");
Assert.IsTrue(annaInbox[0].Personal);
Assert.AreEqual("/profilo", annaInbox[0].Link);
Assert.IsTrue(annaInbox.All(n => !n.Read));
CollectionAssert.AreEqual(new[] { "Per tutti" }, (await Inbox(lucaActor)).Select(n => n.Title).ToList(), "Personal notifications stay personal.");
// Anna reads the one for everyone: it stays unread for Luca; reading it again changes nothing.
var everyone = annaInbox[1].Id;
await notifications.MarkReadAsync(annaActor, everyone);
await notifications.MarkReadAsync(annaActor, everyone);
Assert.IsTrue((await Inbox(annaActor)).Single(n => n.Id == everyone).Read);
Assert.IsFalse((await Inbox(lucaActor)).Single(n => n.Id == everyone).Read);
// Nobody marks someone else's notification.
await notifications.MarkReadAsync(lucaActor, annaInbox[0].Id);
Assert.IsFalse((await Inbox(annaActor)).Single(n => n.Id == annaInbox[0].Id).Read);
// "Segna tutte come lette" is for the user only.
await notifications.MarkAllReadAsync(annaActor);
Assert.IsEmpty(await Inbox(annaActor, unreadOnly: true));
Assert.HasCount(1, await Inbox(lucaActor, unreadOnly: true));
// Instance accounts read the notifications of the system.
await notifications.NotifyInstanceAsync(new NotificationMessage(Category, NotificationSeverity.Error, "Backup non riuscito"));
var system = await Inbox(root, unreadOnly: true);
Assert.AreEqual("Backup non riuscito", system.Single().Title);
Assert.IsFalse((await Inbox(annaActor)).Any(n => n.Title == "Backup non riuscito"));
await notifications.MarkAllReadAsync(root);
Assert.IsEmpty(await Inbox(root, unreadOnly: true));
await app.StopAsync();
async Task<List<InboxItem>> Inbox(Actor actor, bool unreadOnly = false) =>
[.. (await notifications.InboxAsync(actor, unreadOnly)).Where(n => n.Category == Category)];
}
}
}