using Khaemhat.Application.Security; using Microsoft.Extensions.Logging; namespace Khaemhat.Application.Dashboard; /// The colour of a line in a dashboard list. public enum FeedTone { /// Nothing special. Neutral = 0, /// Information. Info = 1, /// Done, fine. Ok = 2, /// Needs attention. Warning = 3, /// Something went wrong. Error = 4, } /// /// A line of Da fare oggi, Fatto oggi or Scadenze. The texts are already in the user's /// language; is the text key of the area label (Sistema, Vendite, Fiscale…). /// /// A stable id, unique within the list. /// What it is. /// The text key of the area. /// The colour. public sealed record FeedItem(string Id, string Text, string AreaKey, FeedTone Tone = FeedTone.Neutral) { /// A second line, if any. public string? Detail { get; init; } /// When: the time for what was done, the date for a deadline. public DateTimeOffset? When { get; init; } /// Where it opens, a local address. public string? Href { get; init; } /// Higher first, for the things to do. public int Priority { get; init; } } /// Who asks and when. /// The user. /// The local time now. public sealed record FeedContext(Actor Actor, DateTimeOffset Now) { /// Today, local. public DateOnly Today => DateOnly.FromDateTime(Now.DateTime); /// The start of today, local. public DateTimeOffset StartOfToday => new(Now.Date, Now.Offset); } /// A source of things to do today (rejected SDI invoices, VAT settlements, procedures waiting… as the modules come). public interface ITodoSource { /// The things to do. /// Who and when. /// Cancellation. /// The lines. Task> GetAsync(FeedContext context, CancellationToken cancellationToken); } /// A source of things done today (documents issued, collections, backups, scheduled tasks…). public interface IDoneSource { /// The things done. /// Who and when. /// Cancellation. /// The lines. Task> GetAsync(FeedContext context, CancellationToken cancellationToken); } /// A source of deadlines (fiscal, sales, treasury, contracts…). public interface IDeadlineSource { /// The deadlines from today up to the horizon. /// Who and when. /// The last day included. /// Cancellation. /// The lines, with set. Task> GetAsync(FeedContext context, DateOnly until, CancellationToken cancellationToken); } /// /// Runs every source of one kind and merges what they say. A source that fails is logged and left out: one broken /// module must not empty the whole dashboard. /// public abstract class FeedAggregator { /// The most lines a widget shows. public const int MaxItems = 50; /// Runs the sources one after the other (they share the database connections of the scope). /// The calls. /// Where failures go. /// Cancellation. /// All the lines. protected static async Task> CollectAsync( IEnumerable<(string Name, Func>> Call)> sources, ILogger logger, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(sources); var items = new List(); foreach (var (name, call) in sources) { cancellationToken.ThrowIfCancellationRequested(); try { items.AddRange(await call().ConfigureAwait(false)); } catch (Exception ex) when (ex is not OperationCanceledException) { logger.LogWarning(ex, "Dashboard source {Source} failed and was left out.", name); } } return items; } } /// What to do today, the most urgent first. /// The sources. /// The clock. /// The log. public sealed class TodoAggregator(IEnumerable sources, TimeProvider clock, ILogger logger) : FeedAggregator { /// The things to do. /// The user. /// Cancellation. /// Higher priority first, then the oldest. public async Task> GetAsync(Actor actor, CancellationToken cancellationToken = default) { var context = new FeedContext(actor, clock.GetLocalNow()); var items = await CollectAsync(sources.Select(s => (s.GetType().Name, (Func>>)(() => s.GetAsync(context, cancellationToken)))), logger, cancellationToken).ConfigureAwait(false); return [.. items.OrderByDescending(i => i.Priority).ThenBy(i => i.When ?? DateTimeOffset.MaxValue).Take(MaxItems)]; } } /// What was done today, the latest first. /// The sources. /// The clock. /// The log. public sealed class DoneAggregator(IEnumerable sources, TimeProvider clock, ILogger logger) : FeedAggregator { /// The things done today. /// The user. /// Cancellation. /// The latest first. public async Task> GetAsync(Actor actor, CancellationToken cancellationToken = default) { var context = new FeedContext(actor, clock.GetLocalNow()); var items = await CollectAsync(sources.Select(s => (s.GetType().Name, (Func>>)(() => s.GetAsync(context, cancellationToken)))), logger, cancellationToken).ConfigureAwait(false); return [.. items.OrderByDescending(i => i.When ?? DateTimeOffset.MinValue).Take(MaxItems)]; } } /// The deadlines of the next days, the nearest first. /// The sources. /// The clock. /// The log. public sealed class DeadlineAggregator(IEnumerable sources, TimeProvider clock, ILogger logger) : FeedAggregator { /// How far the widget looks ahead. public const int HorizonDays = 30; /// The deadlines from today to days ahead. /// The user. /// Cancellation. /// The nearest first. public async Task> GetAsync(Actor actor, CancellationToken cancellationToken = default) { var context = new FeedContext(actor, clock.GetLocalNow()); var until = context.Today.AddDays(HorizonDays); var items = await CollectAsync(sources.Select(s => (s.GetType().Name, (Func>>)(() => s.GetAsync(context, until, cancellationToken)))), logger, cancellationToken).ConfigureAwait(false); return [.. items .Where(i => i.When is { } when && DateOnly.FromDateTime(when.DateTime) >= context.Today && DateOnly.FromDateTime(when.DateTime) <= until) .OrderBy(i => i.When) .Take(MaxItems)]; } }