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

@@ -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 [];
}
}
}