feat: application shell, localized texts and user preferences (M3, part 1)
The pages built so far now live inside the shell of the mockups instead of the M0 placeholder, every interface text comes from Resources/it-IT, and each user keeps their own look and start page. - Shell: top bar, collapsible side menu with fly-out sub-menus, status bar and tabs that keep each page alive (page type and route values per tab, so a tab never shows another page); at most 12 tabs, least-used clean tab evicted. - One shortcut table with Alt variants for the combinations browsers keep (Ctrl+W, Ctrl+Tab, Ctrl+N); command palette for pages and commands. - ITexts over embedded JSON; tests forbid literal texts in .razor components and check that every key used exists. - User settings in sys_user_settings / user_settings; theme written on the server; profile page with live preview, start page, sessions and shortcuts. - Home, coming-soon pages for later milestones, localized sign-in and error pages; ADR 0020; wiki, CHANGELOG, STATUS and data model updated. Refs #25 #26 #31 #33 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1c30054e3d
commit
cf6f849cc1
72 files changed
+5785
-259
No files matched your search
@@ -0,0 +1,189 @@
|
||||
using System.Collections.Frozen;
|
||||
using System.Globalization;
|
||||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Khaemhat.Application.Localization;
|
||||
|
||||
/// <summary>
|
||||
/// The texts of the interface (SPEC §1.9, §10.8): keys such as <c>Shell.Menu.Home</c> resolved from
|
||||
/// <c>Resources/<culture>/*.json</c>. Components never contain literal texts; they ask this service.
|
||||
/// </summary>
|
||||
public interface ITexts
|
||||
{
|
||||
/// <summary>The culture of the texts and of number and date formats.</summary>
|
||||
CultureInfo Culture { get; }
|
||||
|
||||
/// <summary>The text of a key; a missing key gives <c>[key]</c>, visible in the page and caught by the tests.</summary>
|
||||
/// <param name="key">The key, <c>Area.Entity.Text</c>.</param>
|
||||
/// <returns>The text.</returns>
|
||||
string this[string key] { get; }
|
||||
|
||||
/// <summary>The text of a key with <see cref="string.Format(IFormatProvider, string, object[])"/> placeholders filled in the culture.</summary>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <param name="args">The values for <c>{0}</c>, <c>{1}</c>...</param>
|
||||
/// <returns>The text.</returns>
|
||||
string Format(string key, params object?[] args);
|
||||
|
||||
/// <summary>Whether a key exists.</summary>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <returns><see langword="true"/> when it has a text.</returns>
|
||||
bool Contains(string key);
|
||||
|
||||
/// <summary>Every key, for the tests and the documentation.</summary>
|
||||
IReadOnlyCollection<string> Keys { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the texts from JSON files. Nested objects become dotted keys: <c>{"Shell": {"Menu": {"Home": "Home"}}}</c>
|
||||
/// gives <c>Shell.Menu.Home</c>; the property <c>_</c> gives a text to an object that also has children. The file
|
||||
/// name is not part of the key; two files defining the same key are an error.
|
||||
/// </summary>
|
||||
public sealed class JsonTextProvider : ITexts
|
||||
{
|
||||
/// <summary>The prefix of the embedded resources holding the texts: <c>texts/it-IT/Shell.json</c>.</summary>
|
||||
public const string ResourcePrefix = "texts/";
|
||||
|
||||
private readonly FrozenDictionary<string, string> _texts;
|
||||
|
||||
/// <summary>Creates the provider from JSON documents.</summary>
|
||||
/// <param name="culture">The culture.</param>
|
||||
/// <param name="documents">The documents, by name (used in error messages).</param>
|
||||
public JsonTextProvider(CultureInfo culture, IEnumerable<KeyValuePair<string, string>> documents)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(culture);
|
||||
ArgumentNullException.ThrowIfNull(documents);
|
||||
Culture = culture;
|
||||
var texts = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var (name, json) in documents)
|
||||
{
|
||||
using var document = JsonDocument.Parse(json, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true });
|
||||
if (document.RootElement.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
throw new InvalidDataException($"The texts file {name} must contain an object.");
|
||||
}
|
||||
|
||||
Flatten(document.RootElement, string.Empty, name, texts);
|
||||
}
|
||||
|
||||
_texts = texts.ToFrozenDictionary(StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public CultureInfo Culture { get; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyCollection<string> Keys => _texts.Keys;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string this[string key] => key is not null && _texts.TryGetValue(key, out var text) ? text : "[" + key + "]";
|
||||
|
||||
/// <summary>Loads the texts of a culture from the embedded resources of an assembly (<see cref="ResourcePrefix"/>).</summary>
|
||||
/// <param name="assembly">The assembly, usually the web project.</param>
|
||||
/// <param name="culture">The culture, for example <c>it-IT</c>.</param>
|
||||
/// <returns>The provider.</returns>
|
||||
public static JsonTextProvider FromAssembly(Assembly assembly, CultureInfo culture)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(assembly);
|
||||
ArgumentNullException.ThrowIfNull(culture);
|
||||
var prefix = ResourcePrefix + culture.Name + "/";
|
||||
var documents = new List<KeyValuePair<string, string>>();
|
||||
foreach (var resource in assembly.GetManifestResourceNames().Order(StringComparer.Ordinal))
|
||||
{
|
||||
var name = resource.Replace('\\', '/');
|
||||
if (!name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) || !name.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
using var stream = assembly.GetManifestResourceStream(resource)!;
|
||||
using var reader = new StreamReader(stream);
|
||||
documents.Add(new(name, reader.ReadToEnd()));
|
||||
}
|
||||
|
||||
if (documents.Count == 0)
|
||||
{
|
||||
throw new InvalidOperationException($"No texts for {culture.Name} in {assembly.GetName().Name}.");
|
||||
}
|
||||
|
||||
return new JsonTextProvider(culture, documents);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Format(string key, params object?[] args) => string.Format(Culture, this[key], args);
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool Contains(string key) => key is not null && _texts.ContainsKey(key);
|
||||
|
||||
private static void Flatten(JsonElement element, string prefix, string file, Dictionary<string, string> texts)
|
||||
{
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
// "_" gives a text to the object itself: {"Menu": {"Parties": {"_": "Anagrafiche", "Customers": "Clienti"}}}.
|
||||
var key = property.Name == "_" && prefix.Length > 0 ? prefix : prefix.Length == 0 ? property.Name : prefix + "." + property.Name;
|
||||
switch (property.Value.ValueKind)
|
||||
{
|
||||
case JsonValueKind.Object:
|
||||
Flatten(property.Value, key, file, texts);
|
||||
break;
|
||||
case JsonValueKind.String:
|
||||
if (!texts.TryAdd(key, property.Value.GetString()!))
|
||||
{
|
||||
throw new InvalidDataException($"The text {key} is defined twice ({file}).");
|
||||
}
|
||||
|
||||
break;
|
||||
default:
|
||||
throw new InvalidDataException($"The text {key} in {file} must be a string or an object.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Number, money and date formats of the interface, in the culture of <see cref="ITexts"/> (SPEC §10.8).</summary>
|
||||
public static class TextFormats
|
||||
{
|
||||
/// <summary>An amount in euro: <c>€ 1.234,50</c>.</summary>
|
||||
/// <param name="texts">The texts.</param>
|
||||
/// <param name="amount">The amount.</param>
|
||||
/// <returns>The text.</returns>
|
||||
public static string Money(this ITexts texts, decimal amount)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(texts);
|
||||
return "€ " + amount.ToString("#,##0.00", texts.Culture);
|
||||
}
|
||||
|
||||
/// <summary>A number with a fixed count of decimals: <c>1.234,5</c>.</summary>
|
||||
/// <param name="texts">The texts.</param>
|
||||
/// <param name="value">The value.</param>
|
||||
/// <param name="decimals">The decimals.</param>
|
||||
/// <returns>The text.</returns>
|
||||
public static string Number(this ITexts texts, decimal value, int decimals = 0)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(texts);
|
||||
return value.ToString("N" + decimals.ToString(CultureInfo.InvariantCulture), texts.Culture);
|
||||
}
|
||||
|
||||
/// <summary>A date: <c>13/10/2026</c>.</summary>
|
||||
/// <param name="texts">The texts.</param>
|
||||
/// <param name="date">The date.</param>
|
||||
/// <returns>The text.</returns>
|
||||
public static string Date(this ITexts texts, DateOnly date)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(texts);
|
||||
return date.ToString("dd/MM/yyyy", texts.Culture);
|
||||
}
|
||||
|
||||
/// <summary>A date and time in the given time zone: <c>13/10/2026 14:05</c>.</summary>
|
||||
/// <param name="texts">The texts.</param>
|
||||
/// <param name="utc">The moment, in UTC.</param>
|
||||
/// <param name="zone">The time zone of the user.</param>
|
||||
/// <returns>The text.</returns>
|
||||
public static string DateTime(this ITexts texts, DateTime utc, TimeZoneInfo zone)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(texts);
|
||||
ArgumentNullException.ThrowIfNull(zone);
|
||||
var local = TimeZoneInfo.ConvertTimeFromUtc(System.DateTime.SpecifyKind(utc, DateTimeKind.Utc), zone);
|
||||
return local.ToString("dd/MM/yyyy HH:mm", texts.Culture);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace Khaemhat.Application.Preferences;
|
||||
|
||||
/// <summary>The colour theme (SPEC §10.6). <see cref="Auto"/> follows the operating system.</summary>
|
||||
public enum ThemeMode
|
||||
{
|
||||
/// <summary>Follows the operating system.</summary>
|
||||
Auto = 0,
|
||||
|
||||
/// <summary>Light.</summary>
|
||||
Light = 1,
|
||||
|
||||
/// <summary>Dark ("notturno").</summary>
|
||||
Dark = 2,
|
||||
|
||||
/// <summary>High contrast (AAA).</summary>
|
||||
HighContrast = 3,
|
||||
}
|
||||
|
||||
/// <summary>The row height and spacing of lists and forms.</summary>
|
||||
public enum Density
|
||||
{
|
||||
/// <summary>The default spacing.</summary>
|
||||
Comfortable = 0,
|
||||
|
||||
/// <summary>Shorter rows and smaller gaps.</summary>
|
||||
Compact = 1,
|
||||
}
|
||||
|
||||
/// <summary>What the user sees after signing in (SPEC §10.3).</summary>
|
||||
public enum StartPage
|
||||
{
|
||||
/// <summary>The dashboard.</summary>
|
||||
Dashboard = 0,
|
||||
|
||||
/// <summary>The tab that was active at the last sign-out.</summary>
|
||||
LastTab = 1,
|
||||
|
||||
/// <summary>A page chosen by the user (<see cref="UserPreferences.StartPath"/>).</summary>
|
||||
Page = 2,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The interface preferences of a user (SPEC §10.6, mockup 008), stored as key/value pairs in <c>user_settings</c>
|
||||
/// (company users) or <c>sys_user_settings</c> (instance accounts).
|
||||
/// </summary>
|
||||
public sealed record UserPreferences
|
||||
{
|
||||
/// <summary>The eight accents of <c>mockup.css</c>; <c>nilo</c> is the default.</summary>
|
||||
public static readonly IReadOnlyList<string> Accents = ["nilo", "lapislazzuli", "malachite", "turchese", "ocra", "corniola", "ametista", "grafite"];
|
||||
|
||||
/// <summary>The text sizes offered, in percent of the base size.</summary>
|
||||
public static readonly IReadOnlyList<int> TextSizes = [100, 110, 120];
|
||||
|
||||
/// <summary>The preferences of a new user.</summary>
|
||||
public static UserPreferences Default { get; } = new();
|
||||
|
||||
/// <summary>The theme.</summary>
|
||||
public ThemeMode Theme { get; init; } = ThemeMode.Auto;
|
||||
|
||||
/// <summary>The accent, one of <see cref="Accents"/>.</summary>
|
||||
public string Accent { get; init; } = "nilo";
|
||||
|
||||
/// <summary>The density.</summary>
|
||||
public Density Density { get; init; } = Density.Comfortable;
|
||||
|
||||
/// <summary>The text size in percent, one of <see cref="TextSizes"/>.</summary>
|
||||
public int TextSize { get; init; } = 100;
|
||||
|
||||
/// <summary>Whether numbers use tabular figures everywhere (grids always do).</summary>
|
||||
public bool TabularNumbers { get; init; } = true;
|
||||
|
||||
/// <summary>Whether animations and transitions are turned off.</summary>
|
||||
public bool ReducedMotion { get; init; }
|
||||
|
||||
/// <summary>Whether tooltips appear on hover.</summary>
|
||||
public bool Tooltips { get; init; } = true;
|
||||
|
||||
/// <summary>Whether the grid row under the pointer is highlighted.</summary>
|
||||
public bool RowHover { get; init; } = true;
|
||||
|
||||
/// <summary>Whether the side menu is collapsed; <see langword="null"/> lets the window width decide (collapsed under 1100 px).</summary>
|
||||
public bool? MenuCollapsed { get; init; }
|
||||
|
||||
/// <summary>Whether the dashboard is shown on the home page.</summary>
|
||||
public bool ShowDashboard { get; init; } = true;
|
||||
|
||||
/// <summary>The page opened after signing in.</summary>
|
||||
public StartPage StartPage { get; init; } = StartPage.Dashboard;
|
||||
|
||||
/// <summary>The address opened when <see cref="StartPage"/> is <see cref="Preferences.StartPage.Page"/>.</summary>
|
||||
public string? StartPath { get; init; }
|
||||
|
||||
/// <summary>The value of <c>data-theme</c> on the root element.</summary>
|
||||
public string ThemeAttribute => ThemeName(Theme);
|
||||
|
||||
/// <summary>The value of <c>data-density</c> on the root element.</summary>
|
||||
public string DensityAttribute => Density == Density.Compact ? "compact" : "comfortable";
|
||||
|
||||
/// <summary>The attribute value of a theme.</summary>
|
||||
/// <param name="theme">The theme.</param>
|
||||
/// <returns><c>auto</c>, <c>light</c>, <c>dark</c> or <c>high-contrast</c>.</returns>
|
||||
public static string ThemeName(ThemeMode theme) => theme switch
|
||||
{
|
||||
ThemeMode.Light => "light",
|
||||
ThemeMode.Dark => "dark",
|
||||
ThemeMode.HighContrast => "high-contrast",
|
||||
_ => "auto",
|
||||
};
|
||||
|
||||
/// <summary>Reads a theme name; unknown values give <see cref="ThemeMode.Auto"/>.</summary>
|
||||
/// <param name="value">The name.</param>
|
||||
/// <returns>The theme.</returns>
|
||||
public static ThemeMode ParseTheme(string? value) => value switch
|
||||
{
|
||||
"light" => ThemeMode.Light,
|
||||
"dark" => ThemeMode.Dark,
|
||||
"high-contrast" => ThemeMode.HighContrast,
|
||||
_ => ThemeMode.Auto,
|
||||
};
|
||||
|
||||
/// <summary>Reads the preferences from stored values; missing or invalid values keep the default.</summary>
|
||||
/// <param name="values">The stored values by key.</param>
|
||||
/// <returns>The preferences.</returns>
|
||||
public static UserPreferences FromSettings(IReadOnlyDictionary<string, string?> values)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(values);
|
||||
var d = Default;
|
||||
return new UserPreferences
|
||||
{
|
||||
Theme = values.TryGetValue(PreferenceKeys.Theme, out var theme) ? ParseTheme(theme) : d.Theme,
|
||||
Accent = values.TryGetValue(PreferenceKeys.Accent, out var accent) && accent is not null && Accents.Contains(accent) ? accent : d.Accent,
|
||||
Density = values.TryGetValue(PreferenceKeys.Density, out var density) && density == "compact" ? Density.Compact : d.Density,
|
||||
TextSize = values.TryGetValue(PreferenceKeys.TextSize, out var size)
|
||||
&& int.TryParse(size, NumberStyles.None, CultureInfo.InvariantCulture, out var s) && TextSizes.Contains(s) ? s : d.TextSize,
|
||||
TabularNumbers = Bool(values, PreferenceKeys.TabularNumbers) ?? d.TabularNumbers,
|
||||
ReducedMotion = Bool(values, PreferenceKeys.ReducedMotion) ?? d.ReducedMotion,
|
||||
Tooltips = Bool(values, PreferenceKeys.Tooltips) ?? d.Tooltips,
|
||||
RowHover = Bool(values, PreferenceKeys.RowHover) ?? d.RowHover,
|
||||
MenuCollapsed = Bool(values, PreferenceKeys.MenuCollapsed),
|
||||
ShowDashboard = Bool(values, PreferenceKeys.ShowDashboard) ?? d.ShowDashboard,
|
||||
StartPage = values.TryGetValue(PreferenceKeys.StartPage, out var start)
|
||||
? start switch
|
||||
{
|
||||
"last-tab" => StartPage.LastTab,
|
||||
"page" => StartPage.Page,
|
||||
_ => StartPage.Dashboard,
|
||||
}
|
||||
: d.StartPage,
|
||||
StartPath = values.TryGetValue(PreferenceKeys.StartPath, out var path) && IsLocalPath(path) ? path : null,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The values to store.</summary>
|
||||
/// <returns>The values by key; <see langword="null"/> removes the key.</returns>
|
||||
public IReadOnlyDictionary<string, string?> ToSettings() => new Dictionary<string, string?>(StringComparer.Ordinal)
|
||||
{
|
||||
[PreferenceKeys.Theme] = ThemeAttribute,
|
||||
[PreferenceKeys.Accent] = Accents.Contains(Accent) ? Accent : Default.Accent,
|
||||
[PreferenceKeys.Density] = DensityAttribute,
|
||||
[PreferenceKeys.TextSize] = TextSize.ToString(CultureInfo.InvariantCulture),
|
||||
[PreferenceKeys.TabularNumbers] = Text(TabularNumbers),
|
||||
[PreferenceKeys.ReducedMotion] = Text(ReducedMotion),
|
||||
[PreferenceKeys.Tooltips] = Text(Tooltips),
|
||||
[PreferenceKeys.RowHover] = Text(RowHover),
|
||||
[PreferenceKeys.MenuCollapsed] = MenuCollapsed is { } collapsed ? Text(collapsed) : null,
|
||||
[PreferenceKeys.ShowDashboard] = Text(ShowDashboard),
|
||||
[PreferenceKeys.StartPage] = StartPage switch
|
||||
{
|
||||
StartPage.LastTab => "last-tab",
|
||||
StartPage.Page => "page",
|
||||
_ => "dashboard",
|
||||
},
|
||||
[PreferenceKeys.StartPath] = IsLocalPath(StartPath) ? StartPath : null,
|
||||
};
|
||||
|
||||
/// <summary>Whether an address is a path inside the application (no scheme, no host): the start page cannot leave the site.</summary>
|
||||
/// <param name="path">The address.</param>
|
||||
/// <returns><see langword="true"/> for <c>/something</c>.</returns>
|
||||
public static bool IsLocalPath(string? path) =>
|
||||
path is { Length: > 0 and <= 400 }
|
||||
&& path[0] == '/'
|
||||
&& (path.Length == 1 || (path[1] != '/' && path[1] != '\\'))
|
||||
&& !path.Contains("://", StringComparison.Ordinal);
|
||||
|
||||
private static bool? Bool(IReadOnlyDictionary<string, string?> values, string key) =>
|
||||
values.TryGetValue(key, out var value)
|
||||
? value switch
|
||||
{
|
||||
"true" => true,
|
||||
"false" => false,
|
||||
_ => null,
|
||||
}
|
||||
: null;
|
||||
|
||||
private static string Text(bool value) => value ? "true" : "false";
|
||||
}
|
||||
|
||||
/// <summary>The keys of <see cref="UserPreferences"/> in <c>user_settings</c>.</summary>
|
||||
public static class PreferenceKeys
|
||||
{
|
||||
/// <summary>Theme.</summary>
|
||||
public const string Theme = "ui.theme";
|
||||
|
||||
/// <summary>Accent.</summary>
|
||||
public const string Accent = "ui.accent";
|
||||
|
||||
/// <summary>Density.</summary>
|
||||
public const string Density = "ui.density";
|
||||
|
||||
/// <summary>Text size.</summary>
|
||||
public const string TextSize = "ui.text-size";
|
||||
|
||||
/// <summary>Tabular numbers.</summary>
|
||||
public const string TabularNumbers = "ui.tabular-numbers";
|
||||
|
||||
/// <summary>Reduced motion.</summary>
|
||||
public const string ReducedMotion = "ui.reduced-motion";
|
||||
|
||||
/// <summary>Tooltips.</summary>
|
||||
public const string Tooltips = "ui.tooltips";
|
||||
|
||||
/// <summary>Row highlight in grids.</summary>
|
||||
public const string RowHover = "ui.row-hover";
|
||||
|
||||
/// <summary>Menu state.</summary>
|
||||
public const string MenuCollapsed = "ui.menu-collapsed";
|
||||
|
||||
/// <summary>Dashboard on or off.</summary>
|
||||
public const string ShowDashboard = "home.show-dashboard";
|
||||
|
||||
/// <summary>Start page.</summary>
|
||||
public const string StartPage = "home.start-page";
|
||||
|
||||
/// <summary>Start address.</summary>
|
||||
public const string StartPath = "home.start-path";
|
||||
|
||||
/// <summary>The open tabs at the last sign-out (JSON array of addresses).</summary>
|
||||
public const string OpenTabs = "ui.open-tabs";
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Preferences;
|
||||
|
||||
/// <summary>
|
||||
/// Reads and writes the preferences of the signed-in user (SPEC §10.6). Instance accounts keep theirs in the system
|
||||
/// database, so they follow them in every company; company users keep them in the company database.
|
||||
/// </summary>
|
||||
/// <param name="factory">Opens the databases.</param>
|
||||
public sealed class UserSettingsService(IUnitOfWorkFactory factory)
|
||||
{
|
||||
/// <summary>The longest value accepted (dashboard and grid layouts are JSON).</summary>
|
||||
public const int MaxValueLength = 64 * 1024;
|
||||
|
||||
/// <summary>Reads every preference of the actor.</summary>
|
||||
/// <param name="actor">The signed-in user.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The values by key; empty for the instance itself.</returns>
|
||||
public async Task<IReadOnlyDictionary<string, string?>> GetAllAsync(Actor actor, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
if (Owner(actor) is not { } owner)
|
||||
{
|
||||
return new Dictionary<string, string?>(StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
await using var unitOfWork = await factory.CreateAsync(owner.Scope, cancellationToken).ConfigureAwait(false);
|
||||
IReadOnlyList<UserSettingRecord> rows = owner.Scope.IsSystem
|
||||
? await ListAsync<SystemUserSetting>(unitOfWork, owner.UserId, cancellationToken).ConfigureAwait(false)
|
||||
: await ListAsync<UserSetting>(unitOfWork, owner.UserId, cancellationToken).ConfigureAwait(false);
|
||||
return rows.ToDictionary(r => r.Key, r => r.Value, StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>Reads one preference.</summary>
|
||||
/// <param name="actor">The signed-in user.</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(Actor actor, string key, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(key);
|
||||
var all = await GetAllAsync(actor, cancellationToken).ConfigureAwait(false);
|
||||
return all.TryGetValue(key, out var value) ? value : null;
|
||||
}
|
||||
|
||||
/// <summary>Writes one preference; <see langword="null"/> removes it.</summary>
|
||||
/// <param name="actor">The signed-in user.</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 key, string? value, CancellationToken cancellationToken = default) =>
|
||||
SetManyAsync(actor, new Dictionary<string, string?>(StringComparer.Ordinal) { [key] = value }, cancellationToken);
|
||||
|
||||
/// <summary>Writes several preferences in one transaction; <see langword="null"/> values remove the key.</summary>
|
||||
/// <param name="actor">The signed-in user.</param>
|
||||
/// <param name="values">The values by key.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task SetManyAsync(Actor actor, IReadOnlyDictionary<string, string?> values, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
ArgumentNullException.ThrowIfNull(values);
|
||||
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 (Owner(actor) is not { } owner || values.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await using var unitOfWork = await factory.CreateAsync(owner.Scope, cancellationToken).ConfigureAwait(false);
|
||||
await unitOfWork.InTransactionAsync(
|
||||
ct => owner.Scope.IsSystem
|
||||
? WriteAsync<SystemUserSetting>(unitOfWork, owner.UserId, values, ct)
|
||||
: WriteAsync<UserSetting>(unitOfWork, owner.UserId, values, ct),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Reads the interface preferences.</summary>
|
||||
/// <param name="actor">The signed-in user.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The preferences, with defaults for what was never set.</returns>
|
||||
public async Task<UserPreferences> GetPreferencesAsync(Actor actor, CancellationToken cancellationToken = default) =>
|
||||
UserPreferences.FromSettings(await GetAllAsync(actor, cancellationToken).ConfigureAwait(false));
|
||||
|
||||
/// <summary>Writes the interface preferences.</summary>
|
||||
/// <param name="actor">The signed-in user.</param>
|
||||
/// <param name="preferences">The preferences.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public Task SavePreferencesAsync(Actor actor, UserPreferences preferences, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(preferences);
|
||||
return SetManyAsync(actor, preferences.ToSettings(), cancellationToken);
|
||||
}
|
||||
|
||||
private static (DatabaseScope Scope, long UserId)? Owner(Actor actor) => actor switch
|
||||
{
|
||||
{ SystemUserId: { } id } => (DatabaseScope.System, id),
|
||||
{ CompanyUserId: { } id, CompanyCode: { } code } => (DatabaseScope.Company(code), id),
|
||||
_ => null,
|
||||
};
|
||||
|
||||
private static async Task<IReadOnlyList<T>> ListAsync<T>(IUnitOfWork unitOfWork, long userId, CancellationToken cancellationToken)
|
||||
where T : UserSettingRecord, new() =>
|
||||
(await unitOfWork.Repository<T, long>().ListAsync(Query.For<T>().Where(s => s.UserId == userId), cancellationToken).ConfigureAwait(false)).Items;
|
||||
|
||||
private static async Task WriteAsync<T>(IUnitOfWork unitOfWork, long userId, IReadOnlyDictionary<string, string?> values, CancellationToken cancellationToken)
|
||||
where T : UserSettingRecord, new()
|
||||
{
|
||||
var repository = unitOfWork.Repository<T, long>();
|
||||
var existing = (await ListAsync<T>(unitOfWork, userId, 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 T { UserId = userId, Key = key, Value = value }, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user