using Khaemhat.Application.Security;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Application.Notifications;
/// A notification to deliver.
/// The area: security, jobs, system, licenses...
/// The weight.
/// The title.
/// The text.
/// A link inside the application.
public sealed record NotificationMessage(string Category, NotificationSeverity Severity, string Title, string? Body = null, string? Link = null);
/// A notification as its recipient sees it.
/// The id.
/// The area.
/// The weight.
/// The title.
/// The text.
/// A link inside the application.
/// When it was sent (UTC).
/// Whether this user read it.
/// Addressed to this user only, not to everyone.
public sealed record InboxItem(long Id, string Category, NotificationSeverity Severity, string Title, string? Body, string? Link, DateTime CreatedAt, bool Read, bool Personal);
///
/// Delivers in-app notifications (SPEC ยง9; mockup 010): to instance accounts in sys_notifications, to company
/// users in the company's notifications. A notification without recipient goes to everyone in the scope.
/// Delivery never breaks the caller: a failure is logged.
///
/// Opens the databases.
/// The clock.
/// The log.
public sealed class NotificationDispatcher(IUnitOfWorkFactory factory, TimeProvider clock, ILogger logger)
{
/// Notifies instance accounts.
/// The notification.
/// One account, or for all of them.
/// Cancellation.
/// A task.
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().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);
}
}
/// Notifies the users of a company.
/// The company.
/// The notification.
/// One user, or for all of them.
/// Cancellation.
/// A task.
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().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);
}
}
/// The most notifications a user sees: the newest ones.
public const int InboxSize = 100;
/// The notifications of a user, newest first (mockup 010).
/// The user: instance accounts read the system ones, company users those of their company.
/// Only those not read yet.
/// Cancellation.
/// The notifications, at most .
public Task> InboxAsync(Actor actor, bool unreadOnly = false, CancellationToken cancellationToken = default) =>
ScopeOf(actor) switch
{
({ } scope, { } user, true) => InboxAsync(scope, user, unreadOnly, cancellationToken),
({ } scope, { } user, false) => InboxAsync(scope, user, unreadOnly, cancellationToken),
_ => Task.FromResult>([]),
};
/// Marks a notification as read by the user. A notification for everyone stays unread for the others.
/// The user.
/// The notification.
/// Cancellation.
/// A task.
public Task MarkReadAsync(Actor actor, long notificationId, CancellationToken cancellationToken = default) =>
MarkAsync(actor, [notificationId], cancellationToken);
/// Marks every notification of the user as read.
/// The user.
/// Cancellation.
/// A task.
public async Task MarkAllReadAsync(Actor actor, CancellationToken cancellationToken = default)
{
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 ids, CancellationToken cancellationToken) =>
ids.Count == 0
? Task.CompletedTask
: ScopeOf(actor) switch
{
({ } scope, { } user, true) => MarkAsync(scope, user, ids, cancellationToken),
({ } scope, { } user, false) => MarkAsync(scope, user, ids, cancellationToken),
_ => Task.CompletedTask,
};
private static (DatabaseScope? Scope, long? User, bool System) ScopeOf(Actor actor)
{
ArgumentNullException.ThrowIfNull(actor);
return actor switch
{
{ SystemUserId: { } id } => (DatabaseScope.System, id, true),
{ CompanyUserId: { } id, CompanyCode: { } company } => (DatabaseScope.Company(company), id, false),
_ => (null, null, false),
};
}
private async Task> InboxAsync(DatabaseScope scope, long userId, bool unreadOnly, CancellationToken cancellationToken)
where TNotification : NotificationRecord, new()
where TRead : NotificationReadRecord, new()
{
await using var unitOfWork = await factory.CreateAsync(scope, cancellationToken).ConfigureAwait(false);
var notifications = (await unitOfWork.Repository().ListAsync(
Query.For().Where(n => n.RecipientUserId == null || n.RecipientUserId == userId).OrderByDescending(n => n.Id).Take(InboxSize),
cancellationToken).ConfigureAwait(false)).Items;
var everyone = notifications.Where(n => n.RecipientUserId == null).Select(n => n.Id).ToList();
var read = everyone.Count == 0
? []
: (await unitOfWork.Repository().ListAsync(
Query.For().Where(r => r.UserId == userId && everyone.Contains(r.NotificationId)), cancellationToken).ConfigureAwait(false)).Items
.Select(r => r.NotificationId).ToHashSet();
return [.. notifications
.Select(n => new InboxItem(n.Id, n.Category, n.Severity, n.Title, n.Body, n.Link, n.CreatedAt,
n.RecipientUserId is null ? read.Contains(n.Id) : n.ReadAt is not null, n.RecipientUserId is not null))
.Where(n => !unreadOnly || !n.Read)];
}
private async Task MarkAsync(DatabaseScope scope, long userId, IReadOnlyList ids, CancellationToken cancellationToken)
where TNotification : NotificationRecord, new()
where TRead : NotificationReadRecord, new()
{
await using var unitOfWork = await factory.CreateAsync(scope, cancellationToken).ConfigureAwait(false);
var list = ids.ToList();
var repository = unitOfWork.Repository();
var notifications = (await repository.ListAsync(
Query.For().Where(n => list.Contains(n.Id) && (n.RecipientUserId == null || n.RecipientUserId == userId)), cancellationToken).ConfigureAwait(false)).Items;
var reads = unitOfWork.Repository();
var already = (await reads.ListAsync(Query.For().Where(r => r.UserId == userId && list.Contains(r.NotificationId)), cancellationToken).ConfigureAwait(false)).Items
.Select(r => r.NotificationId).ToHashSet();
var now = clock.GetUtcNow().UtcDateTime;
await unitOfWork.InTransactionAsync(
async ct =>
{
foreach (var notification in notifications)
{
if (notification.RecipientUserId is null)
{
if (already.Add(notification.Id))
{
await reads.InsertAsync(new TRead { NotificationId = notification.Id, UserId = userId }, ct).ConfigureAwait(false);
}
}
else if (notification.ReadAt is null)
{
notification.ReadAt = now;
await repository.UpdateAsync(notification, ct).ConfigureAwait(false);
}
}
},
cancellationToken).ConfigureAwait(false);
}
private static T Fill(T notification, NotificationMessage message, long? recipient)
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];
}