From 6839d9cac9ba5424e61c3ef738d004ad6136d803 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sat, 14 Nov 2026 18:09:45 +0000 Subject: [PATCH 01/11] Add opt-in PostIt exception reporting Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 4 ++ .../Services/AndroidBackgroundChatService.cs | 1 + .../Services/ChatBootReceiver.cs | 3 ++ .../Services/ChatConnectionService.cs | 1 + src/PostIt/PostIt.Tests/SettingsLoadTests.cs | 14 ++++++ .../PostIt.Tests/YavscApiClientTests.cs | 45 +++++++++++++++++ src/PostIt/PostIt/App.axaml.cs | 24 ++++++++- src/PostIt/PostIt/Services/YavscApiClient.cs | 50 +++++++++++++++++++ .../PostIt/ViewModels/Settings/Settings.cs | 5 ++ .../PostIt/Views/Layout/SettingsPage.axaml | 4 ++ src/Yavsc.Abstract/IT/BugReport.cs | 5 +- .../Controllers/Survey/BugApiController.cs | 22 ++++---- 12 files changed, 165 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b359d92cc..da2ef3289 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ # Changelog +## [1.0.8-rc37] - unstable + +* [PostIt] Telemetry + ## [1.0.8-rc36] - unstable ### Added diff --git a/src/PostIt/PostIt.Android/Services/AndroidBackgroundChatService.cs b/src/PostIt/PostIt.Android/Services/AndroidBackgroundChatService.cs index ddefc4cf3..c2288fd0c 100644 --- a/src/PostIt/PostIt.Android/Services/AndroidBackgroundChatService.cs +++ b/src/PostIt/PostIt.Android/Services/AndroidBackgroundChatService.cs @@ -87,6 +87,7 @@ internal sealed class AndroidBackgroundChatService : IBackgroundChatService { Cancel(epoch); Log.Error("PostIt.Chat", ex.ToString()); + api.QueueExceptionReport(ex, "PostIt.Android.Chat"); try { await AndroidSettings.UpdateAsync(api.Settings, s => s.SetActionStatus(ex.Message, StatusSeverity.Error)) diff --git a/src/PostIt/PostIt.Android/Services/ChatBootReceiver.cs b/src/PostIt/PostIt.Android/Services/ChatBootReceiver.cs index c38d46c0f..7adf97c54 100644 --- a/src/PostIt/PostIt.Android/Services/ChatBootReceiver.cs +++ b/src/PostIt/PostIt.Android/Services/ChatBootReceiver.cs @@ -34,8 +34,11 @@ public sealed class ChatBootReceiver : BroadcastReceiver { Log.Error("PostIt.Chat", "Boot restart rejected: " + ex); if (api is not null) + { + api.QueueExceptionReport(ex, "PostIt.Android.Chat"); AndroidSettings.ReportError(api.Settings, "Android a refuse le redemarrage de la messagerie : " + ex.Message); + } } finally { pending?.Finish(); } }); diff --git a/src/PostIt/PostIt.Android/Services/ChatConnectionService.cs b/src/PostIt/PostIt.Android/Services/ChatConnectionService.cs index f887a7d31..7de2f38b1 100644 --- a/src/PostIt/PostIt.Android/Services/ChatConnectionService.cs +++ b/src/PostIt/PostIt.Android/Services/ChatConnectionService.cs @@ -253,6 +253,7 @@ public sealed class ChatConnectionService : Service private void ReportError(Exception ex) { Log.Error("PostIt.Chat", ex.ToString()); + _api?.QueueExceptionReport(ex, "PostIt.Android.Chat"); if (_api is not null) AndroidSettings.ReportError(_api.Settings, ex.Message); } diff --git a/src/PostIt/PostIt.Tests/SettingsLoadTests.cs b/src/PostIt/PostIt.Tests/SettingsLoadTests.cs index 5f3bd765d..415d256fe 100644 --- a/src/PostIt/PostIt.Tests/SettingsLoadTests.cs +++ b/src/PostIt/PostIt.Tests/SettingsLoadTests.cs @@ -175,6 +175,20 @@ public class SettingsLoadTests Assert.Equal("bonjour", roundTrip.SearchText); } + [Fact] + public void Exception_reports_are_disabled_by_default_and_persist_when_enabled() + { + var defaults = new PostIt.ViewModels.Settings(); + Assert.False(defaults.ShareExceptionReports); + + defaults.ShareExceptionReports = true; + var roundTrip = JsonSerializer.Deserialize( + JsonSerializer.Serialize(defaults)); + + Assert.NotNull(roundTrip); + Assert.True(roundTrip.ShareExceptionReports); + } + /// /// First-start regression guard: older settings payloads can /// still contain ActionStatus from a previous write. This diff --git a/src/PostIt/PostIt.Tests/YavscApiClientTests.cs b/src/PostIt/PostIt.Tests/YavscApiClientTests.cs index 2fba36b43..e0beb915e 100644 --- a/src/PostIt/PostIt.Tests/YavscApiClientTests.cs +++ b/src/PostIt/PostIt.Tests/YavscApiClientTests.cs @@ -19,6 +19,51 @@ namespace PostIt.Tests; [Trait("Category", "non-reg")] public class YavscApiClientTests { + [Fact] + public async Task Exception_reports_are_sent_only_after_local_opt_in() + { + using var apiServer = new StubApiServer(); + await apiServer.StartAsync(); + var tokensPath = TokensPath(); + try + { + var settings = new Settings + { + ApiUrl = apiServer.BaseUrl + "/api/v1/", + ShareExceptionReports = true, + Authentication = new AuthenticationSettings + { + Authority = "https://example.test/" + } + }; + settings.Load(); + var store = new TokenStore(tokensPath); + store.Save(new RefreshTokenRecord( + "access", "refresh", DateTimeOffset.UtcNow.AddMinutes(5))); + await using var client = new YavscApiClient(settings, store); + Assert.True(settings.ShareExceptionReports); + Assert.True(client.HasValidSession); + + var reportWasSent = await client.ReportExceptionAsync( + new InvalidOperationException("Messaging service unavailable"), + "PostIt.Android.Chat", + TestContext.Current.CancellationToken); + Assert.True(reportWasSent, $"share={settings.ShareExceptionReports}; session={client.HasValidSession}"); + Assert.Equal(1, apiServer.RequestCount); + + settings.ShareExceptionReports = false; + Assert.False(await client.ReportExceptionAsync( + new InvalidOperationException("Do not send"), + "PostIt.Android.Chat", + TestContext.Current.CancellationToken)); + Assert.Equal(1, apiServer.RequestCount); + } + finally + { + if (File.Exists(tokensPath)) File.Delete(tokensPath); + } + } + [Theory] [InlineData(false)] [InlineData(true)] diff --git a/src/PostIt/PostIt/App.axaml.cs b/src/PostIt/PostIt/App.axaml.cs index 1e970c2ba..68e50a581 100644 --- a/src/PostIt/PostIt/App.axaml.cs +++ b/src/PostIt/PostIt/App.axaml.cs @@ -23,6 +23,7 @@ namespace PostIt; public partial class App : Application, ILiveView, IVMPusherApp { public static bool LiveMode { get; private set; } + private static bool _exceptionHandlersRegistered; private Task? _bootTask; private bool _sessionNavigationConfigured; public static string? CliConfigFileSpecification { get; private set; } @@ -52,7 +53,14 @@ public partial class App : Application, ILiveView, IVMPusherApp this.ServiceProvider = Platform.CreateServiceProvider?.Invoke() ?? new ServiceCollection().BuildPostItServices(); var settings = ServiceProvider.GetRequiredService(); - ServiceProvider.GetRequiredService().StartSessionMaintenance(); + var api = ServiceProvider.GetRequiredService(); + api.StartSessionMaintenance(); + if (!_exceptionHandlersRegistered) + { + AppDomain.CurrentDomain.UnhandledException += OnUnhandledException; + TaskScheduler.UnobservedTaskException += OnUnobservedTaskException; + _exceptionHandlersRegistered = true; + } if (!LiveMode) { @@ -115,6 +123,20 @@ public partial class App : Application, ILiveView, IVMPusherApp base.OnFrameworkInitializationCompleted(); } + private static void OnUnhandledException(object? sender, UnhandledExceptionEventArgs args) + { + if (args.ExceptionObject is Exception exception && Current is App app) + app.ServiceProvider?.GetService() + ?.QueueExceptionReport(exception, "PostIt"); + } + + private static void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs args) + { + if (Current is App app) + app.ServiceProvider?.GetService() + ?.QueueExceptionReport(args.Exception, "PostIt"); + } + private bool IsProduction() { #if DEBUG diff --git a/src/PostIt/PostIt/Services/YavscApiClient.cs b/src/PostIt/PostIt/Services/YavscApiClient.cs index 0917f46a2..433a15db9 100644 --- a/src/PostIt/PostIt/Services/YavscApiClient.cs +++ b/src/PostIt/PostIt/Services/YavscApiClient.cs @@ -9,6 +9,7 @@ using System.Threading; using System.Threading.Tasks; using IdentityModel.OidcClient; using PostIt.ViewModels; +using Yavsc.ApiControllers; using Yavsc.Api.Client; namespace PostIt.Services; @@ -110,6 +111,55 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable /// The current OIDC id_token, or null. public string? CurrentIdToken => _tokens?.IdToken; + public async Task ReportExceptionAsync( + Exception exception, + string component, + CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(exception); + ArgumentException.ThrowIfNullOrWhiteSpace(component); + + if (!Settings.ShareExceptionReports || !HasValidSession) + return false; + + var exceptionType = exception.GetType().FullName ?? exception.GetType().Name; + var exceptionDetails = exception.ToString(); + var exceptionJson = SerializeExceptionDetails(exceptionType, exceptionDetails); + while (exceptionJson.Length > 10240 && exceptionDetails.Length > 0) + { + exceptionDetails = exceptionDetails[..(exceptionDetails.Length / 2)]; + exceptionJson = SerializeExceptionDetails(exceptionType, exceptionDetails); + } + + var apiRoot = new Uri(Settings.ApiUrl.TrimEnd('/') + "/", UriKind.Absolute); + var endpoint = new Uri(apiRoot, "/api/bug/signal"); + var report = new BugReport + { + Component = component, + FeatureShortName = "PostIt", + ExceptionObjectJson = exceptionJson + }; + await CallAsync(HttpMethod.Post, endpoint.ToString(), report, ct).ConfigureAwait(false); + return true; + } + + public void QueueExceptionReport(Exception exception, string component) + { + if (!Settings.ShareExceptionReports || !HasValidSession) + return; + + var report = ReportExceptionAsync(exception, component); + _ = report.ContinueWith( + failed => Console.Error.WriteLine( + $"Exception report failed: {failed.Exception?.GetBaseException()}"), + CancellationToken.None, + TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, + TaskScheduler.Default); + } + + private static string SerializeExceptionDetails(string exceptionType, string details) => + JsonSerializer.Serialize(new { ExceptionType = exceptionType, Details = details }); + public void StartSessionMaintenance() { lock (_maintenanceGate) diff --git a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs index 430419483..3ad9ddf46 100644 --- a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs +++ b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs @@ -67,6 +67,8 @@ public partial class Settings : ViewModelBase [ObservableProperty] public partial bool AndroidKeepChatConnected { get; set; } [ObservableProperty] + public partial bool ShareExceptionReports { get; set; } + [ObservableProperty] public partial Dictionary ChatRoomsByAccount { get; set; } = new(); [JsonIgnore] public bool SupportsBackgroundChatService => OperatingSystem.IsAndroid(); @@ -174,6 +176,7 @@ public partial class Settings : ViewModelBase partial void OnPodcastBlurBackgroundChanged(bool value) => MarkDirty(); partial void OnLanCallAddressChanged(string? value) => MarkDirty(); partial void OnAndroidKeepChatConnectedChanged(bool value) => MarkDirty(); + partial void OnShareExceptionReportsChanged(bool value) => MarkDirty(); partial void OnChatRoomsByAccountChanged(Dictionary value) => MarkDirty(); /// @@ -441,6 +444,7 @@ public partial class Settings : ViewModelBase PodcastBlurBackground = settings.PodcastBlurBackground; LanCallAddress = settings.LanCallAddress; AndroidKeepChatConnected = settings.AndroidKeepChatConnected; + ShareExceptionReports = settings.ShareExceptionReports; ChatRoomsByAccount = settings.ChatRoomsByAccount ?? new(); if (!(settings.Authentication is null)) { @@ -521,6 +525,7 @@ public partial class Settings : ViewModelBase this.ApiUrl = "https://api.pschneider.fr/api/v1/"; this.SearchText = string.Empty; this.ProviderOngoingRequestsSortOption = string.Empty; + this.ShareExceptionReports = false; } /// diff --git a/src/PostIt/PostIt/Views/Layout/SettingsPage.axaml b/src/PostIt/PostIt/Views/Layout/SettingsPage.axaml index f0865fd70..160c185ac 100644 --- a/src/PostIt/PostIt/Views/Layout/SettingsPage.axaml +++ b/src/PostIt/PostIt/Views/Layout/SettingsPage.axaml @@ -55,6 +55,10 @@ + + diff --git a/src/Yavsc.Abstract/IT/BugReport.cs b/src/Yavsc.Abstract/IT/BugReport.cs index 3c04d5a93..a876666a7 100644 --- a/src/Yavsc.Abstract/IT/BugReport.cs +++ b/src/Yavsc.Abstract/IT/BugReport.cs @@ -4,12 +4,11 @@ using Yavsc.Attributes.Validation; namespace Yavsc.ApiControllers { public class BugReport { - [Required,YaStringLength(1024)] - public string ApiKey { get ; set; } [Required,YaStringLength(512)] public string Component { get ; set; } [Required][YaStringLength(10240)] public string ExceptionObjectJson { get ; set; } + [YaStringLength(256)] + public string FeatureShortName { get ; set; } } } - diff --git a/src/Yavsc.Api/Controllers/Survey/BugApiController.cs b/src/Yavsc.Api/Controllers/Survey/BugApiController.cs index a28ed8df3..6c3a2454c 100644 --- a/src/Yavsc.Api/Controllers/Survey/BugApiController.cs +++ b/src/Yavsc.Api/Controllers/Survey/BugApiController.cs @@ -1,4 +1,3 @@ -using Newtonsoft.Json; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using Yavsc.Models; @@ -22,22 +21,26 @@ namespace Yavsc.ApiControllers [HttpPost("signal")] [Authorize] - public IActionResult Signal([FromBody] BugReport report) + public async Task Signal([FromBody] BugReport report) { - _logger.LogWarning("bug reported : "+report.ExceptionObjectJson); if (report.ExceptionObjectJson!=null) if (report.ExceptionObjectJson.Length > 10240) report.ExceptionObjectJson = report.ExceptionObjectJson.Substring(0,10240); if (!ModelState.IsValid) - { - _logger.LogError("Bag request :"); - _logger.LogError(JsonConvert.SerializeObject(ModelState)); + _logger.LogError("Invalid bug report request."); return new BadRequestObjectResult(ModelState); } - var existent = _context.Bug.FirstOrDefault( b => + _logger.LogWarning("Bug report received for component {Component}.", report.Component); + var feature = string.IsNullOrWhiteSpace(report.FeatureShortName) + ? null + : await _context.Feature.FirstOrDefaultAsync( + f => f.ShortName == report.FeatureShortName); + long? featureId = feature?.Id; + var existent = await _context.Bug.FirstOrDefaultAsync(b => b.Description == report.ExceptionObjectJson && b.Title == report.Component && + b.FeatureId == featureId && b.Status != BugStatus.Rejected ); if (existent != null) @@ -48,10 +51,11 @@ namespace Yavsc.ApiControllers _logger.LogInformation("Filling a new bug report"); var bug = new Bug { Title = report.Component, - Description = report.ExceptionObjectJson + Description = report.ExceptionObjectJson, + FeatureId = featureId }; _context.Bug.Add(bug); - _context.SaveChanges(); + await _context.SaveChangesAsync(); return CreatedAtRoute("GetBug", new { id = bug.Id }, bug); } From 05cefaff3217821e5414ed4355384527cd5e1d96 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sat, 14 Nov 2026 18:45:32 +0000 Subject: [PATCH 02/11] in a scroll viewer --- src/PostIt/PostIt/Views/Admin/AdministrationPage.axaml | 5 +++-- src/PostIt/PostIt/Views/Layout/SettingsPage.axaml | 2 ++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/PostIt/PostIt/Views/Admin/AdministrationPage.axaml b/src/PostIt/PostIt/Views/Admin/AdministrationPage.axaml index 53aaffa77..374cdd8af 100644 --- a/src/PostIt/PostIt/Views/Admin/AdministrationPage.axaml +++ b/src/PostIt/PostIt/Views/Admin/AdministrationPage.axaml @@ -55,8 +55,8 @@ - - + + + diff --git a/src/PostIt/PostIt/Views/Layout/SettingsPage.axaml b/src/PostIt/PostIt/Views/Layout/SettingsPage.axaml index 160c185ac..8fe10c7de 100644 --- a/src/PostIt/PostIt/Views/Layout/SettingsPage.axaml +++ b/src/PostIt/PostIt/Views/Layout/SettingsPage.axaml @@ -7,6 +7,7 @@ xmlns:vm="using:PostIt.ViewModels" x:DataType="vm:Settings" > + @@ -78,4 +79,5 @@ + From 0fa7615a6049ad41297deb1a86e1c86fffcd8f6e Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sat, 14 Nov 2026 19:18:01 +0000 Subject: [PATCH 03/11] Add server-side admin user pagination Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 4 + .../PostIt.Tests/AdministrationAccessTests.cs | 53 ++++++- .../PostIt.Tests/HomePageProviderFlowTests.cs | 20 +-- .../ViewModels/AdministrationPageViewModel.cs | 150 ++++++++++++++---- .../Views/Admin/AdministrationPage.axaml | 22 ++- .../Administration/AdministrationDtos.cs | 4 + .../AdministrationApiClient.cs | 3 + .../SiteAdministrationApiController.cs | 9 ++ .../Services/AdministrationService.cs | 47 ++++++ .../Services/IAdministrationService.cs | 1 + 10 files changed, 254 insertions(+), 59 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index da2ef3289..1404175db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ # Changelog +## [1.0.8-rc38] - unstable + +* [PostIt/Administration] Rechercher les utilisateurs côté serveur par login ou nom, par pages de 25 résultats maximum avec navigation précédente/suivante. + ## [1.0.8-rc37] - unstable * [PostIt] Telemetry diff --git a/src/PostIt/PostIt.Tests/AdministrationAccessTests.cs b/src/PostIt/PostIt.Tests/AdministrationAccessTests.cs index 429e0ac98..b7805fc53 100644 --- a/src/PostIt/PostIt.Tests/AdministrationAccessTests.cs +++ b/src/PostIt/PostIt.Tests/AdministrationAccessTests.cs @@ -6,6 +6,7 @@ using Avalonia.VisualTree; using PostIt.Services; using PostIt.ViewModels; using PostIt.Views; +using Yavsc.Abstract.Administration; using Yavsc.Abstract.Identity; using Yavsc.Abstract.Resources; using Yavsc.Api.Client; @@ -82,6 +83,42 @@ public class AdministrationAccessTests Assert.DoesNotContain(api.Requests, path => path.EndsWith("/resource-usage/me")); } + [Fact] + public async Task Administration_searches_users_on_the_server_and_pages_results() + { + await using var api = new ProfileTransport("Administrator") { ManyUsers = true }; + var session = new SessionStatusViewModel { Api = api }; + await session.RefreshAsync(); + var vm = new AdministrationPageViewModel(api, api.UsageClient, session); + + await vm.RefreshAsync(); + Assert.Equal(1, vm.UserPage); + Assert.True(vm.HasNextUserPage); + Assert.Equal(25, vm.Users.Count); + Assert.Contains(api.Requests, path => path.Contains( + "/administration/users?page=1&query=", StringComparison.Ordinal)); + + vm.SearchText = "Jean Dupont"; + await vm.SearchUsersCommand.ExecuteAsync(null); + Assert.Equal(1, vm.UserPage); + Assert.False(vm.HasNextUserPage); + Assert.Contains(api.Requests, path => path.Contains( + "/administration/users?page=1&query=Jean", StringComparison.Ordinal)); + + vm.SearchText = ""; + await vm.SearchUsersCommand.ExecuteAsync(null); + Assert.True(vm.HasNextUserPage); + await vm.NextUserPageCommand.ExecuteAsync(null); + Assert.Equal(2, vm.UserPage); + Assert.False(vm.HasNextUserPage); + Assert.Contains(api.Requests, path => path.Contains( + "/administration/users?page=2&query=", StringComparison.Ordinal)); + Assert.False(vm.NextUserPageCommand.CanExecute(null)); + + await vm.PreviousUserPageCommand.ExecuteAsync(null); + Assert.Equal(1, vm.UserPage); + } + [AvaloniaFact] public async Task Administration_displays_both_tabs_and_selected_user_usage() { @@ -232,6 +269,7 @@ public class AdministrationAccessTests public bool FailUsage { get; set; } public bool ExhaustedQuota { get; set; } public bool HideIpAddressInCalls { get; set; } + public bool ManyUsers { get; set; } public ResourceUsageApiClient UsageClient => new(this, Settings.ApiUrl); public ProfileTransport(string role) @@ -278,11 +316,22 @@ public class AdministrationAccessTests }; result = path.EndsWith("/admin") ? new List { usage } : usage; } - else if (path.EndsWith("/users")) + else if (path.Contains("/administration/users", StringComparison.Ordinal)) { if (ExhaustedQuota) throw new HttpRequestException("resource_quota_exceeded", null, System.Net.HttpStatusCode.TooManyRequests); - result = new List { new() { UserId = "alice-id", UserName = "alice" } }; + var matchingQuery = path.Contains("query=Jean", StringComparison.Ordinal); + var page = path.Contains("page=2", StringComparison.Ordinal); + var returnedUsers = !matchingQuery && !page && ManyUsers + ? Enumerable.Range(1, 25).Select(index => new UserInfo + { + UserId = $"alice-id-{index}", UserName = $"alice-{index}" + }).ToList() + : matchingQuery + ? new List { new() { UserId = "jean-id", UserName = "jean", FullName = "Jean Dupont" } } + : page ? new List() + : new List { new() { UserId = "alice-id", UserName = "alice" } }; + result = new AdministrationUserPage(returnedUsers, ManyUsers && !matchingQuery && !page); } else throw new InvalidOperationException($"Unexpected endpoint: {path}"); diff --git a/src/PostIt/PostIt.Tests/HomePageProviderFlowTests.cs b/src/PostIt/PostIt.Tests/HomePageProviderFlowTests.cs index 40922f7ae..84a6afb6e 100644 --- a/src/PostIt/PostIt.Tests/HomePageProviderFlowTests.cs +++ b/src/PostIt/PostIt.Tests/HomePageProviderFlowTests.cs @@ -43,21 +43,7 @@ public class HomePageProviderFlowTests } [Fact] - public void Administration_page_filters_users_by_search_text() - { - var vm = new AdministrationPageViewModel(); - vm.Users.Add(new Yavsc.Abstract.Identity.UserInfo { UserId = "1", UserName = "alice", FullName = "Alice Example" }); - vm.Users.Add(new Yavsc.Abstract.Identity.UserInfo { UserId = "2", UserName = "bob", FullName = "Bob Jones" }); - vm.Users.Add(new Yavsc.Abstract.Identity.UserInfo { UserId = "3", UserName = "carol", FullName = "Carol Smith" }); - - vm.SearchText = "ali"; - - Assert.Single(vm.FilteredUsers); - Assert.Equal("alice", vm.FilteredUsers[0].UserName); - } - - [Fact] - public void Administration_page_filters_users_by_full_name() + public void Administration_search_text_does_not_filter_the_loaded_page_locally() { var vm = new AdministrationPageViewModel(); vm.Users.Add(new Yavsc.Abstract.Identity.UserInfo { UserId = "1", UserName = "alice", FullName = "Alice Example" }); @@ -65,8 +51,8 @@ public class HomePageProviderFlowTests vm.SearchText = "example"; - Assert.Single(vm.FilteredUsers); - Assert.Equal("alice", vm.FilteredUsers[0].UserName); + Assert.Equal(2, vm.Users.Count); + Assert.Equal("example", vm.SearchText); } [Fact] diff --git a/src/PostIt/PostIt/ViewModels/AdministrationPageViewModel.cs b/src/PostIt/PostIt/ViewModels/AdministrationPageViewModel.cs index fc2750a06..e06eddc7e 100644 --- a/src/PostIt/PostIt/ViewModels/AdministrationPageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/AdministrationPageViewModel.cs @@ -22,6 +22,10 @@ public partial class AdministrationPageViewModel : ViewModelBase private readonly ResourceUsageApiClient? _usageClient; private readonly SessionStatusViewModel? _session; private readonly AdministrationApiClient? _administrationClient; + private AdministrationApiClient? UserSearchClient => + _administrationClient ?? (_api is null + ? null + : new AdministrationApiClient(_api, () => _api.Settings.ApiUrl)); public ObservableCollection UsageOverview { get; } = new(); @@ -37,22 +41,20 @@ public partial class AdministrationPageViewModel : ViewModelBase [ObservableProperty] public partial string SearchText { get; set; } = string.Empty; + [ObservableProperty] + public partial int UserPage { get; set; } = 1; + + [ObservableProperty] + public partial bool HasNextUserPage { get; set; } + + public bool HasPreviousUserPage => UserPage > 1; + [ObservableProperty] public partial string StatusMessage { get; set; } = "Chargement…"; [ObservableProperty] public partial UserInfo? SelectedUser { get; set; } - public IReadOnlyList FilteredUsers => - string.IsNullOrWhiteSpace(SearchText) - ? Users.ToList() - : Users.Where(user => - (user.UserName ?? string.Empty).Contains(SearchText, StringComparison.OrdinalIgnoreCase) - || (user.FullName ?? string.Empty).Contains(SearchText, StringComparison.OrdinalIgnoreCase) - || (user.Email ?? string.Empty).Contains(SearchText, StringComparison.OrdinalIgnoreCase) - || (user.UserId ?? string.Empty).Contains(SearchText, StringComparison.OrdinalIgnoreCase)) - .ToList(); - public override bool CanNavigateNext { get => false; protected set { _ = value; } } public override bool CanNavigatePrevious { get => true; protected set { _ = value; } } @@ -107,7 +109,25 @@ public partial class AdministrationPageViewModel : ViewModelBase partial void OnSearchTextChanged(string value) { - OnPropertyChanged(nameof(FilteredUsers)); + UserPage = 1; + HasNextUserPage = false; + } + + partial void OnUserPageChanged(int value) + { + OnPropertyChanged(nameof(HasPreviousUserPage)); + PreviousUserPageCommand.NotifyCanExecuteChanged(); + NextUserPageCommand.NotifyCanExecuteChanged(); + } + + partial void OnHasNextUserPageChanged(bool value) + => NextUserPageCommand.NotifyCanExecuteChanged(); + + partial void OnIsBusyChanged(bool value) + { + SearchUsersCommand.NotifyCanExecuteChanged(); + PreviousUserPageCommand.NotifyCanExecuteChanged(); + NextUserPageCommand.NotifyCanExecuteChanged(); } partial void OnSelectedUserChanged(UserInfo? value) => OnPropertyChanged(nameof(SelectedUsage)); @@ -121,7 +141,7 @@ public partial class AdministrationPageViewModel : ViewModelBase StatusMessage = "Le rôle Administrator est requis."; return; } - if (_api is null || _usageClient is null) + if (_api is null || _usageClient is null || UserSearchClient is null) { StatusMessage = "Client API d’administration indisponible."; return; @@ -141,31 +161,13 @@ public partial class AdministrationPageViewModel : ViewModelBase foreach (var item in usage) UsageOverview.Add(item); - var query = SearchText.Trim(); - var usersEndpoint = string.IsNullOrWhiteSpace(query) - ? new Uri(new Uri(_api.Settings.ApiUrl.TrimEnd('/') + "/", UriKind.Absolute), "users").ToString() - : new Uri(new Uri(_api.Settings.ApiUrl.TrimEnd('/') + "/", UriKind.Absolute), $"users/search/{Uri.EscapeDataString(query)}").ToString(); - - var users = await _api.CallAsync>(HttpMethod.Get, usersEndpoint).ConfigureAwait(true) - ?? throw new InvalidOperationException("Le serveur a renvoyé une liste d’utilisateurs vide."); - - if (!_session.IsAdministrator) - { - ClearAdministrationData(); - StatusMessage = "Le rôle Administrator est requis."; - return; - } - - foreach (var user in users) - { - Users.Add(user); - } - - OnPropertyChanged(nameof(FilteredUsers)); + await LoadUsersPageCoreAsync(1); OnPropertyChanged(nameof(SelectedUsage)); if (_administrationClient is not null) await LoadToolsAsync(); - StatusMessage = Users.Count > 0 ? $"{Users.Count} utilisateur(s) chargé(s)." : "Aucun utilisateur trouvé."; + StatusMessage = Users.Count > 0 + ? $"{Users.Count} utilisateur(s) affiché(s), page {UserPage}." + : "Aucun utilisateur trouvé."; } catch (HttpRequestException ex) when (ex.StatusCode == System.Net.HttpStatusCode.TooManyRequests) { @@ -188,6 +190,83 @@ public partial class AdministrationPageViewModel : ViewModelBase } } + [RelayCommand] + private Task SearchUsersAsync() => LoadUsersPageAsync(1); + + [RelayCommand(CanExecute = nameof(CanGoToPreviousUserPage))] + private Task PreviousUserPageAsync() => LoadUsersPageAsync(UserPage - 1); + + [RelayCommand(CanExecute = nameof(CanGoToNextUserPage))] + private Task NextUserPageAsync() => LoadUsersPageAsync(UserPage + 1); + + private bool CanGoToPreviousUserPage() => !IsBusy && UserPage > 1; + private bool CanGoToNextUserPage() => !IsBusy && HasNextUserPage; + + private async Task LoadUsersPageAsync(int page) + { + if (IsBusy) + return; + if (_session?.IsAdministrator != true) + { + Users.Clear(); + SelectedUser = null; + HasNextUserPage = false; + StatusMessage = "Le rôle Administrator est requis."; + return; + } + if (UserSearchClient is null) + { + StatusMessage = "Client API d’administration indisponible."; + return; + } + + IsBusy = true; + try + { + await LoadUsersPageCoreAsync(page); + StatusMessage = Users.Count > 0 + ? $"{Users.Count} utilisateur(s) affiché(s), page {UserPage}." + : "Aucun utilisateur trouvé."; + } + catch (Exception ex) + { + Users.Clear(); + SelectedUser = null; + HasNextUserPage = false; + StatusMessage = $"Recherche d’utilisateurs indisponible : {ex.Message}"; + } + finally + { + IsBusy = false; + } + } + + private async Task LoadUsersPageCoreAsync(int page) + { + var client = UserSearchClient; + if (client is null) + throw new InvalidOperationException("Client API d’administration indisponible."); + + var result = await client.SearchUsersAsync( + SearchText.Trim(), page).ConfigureAwait(true); + if (_session?.IsAdministrator != true) + { + Users.Clear(); + SelectedUser = null; + HasNextUserPage = false; + StatusMessage = "Le rôle Administrator est requis."; + return; + } + + Users.Clear(); + foreach (var user in result.Users) + Users.Add(user); + SelectedUser = null; + UserPage = page; + HasNextUserPage = result.HasNextPage; + OnPropertyChanged(nameof(SelectedUsage)); + } + private void ClearAdministrationData() { PaymentPurgeReport = ""; @@ -214,7 +293,8 @@ public partial class AdministrationPageViewModel : ViewModelBase EntryValue = ""; EnrollUserId = ""; ConfirmDestructiveAction = false; - OnPropertyChanged(nameof(FilteredUsers)); + UserPage = 1; + HasNextUserPage = false; OnPropertyChanged(nameof(SelectedUsage)); } } diff --git a/src/PostIt/PostIt/Views/Admin/AdministrationPage.axaml b/src/PostIt/PostIt/Views/Admin/AdministrationPage.axaml index 374cdd8af..4e4bd644b 100644 --- a/src/PostIt/PostIt/Views/Admin/AdministrationPage.axaml +++ b/src/PostIt/PostIt/Views/Admin/AdministrationPage.axaml @@ -65,8 +65,6 @@ -