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,134 @@
using Khaemhat.Application.Dashboard;
using Khaemhat.Application.Security;
using Khaemhat.Core.Security;
using Microsoft.Extensions.Logging.Abstractions;
namespace Khaemhat.Application.Tests;
/// <summary>The widget dashboard (SPEC §10.3, issue #30): the saved layout and the lists the widgets read.</summary>
[TestClass]
public sealed class DashboardTests
{
private static readonly Actor User = new("mario", UserLevel.Standard, null, 1, "demo");
private static readonly DateTimeOffset Now = new(2026, 11, 11, 10, 0, 0, TimeSpan.Zero);
[TestMethod]
public void Layout_RoundTrips_AndDropsWhatItCannotUse()
{
var layout = new DashboardLayout([new("todo", 4), new("notes", 6), new("kpi", 12)]);
var read = DashboardLayout.Parse(layout.ToJson());
Assert.IsNotNull(read);
Assert.IsTrue(layout.SameAs(read));
// Unknown and repeated widgets go, odd widths snap to the nearest allowed one (the wider on a tie), a missing width takes the default.
var messy = DashboardLayout.Parse("""{"v":1,"widgets":[{"id":"todo","w":5},{"id":"nope","w":4},{"id":"todo","w":4},{"id":"notes"}]}""");
Assert.IsNotNull(messy);
CollectionAssert.AreEqual(new[] { new WidgetPlacement("todo", 6), new WidgetPlacement("notes", 4) }, messy.Widgets.ToList());
Assert.IsNull(DashboardLayout.Parse(null));
Assert.IsNull(DashboardLayout.Parse("not json"));
Assert.IsNull(DashboardLayout.Parse("""{"widgets":"x"}"""));
}
[TestMethod]
public void Layout_Toggles_Moves_AndResizes()
{
var layout = new DashboardLayout([new("todo", 4), new("done", 4), new("notes", 4)]);
var shown = layout.Toggle("shortcuts", true);
Assert.AreEqual("shortcuts", shown.Widgets[^1].Id);
Assert.AreEqual(WidgetCatalog.Find("shortcuts")!.DefaultWidth, shown.Widgets[^1].Width);
Assert.AreSame(layout, layout.Toggle("todo", true), "Already shown.");
Assert.AreSame(layout, layout.Toggle("nope", true), "Not a widget.");
Assert.IsFalse(layout.Toggle("done", false).Contains("done"));
CollectionAssert.AreEqual(new[] { "done", "todo", "notes" }, layout.Move("done", -1).Widgets.Select(w => w.Id).ToList());
CollectionAssert.AreEqual(new[] { "todo", "done", "notes" }, layout.Move("todo", -1).Widgets.Select(w => w.Id).ToList(), "Already first.");
CollectionAssert.AreEqual(new[] { "notes", "todo", "done" }, layout.MoveTo("notes", 0).Widgets.Select(w => w.Id).ToList(), "Dropped on the first.");
Assert.AreEqual(8, layout.Resize("todo", 7).WidthOf("todo"));
Assert.AreEqual(6, WidgetDefinition.Step(4, 1));
Assert.AreEqual(3, WidgetDefinition.Step(3, -1));
Assert.AreEqual(12, WidgetDefinition.Step(12, 1));
}
[TestMethod]
public void Catalog_BuiltInLayout_UsesOnlyWidgetsWithData()
{
Assert.IsTrue(WidgetCatalog.BuiltIn.Widgets.All(w => WidgetCatalog.Find(w.Id) is { Milestone: null }));
Assert.AreEqual(WidgetCatalog.All.Count, WidgetCatalog.All.Select(w => w.Id).Distinct().Count());
Assert.IsTrue(WidgetCatalog.All.All(w => WidgetDefinition.Widths.Contains(w.DefaultWidth)));
}
[TestMethod]
public async Task Todo_LeavesOutAFailingSource_AndPutsTheUrgentFirst()
{
var aggregator = new TodoAggregator(
[
new Source(new FeedItem("a", "Normale", "x") { When = Now.AddHours(-2) }),
new FailingSource(),
new Source(new FeedItem("b", "Urgente", "x", FeedTone.Error) { Priority = 10 }),
],
new FixedClock(Now),
NullLogger<TodoAggregator>.Instance);
var items = await aggregator.GetAsync(User);
CollectionAssert.AreEqual(new[] { "b", "a" }, items.Select(i => i.Id).ToList());
}
[TestMethod]
public async Task Deadlines_KeepTheNext30Days_NearestFirst()
{
var aggregator = new DeadlineAggregator(
[
new Source(
new FeedItem("later", "Fra 20 giorni", "x") { When = Now.AddDays(20) },
new FeedItem("past", "Ieri", "x") { When = Now.AddDays(-1) },
new FeedItem("far", "Fra 40 giorni", "x") { When = Now.AddDays(40) },
new FeedItem("today", "Oggi", "x") { When = Now },
new FeedItem("undated", "Senza data", "x")),
],
new FixedClock(Now),
NullLogger<DeadlineAggregator>.Instance);
var items = await aggregator.GetAsync(User);
CollectionAssert.AreEqual(new[] { "today", "later" }, items.Select(i => i.Id).ToList());
}
[TestMethod]
public async Task Done_LatestFirst()
{
var aggregator = new DoneAggregator(
[new Source(new FeedItem("early", "Alle 8", "x") { When = Now.AddHours(-2) }, new FeedItem("late", "Alle 9", "x") { When = Now.AddHours(-1) })],
new FixedClock(Now),
NullLogger<DoneAggregator>.Instance);
CollectionAssert.AreEqual(new[] { "late", "early" }, (await aggregator.GetAsync(User)).Select(i => i.Id).ToList());
}
private sealed class Source(params FeedItem[] items) : ITodoSource, IDoneSource, IDeadlineSource
{
public Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, CancellationToken cancellationToken) =>
Task.FromResult<IReadOnlyList<FeedItem>>(items);
public Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, DateOnly until, CancellationToken cancellationToken) =>
Task.FromResult<IReadOnlyList<FeedItem>>(items);
}
private sealed class FailingSource : ITodoSource
{
public Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, CancellationToken cancellationToken) =>
throw new InvalidOperationException("The module is down.");
}
private sealed class FixedClock(DateTimeOffset now) : TimeProvider
{
public override DateTimeOffset GetUtcNow() => now;
public override TimeZoneInfo LocalTimeZone => TimeZoneInfo.Utc;
}
}
+1 -1
View File
@@ -71,7 +71,7 @@ public sealed class MappingTests
[
"sys_companies", "sys_data_protection_keys", "sys_job_locks", "sys_job_runs", "sys_license_activations", "sys_licenses", "sys_log",
"sys_notifications", "sys_roles_templates", "sys_scheduled_tasks", "sys_security_audit", "sys_sessions", "sys_settings", "sys_user_settings", "sys_users",
"attachments", "audit_log", "notifications", "role_permissions", "roles", "user_permission_overrides", "user_roles", "user_sessions", "user_settings", "users",
"attachments", "audit_log", "company_settings", "notifications", "role_permissions", "roles", "user_permission_overrides", "user_roles", "user_sessions", "user_settings", "users",
];
CollectionAssert.AreEquivalent(expected, registry.Maps.Select(m => m.Table).ToArray());
}
@@ -0,0 +1,115 @@
using Khaemhat.Application.Dashboard;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Modules;
using Khaemhat.Application.Security;
using Khaemhat.Core.Security;
using Khaemhat.Web.Tests.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace Khaemhat.Web.Tests.Shell;
/// <summary>The dashboard of each user, the default of a role and the company settings behind it (issues #30 and #31).</summary>
[TestClass]
public sealed class DashboardServiceTests
{
[TestMethod]
public async Task Layout_IsPersonal_FallsBackToTheRole_ThenToTheBuiltIn()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var dashboard = app.Services.GetRequiredService<DashboardService>();
var users = app.Services.GetRequiredService<UserService>();
var root = new Actor(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
var (anna, _) = await users.CreateAsync(root, company, new NewCompanyUser("anna", "Anna Verdi", null, UserKind.Human, [PredefinedRoles.ReadOnly], new UserFlags(false, false, false, false)));
var (luca, _) = await users.CreateAsync(root, company, new NewCompanyUser("luca", "Luca Neri", null, UserKind.Human, [PredefinedRoles.Administration], new UserFlags(false, false, false, false)));
var annaActor = new Actor("anna", UserLevel.Standard, null, anna.Id, company);
var lucaActor = new Actor("luca", UserLevel.Standard, null, luca.Id, company);
// Only instance accounts see the state of the system.
Assert.IsTrue((await dashboard.AvailableAsync(root)).Any(w => w.Id == WidgetIds.SystemStatus));
Assert.IsFalse((await dashboard.AvailableAsync(annaActor)).Any(w => w.Id == WidgetIds.SystemStatus));
// Nothing saved: the built-in layout, without what the user may not see.
var first = await dashboard.GetAsync(annaActor);
Assert.AreEqual(DashboardLayoutSource.BuiltIn, first.Source);
Assert.IsTrue(first.Layout.Contains(WidgetIds.Todo));
Assert.IsFalse(first.Layout.Contains(WidgetIds.SystemStatus));
// The default of the role applies to whoever never customized.
var roleLayout = new DashboardLayout([new(WidgetIds.Notes, 6), new(WidgetIds.Deadlines, 6)]);
await dashboard.SaveRoleDefaultAsync(lucaActor, company, PredefinedRoles.ReadOnly, roleLayout);
var fromRole = await dashboard.GetAsync(annaActor);
Assert.AreEqual(DashboardLayoutSource.Role, fromRole.Source);
Assert.AreEqual(PredefinedRoles.ReadOnly, fromRole.RoleCode);
Assert.IsTrue(roleLayout.SameAs(fromRole.Layout));
Assert.IsTrue((await dashboard.RoleDefaultsAsync(company)).Any(r => r.Role.Code == PredefinedRoles.ReadOnly && r.Layout is not null));
// A user's own layout wins and stays across services; Reset brings the role default back.
var own = new DashboardLayout([new(WidgetIds.Shortcuts, 12), new(WidgetIds.Todo, 4)]);
await dashboard.SaveAsync(annaActor, own);
var reread = await app.Services.CreateScope().ServiceProvider.GetRequiredService<DashboardService>().GetAsync(annaActor with { });
Assert.AreEqual(DashboardLayoutSource.User, reread.Source);
Assert.IsTrue(own.SameAs(reread.Layout));
Assert.AreEqual(DashboardLayoutSource.BuiltIn, (await dashboard.GetAsync(lucaActor)).Source, "Another user is not touched.");
await dashboard.ResetAsync(annaActor);
Assert.AreEqual(DashboardLayoutSource.Role, (await dashboard.GetAsync(annaActor)).Source);
// Only who may change the company settings sets the default of a role.
await Assert.ThrowsExactlyAsync<AccessDeniedException>(() => dashboard.SaveRoleDefaultAsync(annaActor, company, PredefinedRoles.ReadOnly, null));
await dashboard.SaveRoleDefaultAsync(lucaActor, company, PredefinedRoles.ReadOnly, null);
Assert.AreEqual(DashboardLayoutSource.BuiltIn, (await dashboard.GetAsync(annaActor)).Source);
await app.StopAsync();
}
}
[TestMethod]
public async Task Notes_AndShortcuts_AreKeptPerUser_AndCleaned()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var dashboard = app.Services.GetRequiredService<DashboardService>();
var root = new Actor(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
Assert.IsEmpty(await dashboard.GetNotesAsync(root));
Assert.IsNull(await dashboard.GetShortcutsAsync(root), "Never chosen: the widget shows the first areas.");
await dashboard.SaveNotesAsync(root, [new(" Chiamare il commercialista ", false), new(" ", false), new("Fatto", true)]);
CollectionAssert.AreEqual(new[] { new PersonalNote("Chiamare il commercialista", false), new PersonalNote("Fatto", true) }, (await dashboard.GetNotesAsync(root)).ToList());
await dashboard.SaveNotesAsync(root, [.. Enumerable.Range(1, 30).Select(i => new PersonalNote(new string('n', 400), false))]);
var notes = await dashboard.GetNotesAsync(root);
Assert.HasCount(DashboardService.MaxNotes, notes);
Assert.IsTrue(notes.All(n => n.Text.Length <= DashboardService.MaxNoteLength));
await dashboard.SaveShortcutsAsync(root, ["/anagrafiche/clienti", "https://example.com", "//evil", "/anagrafiche/clienti", "/vendite"]);
CollectionAssert.AreEqual(new[] { "/anagrafiche/clienti", "/vendite" }, (await dashboard.GetShortcutsAsync(root))!.ToList());
await dashboard.SaveShortcutsAsync(root, []);
Assert.IsEmpty((await dashboard.GetShortcutsAsync(root))!, "An empty choice is a choice.");
await app.StopAsync();
}
}
[TestMethod]
public async Task CompanySettings_NeedThePermission_AndStayInTheirCompany()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var settings = app.Services.GetRequiredService<CompanySettingsService>();
var root = new Actor(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
var stranger = new Actor("altro", UserLevel.Standard, null, 1, "altra");
await settings.SetAsync(root, company, "test.alpha", "uno");
await settings.SetManyAsync(root, company, new Dictionary<string, string?> { ["test.beta"] = "due", ["test.alpha"] = null });
Assert.IsNull(await settings.GetAsync(company, "test.alpha"));
Assert.AreEqual("due", await settings.GetAsync(company, "test.beta"));
CollectionAssert.AreEquivalent(new[] { "test.beta" }, (await settings.GetAllAsync(company, "test.")).Keys.ToList());
await Assert.ThrowsExactlyAsync<AccessDeniedException>(() => settings.SetAsync(stranger, company, "test.gamma", "tre"));
await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => settings.SetAsync(root, company, " ", "x"));
await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => settings.SetAsync(root, company, "test.big", new string('x', CompanySettingsService.MaxValueLength + 1)));
await app.StopAsync();
}
}
}
@@ -62,7 +62,9 @@ public sealed partial class LocalizationRulesTests
public void EveryTextKeyInTheCode_Exists()
{
var missing = new List<string>();
foreach (var file in Directory.EnumerateFiles(Path.Combine(Repository.Root, "src", "Khaemhat.Web"), "*.*", SearchOption.AllDirectories)
// The web project, and the application one where the dashboard catalog and sources name their texts.
foreach (var file in new[] { "Khaemhat.Web", "Khaemhat.Application" }
.SelectMany(project => Directory.EnumerateFiles(Path.Combine(Repository.Root, "src", project), "*.*", SearchOption.AllDirectories))
.Where(f => (f.EndsWith(".razor", StringComparison.Ordinal) || f.EndsWith(".cs", StringComparison.Ordinal)) && !Repository.IsBuildOutput(f)))
{
foreach (Match match in KeyPattern().Matches(File.ReadAllText(file)))
@@ -269,6 +271,6 @@ public sealed partial class LocalizationRulesTests
[GeneratedRegex(@"&[a-zA-Z]+;|&#\d+;")]
private static partial Regex EntityPattern();
[GeneratedRegex("\"((?:Shell|Pages|Auth|Common|Ui)\\.[A-Za-z0-9_.]+)\"")]
[GeneratedRegex("\"((?:Shell|Pages|Auth|Common|Ui|Dashboard)\\.[A-Za-z0-9_.]+)\"")]
private static partial Regex KeyPattern();
}