Add server-side admin user pagination
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
05cefaff32
commit
0fa7615a60
10 changed files with 254 additions and 59 deletions
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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<ResourceUsageSummary> { 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<UserInfo> { 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<UserInfo> { new() { UserId = "jean-id", UserName = "jean", FullName = "Jean Dupont" } }
|
||||
: page ? new List<UserInfo>()
|
||||
: new List<UserInfo> { new() { UserId = "alice-id", UserName = "alice" } };
|
||||
result = new AdministrationUserPage(returnedUsers, ManyUsers && !matchingQuery && !page);
|
||||
}
|
||||
else
|
||||
throw new InvalidOperationException($"Unexpected endpoint: {path}");
|
||||
|
|
|
|||
|
|
@ -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]
|
||||
|
|
|
|||
|
|
@ -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<ResourceUsageSummary> 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<UserInfo> 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<List<UserInfo>>(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));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -65,8 +65,6 @@
|
|||
<StackPanel Grid.Row="1" Spacing="8">
|
||||
<TextBlock Text="{Binding Summary.UserCount, StringFormat='Utilisateurs enregistrés : {0}'}"/>
|
||||
<TextBlock Text="{Binding Summary.AdministratorCount, StringFormat='Administrateurs : {0}'}"/>
|
||||
<TextBox Text="{Binding SearchText, Mode=TwoWay}"
|
||||
PlaceholderText="Rechercher un utilisateur..."/>
|
||||
<Button Content="Actualiser"
|
||||
Command="{Binding RefreshCommand}"
|
||||
IsEnabled="{Binding !IsBusy}"/>
|
||||
|
|
@ -91,8 +89,22 @@
|
|||
</ItemsPanelTemplate>
|
||||
</TabControl.ItemsPanel>
|
||||
<TabItem Header="Utilisateurs">
|
||||
<Grid ColumnDefinitions="1.3*,0.7*" ColumnSpacing="12">
|
||||
<ListBox ItemsSource="{Binding FilteredUsers}"
|
||||
<Grid ColumnDefinitions="1.3*,0.7*" ColumnSpacing="12"
|
||||
RowDefinitions="Auto,*" RowSpacing="8">
|
||||
<StackPanel Grid.Row="0" Grid.ColumnSpan="2" Spacing="8">
|
||||
<TextBox Text="{Binding SearchText, Mode=TwoWay}"
|
||||
PlaceholderText="Rechercher par login, prénom ou nom..."/>
|
||||
<WrapPanel>
|
||||
<Button Content="Rechercher" Command="{Binding SearchUsersCommand}" Margin="0,0,8,8"/>
|
||||
<Button Content="Page précédente" Command="{Binding PreviousUserPageCommand}"
|
||||
IsEnabled="{Binding HasPreviousUserPage}" Margin="0,0,8,8"/>
|
||||
<TextBlock Text="{Binding UserPage, StringFormat='Page {0}'}"
|
||||
VerticalAlignment="Center" Margin="0,0,8,8"/>
|
||||
<Button Content="Page suivante" Command="{Binding NextUserPageCommand}"
|
||||
IsEnabled="{Binding HasNextUserPage}" Margin="0,0,8,8"/>
|
||||
</WrapPanel>
|
||||
</StackPanel>
|
||||
<ListBox Grid.Row="1" ItemsSource="{Binding Users}"
|
||||
SelectedItem="{Binding SelectedUser, Mode=TwoWay}">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate>
|
||||
|
|
@ -109,7 +121,7 @@
|
|||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
|
||||
<ScrollViewer Grid.Column="1">
|
||||
<ScrollViewer Grid.Row="1" Grid.Column="1">
|
||||
<Border Padding="12" BorderBrush="#D0D7DE" BorderThickness="1" CornerRadius="6">
|
||||
<StackPanel Spacing="8">
|
||||
<TextBlock Text="Détails" FontWeight="SemiBold" FontSize="18"/>
|
||||
|
|
|
|||
|
|
@ -1,12 +1,16 @@
|
|||
#nullable enable
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Text.Json.Serialization;
|
||||
using Yavsc.Abstract.Identity;
|
||||
|
||||
namespace Yavsc.Abstract.Administration;
|
||||
|
||||
/// <summary>Site administration counts and runtime information.</summary>
|
||||
public sealed record AdministrationSummary(int UserCount, int AdministratorCount, string Assembly, string Runtime);
|
||||
|
||||
/// <summary>A page of users matching an administration search.</summary>
|
||||
public sealed record AdministrationUserPage(IReadOnlyList<UserInfo> Users, bool HasNextPage);
|
||||
|
||||
/// <summary>A role with its current membership count.</summary>
|
||||
public sealed record AdministrationRole(string Id, string Name, int UserCount);
|
||||
|
||||
|
|
|
|||
|
|
@ -15,6 +15,9 @@ public sealed class AdministrationApiClient(IYavscApiClient api, Func<string> ba
|
|||
|
||||
public Task<AdministrationSummary> GetSummaryAsync(CancellationToken ct = default)
|
||||
=> api.CallAsync<AdministrationSummary>(HttpMethod.Get, Path("summary"), ct: ct);
|
||||
public Task<AdministrationUserPage> SearchUsersAsync(string? query, int page, CancellationToken ct = default)
|
||||
=> api.CallAsync<AdministrationUserPage>(HttpMethod.Get,
|
||||
Path($"users?page={page}&query={Escape(query ?? string.Empty)}"), ct: ct);
|
||||
public Task<List<AdministrationRole>> GetRolesAsync(CancellationToken ct = default)
|
||||
=> api.CallAsync<List<AdministrationRole>>(HttpMethod.Get, Path("roles"), ct: ct);
|
||||
public Task EnsureRolesAsync(CancellationToken ct = default)
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
using System.ComponentModel.DataAnnotations;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
|
|
@ -32,6 +33,14 @@ public sealed class SiteAdministrationApiController(IAdministrationService servi
|
|||
public async Task<ActionResult<AdministrationSummary>> Summary(CancellationToken ct)
|
||||
=> Ok(await service.GetSummaryAsync(ct));
|
||||
|
||||
[HttpGet("users"), EndpointSummary("Rechercher les utilisateurs par login ou nom")]
|
||||
[ProducesResponseType<AdministrationUserPage>(200)]
|
||||
public async Task<ActionResult<AdministrationUserPage>> SearchUsers(
|
||||
[FromQuery, StringLength(128)] string? query,
|
||||
[FromQuery, Range(1, int.MaxValue / 25)] int page = 1,
|
||||
CancellationToken ct = default)
|
||||
=> Ok(await service.SearchUsersAsync(query, page, ct));
|
||||
|
||||
[HttpGet("roles"), EndpointSummary("Lister les rôles et leurs effectifs")]
|
||||
public async Task<ActionResult<IReadOnlyList<AdministrationRole>>> Roles(CancellationToken ct)
|
||||
=> Ok(await service.GetRolesAsync(ct));
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ using IdentityServer8.EntityFramework.Entities;
|
|||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Yavsc.Abstract.Administration;
|
||||
using Yavsc.Abstract.Identity;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Server.Helpers;
|
||||
using Yavsc.Server.Models.Calendar;
|
||||
|
|
@ -17,6 +18,8 @@ public sealed partial class AdministrationService(
|
|||
ApplicationDbContext db, UserManager<ApplicationUser> users, RoleManager<IdentityRole> roles,
|
||||
IHttpContextAccessor httpContext) : IAdministrationService
|
||||
{
|
||||
private const int UserPageSize = 25;
|
||||
|
||||
private string Actor => httpContext.HttpContext?.User.GetUserId()
|
||||
?? throw new AdministrationOperationException(401, "Session administrateur indisponible.");
|
||||
|
||||
|
|
@ -35,6 +38,50 @@ public sealed partial class AdministrationService(
|
|||
(await users.GetUsersInRoleAsync(Constants.AdminName)).Count,
|
||||
typeof(AdministrationService).Assembly.GetName().ToString(), System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription);
|
||||
|
||||
public async Task<AdministrationUserPage> SearchUsersAsync(string? query, int page, CancellationToken ct)
|
||||
{
|
||||
if (page < 1 || page > int.MaxValue / UserPageSize)
|
||||
throw Invalid("Le numéro de page est invalide.");
|
||||
|
||||
var normalizedQuery = query?.Trim().ToLowerInvariant();
|
||||
var userQuery = db.Users.AsNoTracking()
|
||||
.Include(user => user.PostalAddress)
|
||||
.Include(user => user.BankInfo)
|
||||
.AsQueryable();
|
||||
|
||||
if (!string.IsNullOrEmpty(normalizedQuery))
|
||||
{
|
||||
userQuery = userQuery.Where(user =>
|
||||
(user.UserName != null && user.UserName.ToLower().Contains(normalizedQuery)) ||
|
||||
(user.FullName != null && user.FullName.ToLower().Contains(normalizedQuery)));
|
||||
}
|
||||
|
||||
var matches = await userQuery
|
||||
.OrderBy(user => user.UserName)
|
||||
.ThenBy(user => user.Id)
|
||||
.Skip((page - 1) * UserPageSize)
|
||||
.Take(UserPageSize + 1)
|
||||
.ToListAsync(ct);
|
||||
|
||||
var hasNextPage = matches.Count > UserPageSize;
|
||||
var result = matches.Take(UserPageSize).Select(user => new UserInfo
|
||||
{
|
||||
UserId = user.Id,
|
||||
UserName = user.UserName,
|
||||
FullName = user.FullName,
|
||||
Email = user.Email,
|
||||
Address = user.PostalAddress?.Address ?? string.Empty,
|
||||
Avatar = user.Avatar,
|
||||
DedicatedGoogleCalendar = user.DedicatedGoogleCalendar,
|
||||
BankInfoSummary = user.BankInfo is { Count: > 0 }
|
||||
? string.Join(" | ", user.BankInfo.Select(bank =>
|
||||
string.IsNullOrWhiteSpace(bank.IBAN) ? bank.BIC : $"{bank.IBAN} / {bank.BIC}"))
|
||||
: string.Empty
|
||||
}).ToArray();
|
||||
|
||||
return new AdministrationUserPage(result, hasNextPage);
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<AdministrationRole>> GetRolesAsync(CancellationToken ct)
|
||||
{
|
||||
var all = await roles.Roles.OrderBy(role => role.Name).ToListAsync(ct);
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ namespace Yavsc.Api.Services;
|
|||
public interface IAdministrationService
|
||||
{
|
||||
Task<AdministrationSummary> GetSummaryAsync(CancellationToken ct);
|
||||
Task<AdministrationUserPage> SearchUsersAsync(string? query, int page, CancellationToken ct);
|
||||
Task<IReadOnlyList<AdministrationRole>> GetRolesAsync(CancellationToken ct);
|
||||
Task EnsureRolesAsync(CancellationToken ct);
|
||||
Task<IReadOnlyList<RoleMember>> GetRoleMembersAsync(string roleId, CancellationToken ct);
|
||||
|
|
|
|||
Loading…
Reference in a new issue