Files
Khaemhat/src/Khaemhat.Application/Notifications/NotificationDispatcher.cs
T
Alby96andClaude Opus 5.5 f415dc37a8 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>
2026-11-11 19:39:17 +01:00

202 lines
11 KiB
C#

using Khaemhat.Application.Security;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Application.Notifications;
/// <summary>A notification to deliver.</summary>
/// <param name="Category">The area: <c>security</c>, <c>jobs</c>, <c>system</c>, <c>licenses</c>...</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>
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, TimeProvider clock, ILogger<NotificationDispatcher> logger)
{
/// <summary>Notifies instance accounts.</summary>
/// <param name="message">The notification.</param>
/// <param name="recipientUserId">One account, or <see langword="null"/> for all of them.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task NotifyInstanceAsync(NotificationMessage message, long? recipientUserId = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(message);
try
{
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
await unitOfWork.Repository<SystemNotification, long>().InsertAsync(Fill(new SystemNotification(), message, recipientUserId), cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
logger.LogError(ex, "Notification {Title} not delivered to instance accounts.", message.Title);
}
}
/// <summary>Notifies the users of a company.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="message">The notification.</param>
/// <param name="recipientUserId">One user, or <see langword="null"/> for all of them.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task NotifyCompanyAsync(string companyCode, NotificationMessage message, long? recipientUserId = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(message);
try
{
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
await unitOfWork.Repository<Notification, long>().InsertAsync(Fill(new Notification(), message, recipientUserId), cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
logger.LogError(ex, "Notification {Title} not delivered to company {Company}.", message.Title, companyCode);
}
}
/// <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, 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)
{
var unread = await InboxAsync(actor, unreadOnly: true, cancellationToken).ConfigureAwait(false);
await MarkAsync(actor, [.. unread.Select(n => n.Id)], cancellationToken).ConfigureAwait(false);
}
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)
{
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)
where T : NotificationRecord
{
notification.RecipientUserId = recipient;
notification.Category = Clip(message.Category, 40);
notification.Severity = message.Severity;
notification.Title = Clip(message.Title, 200);
notification.Body = message.Body;
notification.Link = message.Link is null ? null : Clip(message.Link, 400);
return notification;
}
private static string Clip(string value, int length) => value.Length <= length ? value : value[..length];
}