feat: widget dashboard and company settings (#30, #31)

The home page becomes the widget dashboard of mockups 004-006. Each user
switches widgets on and off, orders them (drag and drop or buttons that
also work from the keyboard), sizes them on the 12-column grid and picks
the start page; every change is saved at once. Whoever may change the
company settings sets a default layout per role, used by people who
never customized; Reset goes back to it.

Todo, Done and Deadlines collect lines from sources each module
registers, so later milestones fill them without touching the widgets;
a failing source is logged and skipped. M3 provides licence, unread
warnings and scheduled task runs. Notes, Shortcuts and System status
work now; widgets of modules still to come say which milestone brings
their data instead of showing fake numbers.

Role defaults live in the new company_settings table, written through
CompanySettingsService with company.settings.write (ADR 0022).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 19:15:06 +01:00
1 parent 75d60ee4c4
commit acb7e598d1
34 files changed
+2812 -76

No files matched your search

@@ -0,0 +1,186 @@
using Khaemhat.Application.Security;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Application.Dashboard;
/// <summary>The colour of a line in a dashboard list.</summary>
public enum FeedTone
{
/// <summary>Nothing special.</summary>
Neutral = 0,
/// <summary>Information.</summary>
Info = 1,
/// <summary>Done, fine.</summary>
Ok = 2,
/// <summary>Needs attention.</summary>
Warning = 3,
/// <summary>Something went wrong.</summary>
Error = 4,
}
/// <summary>
/// A line of <em>Da fare oggi</em>, <em>Fatto oggi</em> or <em>Scadenze</em>. The texts are already in the user's
/// language; <see cref="AreaKey"/> is the text key of the area label (Sistema, Vendite, Fiscale…).
/// </summary>
/// <param name="Id">A stable id, unique within the list.</param>
/// <param name="Text">What it is.</param>
/// <param name="AreaKey">The text key of the area.</param>
/// <param name="Tone">The colour.</param>
public sealed record FeedItem(string Id, string Text, string AreaKey, FeedTone Tone = FeedTone.Neutral)
{
/// <summary>A second line, if any.</summary>
public string? Detail { get; init; }
/// <summary>When: the time for what was done, the date for a deadline.</summary>
public DateTimeOffset? When { get; init; }
/// <summary>Where it opens, a local address.</summary>
public string? Href { get; init; }
/// <summary>Higher first, for the things to do.</summary>
public int Priority { get; init; }
}
/// <summary>Who asks and when.</summary>
/// <param name="Actor">The user.</param>
/// <param name="Now">The local time now.</param>
public sealed record FeedContext(Actor Actor, DateTimeOffset Now)
{
/// <summary>Today, local.</summary>
public DateOnly Today => DateOnly.FromDateTime(Now.DateTime);
/// <summary>The start of today, local.</summary>
public DateTimeOffset StartOfToday => new(Now.Date, Now.Offset);
}
/// <summary>A source of things to do today (rejected SDI invoices, VAT settlements, procedures waiting… as the modules come).</summary>
public interface ITodoSource
{
/// <summary>The things to do.</summary>
/// <param name="context">Who and when.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The lines.</returns>
Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, CancellationToken cancellationToken);
}
/// <summary>A source of things done today (documents issued, collections, backups, scheduled tasks…).</summary>
public interface IDoneSource
{
/// <summary>The things done.</summary>
/// <param name="context">Who and when.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The lines.</returns>
Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, CancellationToken cancellationToken);
}
/// <summary>A source of deadlines (fiscal, sales, treasury, contracts…).</summary>
public interface IDeadlineSource
{
/// <summary>The deadlines from today up to the horizon.</summary>
/// <param name="context">Who and when.</param>
/// <param name="until">The last day included.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The lines, with <see cref="FeedItem.When"/> set.</returns>
Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, DateOnly until, CancellationToken cancellationToken);
}
/// <summary>
/// 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.
/// </summary>
public abstract class FeedAggregator
{
/// <summary>The most lines a widget shows.</summary>
public const int MaxItems = 50;
/// <summary>Runs the sources one after the other (they share the database connections of the scope).</summary>
/// <param name="sources">The calls.</param>
/// <param name="logger">Where failures go.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>All the lines.</returns>
protected static async Task<List<FeedItem>> CollectAsync(
IEnumerable<(string Name, Func<Task<IReadOnlyList<FeedItem>>> Call)> sources, ILogger logger, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(sources);
var items = new List<FeedItem>();
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;
}
}
/// <summary>What to do today, the most urgent first.</summary>
/// <param name="sources">The sources.</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log.</param>
public sealed class TodoAggregator(IEnumerable<ITodoSource> sources, TimeProvider clock, ILogger<TodoAggregator> logger) : FeedAggregator
{
/// <summary>The things to do.</summary>
/// <param name="actor">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Higher priority first, then the oldest.</returns>
public async Task<IReadOnlyList<FeedItem>> GetAsync(Actor actor, CancellationToken cancellationToken = default)
{
var context = new FeedContext(actor, clock.GetLocalNow());
var items = await CollectAsync(sources.Select(s => (s.GetType().Name, (Func<Task<IReadOnlyList<FeedItem>>>)(() => s.GetAsync(context, cancellationToken)))), logger, cancellationToken).ConfigureAwait(false);
return [.. items.OrderByDescending(i => i.Priority).ThenBy(i => i.When ?? DateTimeOffset.MaxValue).Take(MaxItems)];
}
}
/// <summary>What was done today, the latest first.</summary>
/// <param name="sources">The sources.</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log.</param>
public sealed class DoneAggregator(IEnumerable<IDoneSource> sources, TimeProvider clock, ILogger<DoneAggregator> logger) : FeedAggregator
{
/// <summary>The things done today.</summary>
/// <param name="actor">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The latest first.</returns>
public async Task<IReadOnlyList<FeedItem>> GetAsync(Actor actor, CancellationToken cancellationToken = default)
{
var context = new FeedContext(actor, clock.GetLocalNow());
var items = await CollectAsync(sources.Select(s => (s.GetType().Name, (Func<Task<IReadOnlyList<FeedItem>>>)(() => s.GetAsync(context, cancellationToken)))), logger, cancellationToken).ConfigureAwait(false);
return [.. items.OrderByDescending(i => i.When ?? DateTimeOffset.MinValue).Take(MaxItems)];
}
}
/// <summary>The deadlines of the next days, the nearest first.</summary>
/// <param name="sources">The sources.</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log.</param>
public sealed class DeadlineAggregator(IEnumerable<IDeadlineSource> sources, TimeProvider clock, ILogger<DeadlineAggregator> logger) : FeedAggregator
{
/// <summary>How far the widget looks ahead.</summary>
public const int HorizonDays = 30;
/// <summary>The deadlines from today to <see cref="HorizonDays"/> days ahead.</summary>
/// <param name="actor">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The nearest first.</returns>
public async Task<IReadOnlyList<FeedItem>> 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<Task<IReadOnlyList<FeedItem>>>)(() => 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)];
}
}
@@ -0,0 +1,166 @@
using System.Text.Json;
using System.Text.Json.Nodes;
namespace Khaemhat.Application.Dashboard;
/// <summary>A widget on the dashboard: which one and how wide.</summary>
/// <param name="Id">The widget id (<see cref="WidgetIds"/>).</param>
/// <param name="Width">The width in columns of twelve: 3, 4, 6, 8 or 12.</param>
public sealed record WidgetPlacement(string Id, int Width);
/// <summary>
/// The widgets shown, in order, with their width (SPEC §10.3). A widget that is not in the list is switched off.
/// Kept as JSON in <c>user_settings</c> (<c>dashboard.layout</c>) and, as the default of a role, in
/// <c>company_settings</c>: <c>{"v":1,"widgets":[{"id":"todo","w":4}]}</c>.
/// </summary>
/// <param name="Widgets">The widgets in order.</param>
public sealed record DashboardLayout(IReadOnlyList<WidgetPlacement> Widgets)
{
/// <summary>The most widgets a layout keeps.</summary>
public const int MaxWidgets = 30;
private const int Version = 1;
/// <summary>Whether a widget is shown.</summary>
/// <param name="id">The widget id.</param>
/// <returns><see langword="true"/> when it is in the layout.</returns>
public bool Contains(string id) => Widgets.Any(w => w.Id == id);
/// <summary>The width of a widget, or its default when not shown.</summary>
/// <param name="id">The widget id.</param>
/// <returns>The width.</returns>
public int WidthOf(string id) =>
Widgets.FirstOrDefault(w => w.Id == id)?.Width ?? WidgetCatalog.Find(id)?.DefaultWidth ?? 4;
/// <summary>Reads a layout saved as JSON.</summary>
/// <param name="json">The JSON, or <see langword="null"/>.</param>
/// <returns>The layout without unknown widgets, duplicates or invalid widths; <see langword="null"/> when there
/// is none or it cannot be read.</returns>
public static DashboardLayout? Parse(string? json)
{
if (string.IsNullOrWhiteSpace(json))
{
return null;
}
try
{
if (JsonNode.Parse(json) is not JsonObject root || root["widgets"] is not JsonArray array)
{
return null;
}
var widgets = new List<WidgetPlacement>();
foreach (var node in array)
{
if (node is JsonObject item && item["id"]?.GetValueKind() == JsonValueKind.String)
{
var width = item["w"]?.GetValueKind() == JsonValueKind.Number ? item["w"]!.GetValue<int>() : 0;
widgets.Add(new WidgetPlacement(item["id"]!.GetValue<string>(), width));
}
}
return new DashboardLayout(widgets).Normalize();
}
catch (Exception ex) when (ex is JsonException or FormatException or InvalidOperationException)
{
return null;
}
}
/// <summary>The layout as JSON.</summary>
/// <returns>The JSON.</returns>
public string ToJson()
{
var array = new JsonArray();
foreach (var widget in Normalize().Widgets)
{
array.Add(new JsonObject { ["id"] = widget.Id, ["w"] = widget.Width });
}
return new JsonObject { ["v"] = Version, ["widgets"] = array }.ToJsonString();
}
/// <summary>Drops unknown widgets and repeated ones and snaps the widths to the allowed ones.</summary>
/// <returns>The clean layout.</returns>
public DashboardLayout Normalize()
{
var seen = new HashSet<string>(StringComparer.Ordinal);
var widgets = new List<WidgetPlacement>();
foreach (var widget in Widgets)
{
if (WidgetCatalog.Find(widget.Id) is { } definition && seen.Add(widget.Id) && widgets.Count < MaxWidgets)
{
widgets.Add(new WidgetPlacement(definition.Id, widget.Width <= 0 ? definition.DefaultWidth : WidgetDefinition.Snap(widget.Width)));
}
}
return new DashboardLayout(widgets);
}
/// <summary>Only the widgets that pass a test, such as those the user may see.</summary>
/// <param name="keep">The test.</param>
/// <returns>The layout.</returns>
public DashboardLayout Where(Func<string, bool> keep)
{
ArgumentNullException.ThrowIfNull(keep);
return new DashboardLayout([.. Widgets.Where(w => keep(w.Id))]);
}
/// <summary>Shows a widget at the end, or hides it.</summary>
/// <param name="id">The widget id.</param>
/// <param name="visible">Whether to show it.</param>
/// <returns>The layout.</returns>
public DashboardLayout Toggle(string id, bool visible)
{
if (visible == Contains(id) || WidgetCatalog.Find(id) is not { } definition)
{
return this;
}
return visible
? new DashboardLayout([.. Widgets, new WidgetPlacement(id, definition.DefaultWidth)])
: new DashboardLayout([.. Widgets.Where(w => w.Id != id)]);
}
/// <summary>Changes the width of a widget.</summary>
/// <param name="id">The widget id.</param>
/// <param name="width">The new width (snapped to the allowed ones).</param>
/// <returns>The layout.</returns>
public DashboardLayout Resize(string id, int width) =>
new([.. Widgets.Select(w => w.Id == id ? w with { Width = WidgetDefinition.Snap(width) } : w)]);
/// <summary>Moves a widget by some places.</summary>
/// <param name="id">The widget id.</param>
/// <param name="offset">-1 before the previous one, +1 after the next one.</param>
/// <returns>The layout.</returns>
public DashboardLayout Move(string id, int offset)
{
var index = Widgets.ToList().FindIndex(w => w.Id == id);
return index < 0 ? this : MoveTo(id, Math.Clamp(index + offset, 0, Widgets.Count - 1));
}
/// <summary>Moves a widget to a position, as dropping it on another widget does.</summary>
/// <param name="id">The widget id.</param>
/// <param name="index">The new position.</param>
/// <returns>The layout.</returns>
public DashboardLayout MoveTo(string id, int index)
{
var list = Widgets.ToList();
var from = list.FindIndex(w => w.Id == id);
if (from < 0)
{
return this;
}
var widget = list[from];
list.RemoveAt(from);
list.Insert(Math.Clamp(index, 0, list.Count), widget);
return new DashboardLayout(list);
}
/// <summary>Whether two layouts show the same widgets in the same order and widths.</summary>
/// <param name="other">The other layout.</param>
/// <returns><see langword="true"/> when they look the same.</returns>
public bool SameAs(DashboardLayout? other) => other is not null && Widgets.SequenceEqual(other.Widgets);
}
@@ -0,0 +1,284 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Preferences;
using Khaemhat.Application.Security;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Dashboard;
/// <summary>Where the layout shown comes from.</summary>
public enum DashboardLayoutSource
{
/// <summary>The built-in layout of <see cref="WidgetCatalog.BuiltIn"/>.</summary>
BuiltIn = 0,
/// <summary>The default of one of the user's roles.</summary>
Role = 1,
/// <summary>The user's own layout.</summary>
User = 2,
}
/// <summary>The dashboard of a user: the layout and where it comes from.</summary>
/// <param name="Layout">The widgets the user may see, in order.</param>
/// <param name="Source">Where it comes from.</param>
/// <param name="RoleCode">The role whose default is used, when <see cref="Source"/> is <see cref="DashboardLayoutSource.Role"/>.</param>
public sealed record DashboardView(DashboardLayout Layout, DashboardLayoutSource Source, string? RoleCode = null);
/// <summary>A personal reminder of the dashboard.</summary>
/// <param name="Text">What to remember.</param>
/// <param name="Done">Whether it is ticked.</param>
public sealed record PersonalNote(string Text, bool Done);
/// <summary>
/// The dashboard of SPEC §10.3: which widgets a user may see, the layout to show (the user's own, else the default
/// of one of their roles, else the built-in one), the personal reminders and the shortcuts. Everything belongs to the
/// user in <c>user_settings</c>; the role defaults belong to the company in <c>company_settings</c>.
/// </summary>
/// <param name="settings">The user's settings.</param>
/// <param name="company">The company's settings.</param>
/// <param name="factory">Opens the company database, for the roles of a user.</param>
/// <param name="permissions">The user's permissions.</param>
/// <param name="licenses">The licensed modules.</param>
public sealed class DashboardService(
UserSettingsService settings,
CompanySettingsService company,
IUnitOfWorkFactory factory,
PermissionService permissions,
ILicenseGate licenses)
{
/// <summary>The key of the user's layout.</summary>
public const string LayoutKey = "dashboard.layout";
/// <summary>The key of the personal reminders.</summary>
public const string NotesKey = "dashboard.notes";
/// <summary>The key of the shortcuts.</summary>
public const string ShortcutsKey = "dashboard.shortcuts";
/// <summary>The start of the keys of the role defaults in <c>company_settings</c>.</summary>
public const string RolePrefix = "dashboard.layout.role.";
/// <summary>The most reminders kept.</summary>
public const int MaxNotes = 20;
/// <summary>The longest reminder.</summary>
public const int MaxNoteLength = 300;
/// <summary>The most shortcuts kept.</summary>
public const int MaxShortcuts = 12;
/// <summary>The key of the default layout of a role.</summary>
/// <param name="roleCode">The role code.</param>
/// <returns>The key.</returns>
public static string RoleKey(string roleCode) => RolePrefix + roleCode;
/// <summary>The widgets a user may see: licensed module, permission, administrators only.</summary>
/// <param name="actor">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The widgets in catalog order.</returns>
public async Task<IReadOnlyList<WidgetDefinition>> AvailableAsync(Actor actor, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var granted = await permissions.GetAsync(actor, cancellationToken).ConfigureAwait(false);
return [.. WidgetCatalog.All.Where(w =>
licenses.IsModuleActive(w.Module)
&& (!w.InstanceOnly || actor.IsInstanceAccount)
&& (w.Permission is null || granted.Allows(w.Permission)))];
}
/// <summary>The dashboard to show.</summary>
/// <param name="actor">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The layout, limited to the widgets the user may see, and where it comes from.</returns>
public async Task<DashboardView> GetAsync(Actor actor, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var available = (await AvailableAsync(actor, cancellationToken).ConfigureAwait(false)).Select(w => w.Id).ToHashSet(StringComparer.Ordinal);
if (DashboardLayout.Parse(await settings.GetAsync(actor, LayoutKey, cancellationToken).ConfigureAwait(false)) is { } own)
{
return new DashboardView(own.Where(available.Contains), DashboardLayoutSource.User);
}
if (await RoleDefaultAsync(actor, cancellationToken).ConfigureAwait(false) is { } fromRole)
{
return new DashboardView(fromRole.Layout.Where(available.Contains), DashboardLayoutSource.Role, fromRole.RoleCode);
}
return new DashboardView(WidgetCatalog.BuiltIn.Where(available.Contains), DashboardLayoutSource.BuiltIn);
}
/// <summary>Saves the user's layout.</summary>
/// <param name="actor">The user.</param>
/// <param name="layout">The layout.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task SaveAsync(Actor actor, DashboardLayout layout, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(layout);
return settings.SetAsync(actor, LayoutKey, layout.ToJson(), cancellationToken);
}
/// <summary>Forgets the user's layout: the role default or the built-in one comes back.</summary>
/// <param name="actor">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task ResetAsync(Actor actor, CancellationToken cancellationToken = default) =>
settings.SetAsync(actor, LayoutKey, null, cancellationToken);
/// <summary>The roles of the company with their default layout, if they have one.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The roles in name order.</returns>
public async Task<IReadOnlyList<(Role Role, DashboardLayout? Layout)>> RoleDefaultsAsync(string companyCode, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(companyCode);
var defaults = await company.GetAllAsync(companyCode, RolePrefix, cancellationToken).ConfigureAwait(false);
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var roles = (await unitOfWork.Repository<Role, long>().ListAsync(Query.For<Role>(), cancellationToken).ConfigureAwait(false)).Items;
return [.. roles.OrderBy(r => r.Name, StringComparer.CurrentCulture)
.Select(r => (r, defaults.TryGetValue(RoleKey(r.Code), out var json) ? DashboardLayout.Parse(json) : null))];
}
/// <summary>Sets or removes (<see langword="null"/>) the default layout of a role.</summary>
/// <param name="actor">Who sets it: needs <c>company.settings.write</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="roleCode">The role.</param>
/// <param name="layout">The layout, or <see langword="null"/>.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task SaveRoleDefaultAsync(Actor actor, string companyCode, string roleCode, DashboardLayout? layout, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(roleCode);
return company.SetAsync(actor, companyCode, RoleKey(roleCode), layout?.ToJson(), cancellationToken);
}
/// <summary>The personal reminders.</summary>
/// <param name="actor">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The reminders in order.</returns>
public async Task<IReadOnlyList<PersonalNote>> GetNotesAsync(Actor actor, CancellationToken cancellationToken = default)
{
var json = await settings.GetAsync(actor, NotesKey, cancellationToken).ConfigureAwait(false);
var notes = new List<PersonalNote>();
foreach (var node in ReadArray(json))
{
if (node is JsonObject item && item["t"]?.GetValueKind() == JsonValueKind.String)
{
notes.Add(new PersonalNote(item["t"]!.GetValue<string>(), item["d"]?.GetValueKind() == JsonValueKind.True));
}
}
return CleanNotes(notes);
}
/// <summary>Saves the personal reminders (at most <see cref="MaxNotes"/>, each up to <see cref="MaxNoteLength"/> characters).</summary>
/// <param name="actor">The user.</param>
/// <param name="notes">The reminders.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task SaveNotesAsync(Actor actor, IReadOnlyList<PersonalNote> notes, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(notes);
var array = new JsonArray();
foreach (var note in CleanNotes(notes))
{
array.Add(new JsonObject { ["t"] = note.Text, ["d"] = note.Done });
}
return settings.SetAsync(actor, NotesKey, array.Count == 0 ? null : array.ToJsonString(), cancellationToken);
}
/// <summary>The addresses of the shortcut buttons.</summary>
/// <param name="actor">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The addresses in order; <see langword="null"/> when the user never chose them.</returns>
public async Task<IReadOnlyList<string>?> GetShortcutsAsync(Actor actor, CancellationToken cancellationToken = default)
{
var json = await settings.GetAsync(actor, ShortcutsKey, cancellationToken).ConfigureAwait(false);
if (json is null)
{
return null;
}
return CleanShortcuts(ReadArray(json).Where(n => n?.GetValueKind() == JsonValueKind.String).Select(n => n!.GetValue<string>()));
}
/// <summary>Saves the shortcut buttons (local addresses only, at most <see cref="MaxShortcuts"/>).</summary>
/// <param name="actor">The user.</param>
/// <param name="paths">The addresses.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task SaveShortcutsAsync(Actor actor, IReadOnlyList<string> paths, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(paths);
var array = new JsonArray();
foreach (var path in CleanShortcuts(paths))
{
array.Add(path);
}
return settings.SetAsync(actor, ShortcutsKey, array.ToJsonString(), cancellationToken);
}
private static List<PersonalNote> CleanNotes(IEnumerable<PersonalNote> notes) =>
[
.. notes.Select(n => n with { Text = (n.Text ?? string.Empty).Trim() })
.Where(n => n.Text.Length > 0)
.Select(n => n.Text.Length > MaxNoteLength ? n with { Text = n.Text[..MaxNoteLength] } : n)
.Take(MaxNotes),
];
private static List<string> CleanShortcuts(IEnumerable<string> paths) =>
[.. paths.Where(UserPreferences.IsLocalPath).Distinct(StringComparer.OrdinalIgnoreCase).Take(MaxShortcuts)];
private static JsonArray ReadArray(string? json)
{
if (string.IsNullOrWhiteSpace(json))
{
return [];
}
try
{
return JsonNode.Parse(json) as JsonArray ?? [];
}
catch (JsonException)
{
return [];
}
}
// The default of the first of the user's roles (in role order) that has one. Instance accounts have no roles.
private async Task<(DashboardLayout Layout, string RoleCode)?> RoleDefaultAsync(Actor actor, CancellationToken cancellationToken)
{
if (actor.CompanyCode is not { } companyCode || actor.CompanyUserId is not { } userId)
{
return null;
}
var defaults = await company.GetAllAsync(companyCode, RolePrefix, cancellationToken).ConfigureAwait(false);
if (defaults.Count == 0)
{
return null;
}
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var roleIds = (await unitOfWork.Repository<UserRole, long>().ListAsync(Query.For<UserRole>().Where(r => r.UserId == userId), cancellationToken).ConfigureAwait(false))
.Items.Select(r => r.RoleId).ToHashSet();
var roles = (await unitOfWork.Repository<Role, long>().ListAsync(Query.For<Role>(), cancellationToken).ConfigureAwait(false)).Items;
foreach (var role in roles.Where(r => roleIds.Contains(r.Id)).OrderBy(r => r.Id))
{
if (defaults.TryGetValue(RoleKey(role.Code), out var json) && DashboardLayout.Parse(json) is { } layout)
{
return (layout, role.Code);
}
}
return null;
}
}
@@ -0,0 +1,182 @@
using System.Globalization;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Localization;
using Khaemhat.Application.Notifications;
using Khaemhat.Application.Preferences;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Dashboard;
/// <summary>Text keys of the dashboard areas (the label at the side of a line).</summary>
public static class FeedAreas
{
/// <summary>System and administration.</summary>
public const string System = "Dashboard.Areas.System";
/// <summary>Messages for the user.</summary>
public const string Notifications = "Dashboard.Areas.Notifications";
}
/// <summary>
/// The licence on the dashboard of the administrators: the expiry among the deadlines, and renewing it among the
/// things to do once it is near, in grace or expired.
/// </summary>
/// <param name="licenses">The licence in force.</param>
/// <param name="texts">The texts.</param>
public sealed class LicenseFeedSource(ILicenseGate licenses, ITexts texts) : ITodoSource, IDeadlineSource
{
/// <summary>Days before the expiry when renewing becomes a thing to do.</summary>
public const int RenewDays = 7;
private const string Href = "/amministrazione/licenze";
/// <inheritdoc />
public Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
var license = licenses.Current;
if (!context.Actor.IsInstanceAccount || license.IsTestMode)
{
return Task.FromResult<IReadOnlyList<FeedItem>>([]);
}
var days = license.DaysLeft(context.Now.UtcDateTime);
FeedItem? item = license.Status switch
{
LicenseStatus.Expired => new FeedItem("license", texts["Dashboard.Feed.LicenseExpired"], FeedAreas.System, FeedTone.Error) { Priority = 100, Href = Href },
LicenseStatus.Grace => new FeedItem("license", texts["Dashboard.Feed.LicenseGrace"], FeedAreas.System, FeedTone.Error) { Priority = 90, Href = Href },
_ when days is { } left && left <= RenewDays => new FeedItem("license", texts.Format("Dashboard.Feed.LicenseRenew", left), FeedAreas.System, FeedTone.Warning)
{
Priority = 50,
Href = Href,
},
_ => null,
};
return Task.FromResult<IReadOnlyList<FeedItem>>(item is null ? [] : [item]);
}
/// <inheritdoc />
public Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, DateOnly until, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
var license = licenses.Current;
if (!context.Actor.IsInstanceAccount || license.IsTestMode || license.ExpiresAt is not { } expires || license.Status != LicenseStatus.Valid)
{
return Task.FromResult<IReadOnlyList<FeedItem>>([]);
}
var when = new DateTimeOffset(DateTime.SpecifyKind(expires, DateTimeKind.Utc)).ToOffset(context.Now.Offset);
if (DateOnly.FromDateTime(when.DateTime) > until)
{
return Task.FromResult<IReadOnlyList<FeedItem>>([]);
}
var key = license.Kind == LicenseKind.Trial ? "Dashboard.Feed.TrialEnds" : "Dashboard.Feed.LicenseEnds";
var near = license.DaysLeft(context.Now.UtcDateTime) <= RenewDays;
return Task.FromResult<IReadOnlyList<FeedItem>>(
[
new FeedItem("license-expiry", texts[key], FeedAreas.System, near ? FeedTone.Warning : FeedTone.Info) { When = when, Href = Href },
]);
}
}
/// <summary>The unread warnings and errors addressed to the user, until they are read.</summary>
/// <param name="notifications">The notifications.</param>
public sealed class NotificationTodoSource(NotificationDispatcher notifications) : ITodoSource
{
/// <inheritdoc />
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),
_ => [],
};
return [.. unread
.Where(n => n.Severity >= NotificationSeverity.Warning)
.Select(n => new FeedItem("notification-" + n.Id.ToString(CultureInfo.InvariantCulture), n.Title, FeedAreas.Notifications,
n.Severity == NotificationSeverity.Warning ? FeedTone.Warning : FeedTone.Error)
{
Detail = n.Body,
Href = UserPreferences.IsLocalPath(n.Link) ? n.Link : null,
Priority = n.Severity == NotificationSeverity.Warning ? 60 : 80,
When = new DateTimeOffset(DateTime.SpecifyKind(n.CreatedAt, DateTimeKind.Utc)).ToOffset(context.Now.Offset),
})];
}
}
/// <summary>
/// The scheduled tasks of today for the administrators: those that ran fine among the things done (one line per task),
/// those that failed among the things to do.
/// </summary>
/// <param name="factory">Opens the system database.</param>
/// <param name="texts">The texts.</param>
public sealed class JobRunFeedSource(IUnitOfWorkFactory factory, ITexts texts) : IDoneSource, ITodoSource
{
private const string Href = "/amministrazione/attivita";
/// <inheritdoc />
async Task<IReadOnlyList<FeedItem>> IDoneSource.GetAsync(FeedContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
if (!context.Actor.IsInstanceAccount)
{
return [];
}
var (runs, names) = await TodayAsync(context, cancellationToken).ConfigureAwait(false);
return [.. runs
.Where(r => r.Outcome == JobOutcome.Succeeded)
.GroupBy(r => r.TaskCode, StringComparer.Ordinal)
.Select(g =>
{
var last = g.MaxBy(r => r.FinishedAt ?? r.StartedAt)!;
var when = Local(last.FinishedAt ?? last.StartedAt, context);
// The widget shows the time of the last run at the side: the detail says how many.
var detail = g.Count() == 1 ? texts["Dashboard.Feed.JobRanOnce"] : texts.Format("Dashboard.Feed.JobRanTimes", g.Count());
return new FeedItem("job-" + g.Key, names.GetValueOrDefault(g.Key, g.Key), FeedAreas.System, FeedTone.Ok) { Detail = detail, When = when, Href = Href };
})];
}
/// <inheritdoc />
async Task<IReadOnlyList<FeedItem>> ITodoSource.GetAsync(FeedContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
if (!context.Actor.IsInstanceAccount)
{
return [];
}
var (runs, names) = await TodayAsync(context, cancellationToken).ConfigureAwait(false);
// A task that failed and has not succeeded since is still a thing to do.
return [.. runs
.GroupBy(r => r.TaskCode, StringComparer.Ordinal)
.Select(g => g.MaxBy(r => r.StartedAt)!)
.Where(r => r.Outcome == JobOutcome.Failed)
.Select(r => new FeedItem("job-failed-" + r.TaskCode, texts.Format("Dashboard.Feed.JobFailed", names.GetValueOrDefault(r.TaskCode, r.TaskCode)), FeedAreas.System, FeedTone.Error)
{
Detail = r.Message,
When = Local(r.StartedAt, context),
Href = Href,
Priority = 70,
})];
}
private static DateTimeOffset Local(DateTime utc, FeedContext context) =>
new DateTimeOffset(DateTime.SpecifyKind(utc, DateTimeKind.Utc)).ToOffset(context.Now.Offset);
private async Task<(IReadOnlyList<JobRun> Runs, IReadOnlyDictionary<string, string> Names)> TodayAsync(FeedContext context, CancellationToken cancellationToken)
{
var since = context.StartOfToday.UtcDateTime;
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var runs = (await unitOfWork.Repository<JobRun, long>().ListAsync(Query.For<JobRun>().Where(r => r.StartedAt >= since), cancellationToken).ConfigureAwait(false)).Items;
var tasks = (await unitOfWork.Repository<ScheduledTask, long>().ListAsync(Query.For<ScheduledTask>(), cancellationToken).ConfigureAwait(false)).Items;
return (runs, tasks.ToDictionary(t => t.Code, t => t.Name, StringComparer.Ordinal));
}
}
@@ -0,0 +1,42 @@
using Khaemhat.Application.Instance;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Dashboard;
/// <summary>What the <em>Stato del sistema</em> widget shows besides version, cache and licence.</summary>
/// <param name="Engine">The database engine.</param>
/// <param name="Companies">The companies that are not disabled.</param>
/// <param name="FailedCompanies">Those that failed to open at start-up.</param>
/// <param name="JobsSucceeded">Scheduled task runs of today that succeeded.</param>
/// <param name="JobsFailed">Those that failed.</param>
public sealed record SystemStatus(DbEngine Engine, int Companies, int FailedCompanies, int JobsSucceeded, int JobsFailed);
/// <summary>Reads the state of the instance for the administrators' widget.</summary>
/// <param name="factory">Opens the system database.</param>
/// <param name="system">The system database.</param>
/// <param name="companies">The companies.</param>
/// <param name="bootstrap">What happened at start-up.</param>
/// <param name="clock">The clock.</param>
public sealed class SystemStatusService(IUnitOfWorkFactory factory, DatabaseTarget system, ICompanyRegistry companies, BootstrapState bootstrap, TimeProvider clock)
{
/// <summary>The state now.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The state.</returns>
public async Task<SystemStatus> GetAsync(CancellationToken cancellationToken = default)
{
var all = await companies.ListAsync(cancellationToken).ConfigureAwait(false);
var now = clock.GetLocalNow();
var since = new DateTimeOffset(now.Date, now.Offset).UtcDateTime;
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var runs = (await unitOfWork.Repository<JobRun, long>().ListAsync(Query.For<JobRun>().Where(r => r.StartedAt >= since), cancellationToken).ConfigureAwait(false)).Items;
return new SystemStatus(
system.Engine,
all.Count(c => c.Status != CompanyStatus.Disabled),
bootstrap.FailedCompanies.Count,
runs.Count(r => r.Outcome == JobOutcome.Succeeded),
runs.Count(r => r.Outcome == JobOutcome.Failed));
}
}
@@ -0,0 +1,132 @@
using Khaemhat.Application.Modules;
namespace Khaemhat.Application.Dashboard;
/// <summary>
/// A widget of the dashboard (SPEC §10.3, mockup 004): what it is, how wide it starts and who may see it. The
/// <see cref="Milestone"/> of a widget whose data comes from a later module says where its data will come from; until
/// then the widget shows that instead of invented numbers.
/// </summary>
/// <param name="Id">The id, kept in the layouts.</param>
/// <param name="TitleKey">The text key of the title.</param>
/// <param name="Icon">The icon.</param>
/// <param name="DefaultWidth">The starting width in columns of twelve.</param>
/// <param name="Module">The licensed module it needs.</param>
/// <param name="Permission">The permission it needs, if any.</param>
/// <param name="InstanceOnly">Only for administrators of the instance.</param>
/// <param name="Milestone">The milestone that brings its data, if still to come.</param>
public sealed record WidgetDefinition(
string Id,
string TitleKey,
string Icon,
int DefaultWidth,
string Module,
string? Permission = null,
bool InstanceOnly = false,
string? Milestone = null)
{
/// <summary>The widths a widget can take, in columns of twelve.</summary>
public static readonly IReadOnlyList<int> Widths = [3, 4, 6, 8, 12];
/// <summary>The text key of the description shown in the customize panel.</summary>
public string DescriptionKey => TitleKey[..TitleKey.LastIndexOf('.')] + ".Description";
/// <summary>The nearest allowed width.</summary>
/// <param name="width">Any number.</param>
/// <returns>One of <see cref="Widths"/>.</returns>
public static int Snap(int width) => Widths.OrderBy(w => Math.Abs(w - width)).ThenByDescending(w => w).First();
/// <summary>The next width up or down, staying at the ends.</summary>
/// <param name="width">The current width.</param>
/// <param name="step">+1 wider, -1 narrower.</param>
/// <returns>The width.</returns>
public static int Step(int width, int step)
{
var index = Math.Clamp(Widths.ToList().IndexOf(Snap(width)) + Math.Sign(step), 0, Widths.Count - 1);
return Widths[index];
}
}
/// <summary>The ids of the widgets.</summary>
public static class WidgetIds
{
/// <summary>Indicators chosen by the user.</summary>
public const string Kpi = "kpi";
/// <summary>What to do today.</summary>
public const string Todo = "todo";
/// <summary>What was done today.</summary>
public const string Done = "done";
/// <summary>Deadlines of the next 30 days.</summary>
public const string Deadlines = "deadlines";
/// <summary>Orders and delivery notes still to fulfil.</summary>
public const string ToFulfil = "to-fulfil";
/// <summary>Revenue of the last 12 months.</summary>
public const string Revenue = "revenue";
/// <summary>CRM activities.</summary>
public const string CrmActivities = "crm-activities";
/// <summary>Personal reminders.</summary>
public const string Notes = "notes";
/// <summary>Shortcut buttons.</summary>
public const string Shortcuts = "shortcuts";
/// <summary>Items under the minimum stock.</summary>
public const string Understock = "understock";
/// <summary>The CRM pipeline.</summary>
public const string Pipeline = "pipeline";
/// <summary>The last documents.</summary>
public const string RecentDocuments = "recent-documents";
/// <summary>State of the system (administrators).</summary>
public const string SystemStatus = "system";
}
/// <summary>Every widget, in the order of the customize panel (SPEC §10.3).</summary>
public static class WidgetCatalog
{
/// <summary>The widgets.</summary>
public static IReadOnlyList<WidgetDefinition> All { get; } =
[
new(WidgetIds.Kpi, "Dashboard.Widgets.Kpi.Title", "chart", 12, ModuleCodes.Core, "sales.invoice.read", Milestone: "M5"),
new(WidgetIds.Todo, "Dashboard.Widgets.Todo.Title", "check-circle", 4, ModuleCodes.Core),
new(WidgetIds.Done, "Dashboard.Widgets.Done.Title", "check", 4, ModuleCodes.Core),
new(WidgetIds.Deadlines, "Dashboard.Widgets.Deadlines.Title", "calendar", 4, ModuleCodes.Core),
new(WidgetIds.ToFulfil, "Dashboard.Widgets.ToFulfil.Title", "truck", 8, ModuleCodes.Core, "sales.order.read", Milestone: "M5"),
new(WidgetIds.Revenue, "Dashboard.Widgets.Revenue.Title", "chart", 4, ModuleCodes.Core, "sales.invoice.read", Milestone: "M5"),
new(WidgetIds.CrmActivities, "Dashboard.Widgets.CrmActivities.Title", "target", 6, ModuleCodes.Crm, "crm.lead.read", Milestone: "M11"),
new(WidgetIds.Notes, "Dashboard.Widgets.Notes.Title", "edit", 4, ModuleCodes.Core),
new(WidgetIds.Shortcuts, "Dashboard.Widgets.Shortcuts.Title", "zap", 4, ModuleCodes.Core),
new(WidgetIds.Understock, "Dashboard.Widgets.Understock.Title", "box", 6, ModuleCodes.Core, "inventory.stock.read", Milestone: "M6"),
new(WidgetIds.Pipeline, "Dashboard.Widgets.Pipeline.Title", "target", 6, ModuleCodes.Crm, "crm.lead.read", Milestone: "M11"),
new(WidgetIds.RecentDocuments, "Dashboard.Widgets.RecentDocuments.Title", "file", 6, ModuleCodes.Core, "sales.invoice.read", Milestone: "M5"),
new(WidgetIds.SystemStatus, "Dashboard.Widgets.System.Title", "shield", 4, ModuleCodes.Core, InstanceOnly: true),
];
/// <summary>
/// The layout of whoever never customized it and has no default from a role: the widgets that already have data.
/// Those that wait for a later module stay in the panel, ready to be switched on.
/// </summary>
public static DashboardLayout BuiltIn { get; } = new(
[
new(WidgetIds.Todo, 4),
new(WidgetIds.Done, 4),
new(WidgetIds.Deadlines, 4),
new(WidgetIds.Shortcuts, 4),
new(WidgetIds.Notes, 4),
new(WidgetIds.SystemStatus, 4),
]);
/// <summary>Finds a widget.</summary>
/// <param name="id">The id.</param>
/// <returns>The widget, or <see langword="null"/>.</returns>
public static WidgetDefinition? Find(string? id) => All.FirstOrDefault(w => string.Equals(w.Id, id, StringComparison.Ordinal));
}
@@ -0,0 +1,126 @@
using Khaemhat.Application.Security;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Instance;
/// <summary>
/// Reads and writes the preferences of a company as a whole (<c>company_settings</c>, SPEC §11.12): the default
/// dashboard of each role today, the company options of the later modules tomorrow. Reading is open to the company
/// code (the callers check what they show); writing needs <c>company.settings.write</c>.
/// </summary>
/// <param name="factory">Opens the databases.</param>
/// <param name="permissions">Checks the permission to write.</param>
public sealed class CompanySettingsService(IUnitOfWorkFactory factory, PermissionService permissions)
{
/// <summary>The permission to change the settings.</summary>
public const string WritePermission = "company.settings.write";
/// <summary>The longest value accepted (layouts are JSON).</summary>
public const int MaxValueLength = 64 * 1024;
/// <summary>Reads the settings of a company, all or those whose key starts with a prefix.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="prefix">The start of the keys, or <see langword="null"/> for all.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The values by key.</returns>
public async Task<IReadOnlyDictionary<string, string?>> GetAllAsync(string companyCode, string? prefix = null, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(companyCode);
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var rows = await ListAsync(unitOfWork, cancellationToken).ConfigureAwait(false);
return rows.Where(r => prefix is null || r.Key.StartsWith(prefix, StringComparison.Ordinal))
.ToDictionary(r => r.Key, r => r.Value, StringComparer.Ordinal);
}
/// <summary>Reads one setting.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="key">The key.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The value, or <see langword="null"/>.</returns>
public async Task<string?> GetAsync(string companyCode, string key, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(key);
var all = await GetAllAsync(companyCode, key, cancellationToken).ConfigureAwait(false);
return all.TryGetValue(key, out var value) ? value : null;
}
/// <summary>Writes one setting; <see langword="null"/> removes it.</summary>
/// <param name="actor">Who writes: needs <see cref="WritePermission"/> in that company.</param>
/// <param name="companyCode">The company.</param>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task SetAsync(Actor actor, string companyCode, string key, string? value, CancellationToken cancellationToken = default) =>
SetManyAsync(actor, companyCode, new Dictionary<string, string?>(StringComparer.Ordinal) { [key] = value }, cancellationToken);
/// <summary>Writes several settings in one transaction; <see langword="null"/> values remove the key.</summary>
/// <param name="actor">Who writes: needs <see cref="WritePermission"/> in that company.</param>
/// <param name="companyCode">The company.</param>
/// <param name="values">The values by key.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
/// <exception cref="AccessDeniedException">The actor may not change this company's settings.</exception>
public async Task SetManyAsync(Actor actor, string companyCode, IReadOnlyDictionary<string, string?> values, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentException.ThrowIfNullOrWhiteSpace(companyCode);
ArgumentNullException.ThrowIfNull(values);
if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, companyCode, StringComparison.OrdinalIgnoreCase))
{
throw new AccessDeniedException("Settings of another company.");
}
await permissions.DemandAsync(actor, WritePermission, cancellationToken).ConfigureAwait(false);
foreach (var (key, value) in values)
{
if (string.IsNullOrWhiteSpace(key) || key.Length > 200)
{
throw new ValidationFailedException("settings.key_invalid");
}
if (value is { Length: > MaxValueLength })
{
throw new ValidationFailedException("settings.value_too_long");
}
}
if (values.Count == 0)
{
return;
}
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
await unitOfWork.InTransactionAsync(ct => WriteAsync(unitOfWork, values, ct), cancellationToken).ConfigureAwait(false);
}
private static async Task<IReadOnlyList<CompanySetting>> ListAsync(IUnitOfWork unitOfWork, CancellationToken cancellationToken) =>
(await unitOfWork.Repository<CompanySetting, long>().ListAsync(Query.For<CompanySetting>(), cancellationToken).ConfigureAwait(false)).Items;
private static async Task WriteAsync(IUnitOfWork unitOfWork, IReadOnlyDictionary<string, string?> values, CancellationToken cancellationToken)
{
var repository = unitOfWork.Repository<CompanySetting, long>();
var existing = (await ListAsync(unitOfWork, cancellationToken).ConfigureAwait(false)).ToDictionary(r => r.Key, StringComparer.Ordinal);
foreach (var (key, value) in values)
{
if (existing.TryGetValue(key, out var row))
{
if (value is null)
{
await repository.DeleteAsync(row.Id, cancellationToken).ConfigureAwait(false);
}
else if (!string.Equals(row.Value, value, StringComparison.Ordinal))
{
row.Value = value;
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
}
}
else if (value is not null)
{
await repository.InsertAsync(new CompanySetting { Key = key, Value = value }, cancellationToken).ConfigureAwait(false);
}
}
}
}