Compare commits

...
Author SHA1 Message Date
0b0a6e6040
No more Platform menu.
Some checks failed
Forgejo Release / release (push) Successful in 14m11s
Dotnet build and test / build (pull_request) Failing after 16m7s
2026-11-14 23:47:14 +00:00
c4d599cda1
Refactor rendez-vous address editing
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-14 23:28:19 +00:00
7893777ab3
Replace status bar with global notifications
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-14 22:44:23 +00:00
910d1ebc35
see th message 2026-11-14 21:33:06 +00:00
f282d14126
si le state persistant est stale ou absent, on accepte le démarrage plutôt que de déclencher l’exception de fond 2026-11-14 21:10:33 +00:00
5ec23d1278
Avoid all users tracking new bugs 2026-11-14 21:08:20 +00:00
6ed1b91019
Starts 1.0.8-rc38 Change description 2026-11-14 19:26:45 +00:00
5c834025d7
enable telemetry 2026-11-14 19:24:18 +00:00
0fa7615a60
Add server-side admin user pagination
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-14 19:18:01 +00:00
05cefaff32
in a scroll viewer 2026-11-14 18:45:32 +00:00
6839d9cac9
Add opt-in PostIt exception reporting
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-14 18:09:45 +00:00
56 changed files with 1310 additions and 637 deletions

View file

@ -2,6 +2,18 @@
# Changelog
## [1.0.8-rc37] - unstable
### Added
* [PostIt] Replace the persistent status bar with a global notification service using ephemeral toasts for info/success and dismissible modal alerts for warnings/errors.
* [PostIt] Refactor rendez-vous address editing around a dedicated physical-address view model and a dedicated address editor page so the map remains usable without a ScrollViewer and the main command form stays compact on small screens.
* [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.
* [PostIt] Telemetry
## [1.0.8-rc36] - unstable
### Added

View file

@ -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))

View file

@ -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(); }
});

View file

@ -30,10 +30,25 @@ internal static class ChatBootState
throw new IOException("Impossible d'enregistrer la deconnexion Android.");
}
internal static bool CanStart(YavscApiClient api) =>
OptedIn && Preferences.GetBoolean("signed-in", false)
&& api.Settings.AndroidKeepChatConnected && !api.IsSigningOut && api.HasValidSession
&& Identity(api) is { } identity && identity == Preferences.GetString("identity", null);
internal static bool CanStart(YavscApiClient api)
{
if (!OptedIn || !api.Settings.AndroidKeepChatConnected || api.IsSigningOut || !api.HasValidSession)
return false;
var identity = Identity(api);
if (identity is null) return false;
var signedIn = Preferences.GetBoolean("signed-in", false);
var storedIdentity = Preferences.GetString("identity", null);
// A valid refresh-capable session can coexist with stale native prefs
// (for example after app relaunch or an interrupted token renewal).
// Treat missing/lagging prefs as recoverable instead of rejecting the
// start outright, but keep strict identity matching when both values exist.
if (!signedIn && string.IsNullOrEmpty(storedIdentity)) return true;
if (signedIn && !string.IsNullOrEmpty(storedIdentity)) return identity == storedIdentity;
return true;
}
internal static string? Identity(YavscApiClient api)
{

View file

@ -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);
}

View file

@ -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}");

View file

@ -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]

View file

@ -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<PostIt.ViewModels.Settings>(
JsonSerializer.Serialize(defaults));
Assert.NotNull(roundTrip);
Assert.True(roundTrip.ShareExceptionReports);
}
/// <summary>
/// First-start regression guard: older settings payloads can
/// still contain <c>ActionStatus</c> from a previous write. This

View file

@ -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)]

View file

@ -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<Settings>();
ServiceProvider.GetRequiredService<YavscApiClient>().StartSessionMaintenance();
var api = ServiceProvider.GetRequiredService<YavscApiClient>();
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<YavscApiClient>()
?.QueueExceptionReport(exception, "PostIt");
}
private static void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs args)
{
if (Current is App app)
app.ServiceProvider?.GetService<YavscApiClient>()
?.QueueExceptionReport(args.Exception, "PostIt");
}
private bool IsProduction()
{
#if DEBUG

View file

@ -1,28 +0,0 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:PostIt.ViewModels"
x:Class="PostIt.Controls.StatusBar"
x:DataType="vm:StatusNotice">
<Border Background="{Binding Background}"
BorderBrush="{Binding BorderBrush}"
BorderThickness="1"
CornerRadius="6"
Padding="8">
<StackPanel Orientation="Horizontal" Spacing="8">
<TextBlock Text="{Binding Glyph}"
FontWeight="Bold"
Foreground="{Binding Foreground}"
VerticalAlignment="Top"/>
<SelectableTextBlock Text="{Binding Message}"
Foreground="{Binding Foreground}"
TextWrapping="Wrap"
VerticalAlignment="Center"/>
<Button Content="{Binding CheckCommandLabel}"
Foreground="{Binding Foreground}"
VerticalAlignment="Center"
IsVisible="{Binding HasCheckCommand}"
Command="{Binding CheckCommand}"
/>
</StackPanel>
</Border>
</UserControl>

View file

@ -1,11 +0,0 @@
using Avalonia.Controls;
namespace PostIt.Controls;
public partial class StatusBar : UserControl
{
public StatusBar()
{
InitializeComponent();
}
}

View file

@ -55,6 +55,7 @@ public static class ServiceCollectionHelpers
services.AddSingleton<ChatViewModel>();
services.AddSingleton<ChatHubConnection>();
services.AddSingleton<MessagingSession>();
services.AddSingleton(NotificationService.Instance);
// Android activities need fresh controls; retain state in singleton VMs.
void AddReusablePage<TPage>() where TPage : class
@ -87,6 +88,7 @@ public static class ServiceCollectionHelpers
services.AddTransient<ChatPage>();
services.AddTransient<CallPage>();
services.AddTransient<RdvPage>();
services.AddTransient<AddressEditorPage>();
services.AddTransient<BrushPage>();
services.AddTransient<BillingQueriesPage>();
services.AddTransient<BillingQueryDetailsPage>();

View file

@ -0,0 +1,25 @@
using System;
using PostIt.Models;
namespace PostIt.Services;
public sealed class NotificationService
{
public static NotificationService Instance { get; } = new();
public event EventHandler<NotificationRequest>? NotificationRequested;
private NotificationService()
{
}
public void Show(string message, StatusSeverity severity = StatusSeverity.Info, string? actionLabel = null, Action? action = null)
=> NotificationRequested?.Invoke(this, new NotificationRequest(message, severity, actionLabel, action));
public void Hide()
{
NotificationRequested?.Invoke(this, new NotificationRequest(string.Empty, StatusSeverity.Info));
}
}
public sealed record NotificationRequest(string Message, StatusSeverity Severity, string? ActionLabel = null, Action? Action = null);

View file

@ -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
/// <summary>The current OIDC id_token, or null.</summary>
public string? CurrentIdToken => _tokens?.IdToken;
public async Task<bool> 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)

View file

@ -51,6 +51,7 @@ public class ViewLocator : IDataTemplate
CommandFormsPageViewModel => services.GetRequiredService<CommandFormsPage>(),
BrushViewModel => services.GetRequiredService<BrushPage>(),
RdvViewModel => services.GetRequiredService<RdvPage>(),
PhysicalAddressViewModel => services.GetRequiredService<AddressEditorPage>(),
SignaturePageViewModel => services.GetRequiredService<SignaturePage>(),
AddCircleMemberDialogViewModel => services.GetRequiredService<AddCircleMemberDialog>(),
ConfirmationDialogViewModel => services.GetRequiredService<ConfirmationDialog>(),

View file

@ -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));
}
}

View file

@ -0,0 +1,190 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using PostIt.Services;
namespace PostIt.ViewModels.Commands;
public partial class PhysicalAddressViewModel : ViewModelBase
{
private readonly IReverseGeocodingService _reverseGeocodingService;
private CancellationTokenSource? _reverseGeocodeCts;
private double? _lastResolvedLatitude;
private double? _lastResolvedLongitude;
private string? _lastResolvedAddress;
private const double ReverseGeocodingCacheToleranceDegrees = 0.0001;
private static readonly TimeSpan ReverseGeocodingDebounce = TimeSpan.FromMilliseconds(350);
[ObservableProperty]
public partial string Address { get; set; } = string.Empty;
[ObservableProperty]
public partial string SuggestedAddress { get; set; } = string.Empty;
[ObservableProperty]
public partial bool IsResolvingAddress { get; set; }
[ObservableProperty]
public partial double? Latitude { get; set; }
[ObservableProperty]
public partial double? Longitude { get; set; }
[ObservableProperty]
public partial bool IsBusy { get; set; }
public bool HasSuggestedAddress => !string.IsNullOrWhiteSpace(SuggestedAddress);
public bool HasSuggestedAddressPanel => HasSuggestedAddress || IsResolvingAddress;
public bool CanUseCurrentLocation => !IsBusy;
public override bool CanNavigateNext { get; protected set; }
public override bool CanNavigatePrevious { get; protected set; } = true;
public PhysicalAddressViewModel(IReverseGeocodingService reverseGeocodingService)
{
_reverseGeocodingService = reverseGeocodingService ?? throw new ArgumentNullException(nameof(reverseGeocodingService));
}
public void ApplyLocationFromMap(double latitude, double longitude)
{
Latitude = Math.Round(latitude, 6);
Longitude = Math.Round(longitude, 6);
}
public void NotifyReverseGeocodingStarted()
{
IsResolvingAddress = true;
}
public void NotifyReverseGeocodingUnavailable()
{
IsResolvingAddress = false;
}
public void ApplyResolvedAddress(string address)
{
if (string.IsNullOrWhiteSpace(address))
return;
var trimmedAddress = address.Trim();
if (string.IsNullOrWhiteSpace(Address))
{
Address = trimmedAddress;
SuggestedAddress = string.Empty;
IsResolvingAddress = false;
return;
}
if (string.Equals(Address.Trim(), trimmedAddress, StringComparison.Ordinal))
{
SuggestedAddress = string.Empty;
IsResolvingAddress = false;
return;
}
SuggestedAddress = trimmedAddress;
IsResolvingAddress = false;
}
[RelayCommand(CanExecute = nameof(HasSuggestedAddress))]
private void ApplySuggestedAddress()
{
if (string.IsNullOrWhiteSpace(SuggestedAddress))
return;
Address = SuggestedAddress.Trim();
SuggestedAddress = string.Empty;
IsResolvingAddress = false;
}
[RelayCommand(CanExecute = nameof(CanUseCurrentLocation))]
private async Task UseCurrentLocationAsync()
{
if (!CanUseCurrentLocation)
return;
IsBusy = true;
try
{
var result = await Platform.TryGetCurrentLocationAsync(default).ConfigureAwait(true);
if (!result.IsSuccess || !result.Latitude.HasValue || !result.Longitude.HasValue)
{
return;
}
Latitude = result.Latitude.Value;
Longitude = result.Longitude.Value;
}
finally
{
IsBusy = false;
}
}
public async Task TryResolveAddressAsync(double latitude, double longitude)
{
if (_lastResolvedLatitude.HasValue
&& _lastResolvedLongitude.HasValue
&& AreCoordinatesClose(_lastResolvedLatitude.Value, _lastResolvedLongitude.Value, latitude, longitude)
&& !string.IsNullOrWhiteSpace(_lastResolvedAddress))
{
ApplyResolvedAddress(_lastResolvedAddress);
return;
}
_reverseGeocodeCts?.Cancel();
_reverseGeocodeCts?.Dispose();
_reverseGeocodeCts = new CancellationTokenSource();
var cancellationToken = _reverseGeocodeCts.Token;
try
{
NotifyReverseGeocodingStarted();
await Task.Delay(ReverseGeocodingDebounce, cancellationToken).ConfigureAwait(true);
var resolved = await _reverseGeocodingService
.TryResolveAddressAsync(latitude, longitude, cancellationToken)
.ConfigureAwait(true);
if (!string.IsNullOrWhiteSpace(resolved))
{
_lastResolvedLatitude = latitude;
_lastResolvedLongitude = longitude;
_lastResolvedAddress = resolved;
ApplyResolvedAddress(resolved);
return;
}
NotifyReverseGeocodingUnavailable();
}
catch (OperationCanceledException)
{
IsResolvingAddress = false;
}
}
partial void OnSuggestedAddressChanged(string value)
{
OnPropertyChanged(nameof(HasSuggestedAddress));
OnPropertyChanged(nameof(HasSuggestedAddressPanel));
ApplySuggestedAddressCommand.NotifyCanExecuteChanged();
}
partial void OnIsResolvingAddressChanged(bool value)
{
OnPropertyChanged(nameof(HasSuggestedAddressPanel));
}
public static bool AreCoordinatesClose(
double latitudeA,
double longitudeA,
double latitudeB,
double longitudeB)
{
return Math.Abs(latitudeA - latitudeB) <= ReverseGeocodingCacheToleranceDegrees
&& Math.Abs(longitudeA - longitudeB) <= ReverseGeocodingCacheToleranceDegrees;
}
}

View file

@ -17,21 +17,64 @@ public partial class RdvViewModel : BillingCommandPageViewModel
public override string SupportMessage => "Complétez les informations du rendez-vous puis postez la commande.";
[ObservableProperty]
public partial string Address { get; set; } = string.Empty;
public PhysicalAddressViewModel PhysicalAddress { get; }
[ObservableProperty]
public partial string SuggestedAddress { get; set; } = string.Empty;
public string Address
{
get => PhysicalAddress.Address;
set
{
if (PhysicalAddress.Address == value)
return;
[ObservableProperty]
public partial bool IsResolvingAddress { get; set; }
PhysicalAddress.Address = value;
if (!_hydratingExistingQuery)
_existingLocationId = null;
}
}
[ObservableProperty]
public partial double? Latitude { get; set; }
public string SuggestedAddress
{
get => PhysicalAddress.SuggestedAddress;
set => PhysicalAddress.SuggestedAddress = value;
}
[ObservableProperty]
public partial double? Longitude { get; set; }
public bool IsResolvingAddress
{
get => PhysicalAddress.IsResolvingAddress;
set => PhysicalAddress.IsResolvingAddress = value;
}
public double? Latitude
{
get => PhysicalAddress.Latitude;
set
{
if (PhysicalAddress.Latitude == value)
return;
PhysicalAddress.Latitude = value;
if (!_hydratingExistingQuery)
_existingLocationId = null;
}
}
public double? Longitude
{
get => PhysicalAddress.Longitude;
set
{
if (PhysicalAddress.Longitude == value)
return;
PhysicalAddress.Longitude = value;
if (!_hydratingExistingQuery)
_existingLocationId = null;
}
}
public IAsyncRelayCommand UseCurrentLocationCommand => PhysicalAddress.UseCurrentLocationCommand;
public IRelayCommand ApplySuggestedAddressCommand => PhysicalAddress.ApplySuggestedAddressCommand;
[ObservableProperty]
public partial DateTime EventDate { get; set; }
@ -48,15 +91,16 @@ public partial class RdvViewModel : BillingCommandPageViewModel
}
}
public bool HasSuggestedAddress => PhysicalAddress.HasSuggestedAddress;
public bool HasSuggestedAddressPanel => PhysicalAddress.HasSuggestedAddressPanel;
public RdvViewModel(ActivityInfo activity, ActivityUserDisplayItem performer, CommandFormSummary form, BillingApiClient billingClient)
: base(activity, performer, form, billingClient)
{
PhysicalAddress = new PhysicalAddressViewModel(new NominatimReverseGeocodingService());
EventDate = DateTime.Now.AddDays(1);
}
public bool HasSuggestedAddress => !string.IsNullOrWhiteSpace(SuggestedAddress);
public bool HasSuggestedAddressPanel => HasSuggestedAddress || IsResolvingAddress;
protected override void ApplyExistingQuery(BillingQueryDetailsDto existingQuery)
{
_hydratingExistingQuery = true;
@ -75,10 +119,10 @@ public partial class RdvViewModel : BillingCommandPageViewModel
if (existingQuery.Location is not null)
{
_existingLocationId = existingQuery.Location.Id;
Address = existingQuery.Location.Address ?? string.Empty;
SuggestedAddress = string.Empty;
Latitude = existingQuery.Location.Latitude;
Longitude = existingQuery.Location.Longitude;
PhysicalAddress.Address = existingQuery.Location.Address ?? string.Empty;
PhysicalAddress.SuggestedAddress = string.Empty;
PhysicalAddress.Latitude = existingQuery.Location.Latitude;
PhysicalAddress.Longitude = existingQuery.Location.Longitude;
}
else
{
@ -90,44 +134,6 @@ public partial class RdvViewModel : BillingCommandPageViewModel
this.SetInfoStatus($"Commande #{existingQuery.Id} chargée.");
}
[RelayCommand(CanExecute = nameof(CanUseCurrentLocation))]
private async Task UseCurrentLocationAsync()
{
if (!CanUseCurrentLocation)
{
return;
}
IsBusy = true;
try
{
var result = await Platform.TryGetCurrentLocationAsync(default).ConfigureAwait(true);
if (!result.IsSuccess || !result.Latitude.HasValue || !result.Longitude.HasValue)
{
this.SetWarningStatus(result.Message);
return;
}
Latitude = result.Latitude.Value;
Longitude = result.Longitude.Value;
this.SetInfoStatus(string.IsNullOrWhiteSpace(Address)
? "Position récupérée. Complétez l'adresse puis envoyez la commande."
: result.Message);
}
catch (OperationCanceledException)
{
this.SetWarningStatus("La récupération de la position a été annulée.");
}
catch (Exception ex)
{
this.SetErrorStatus($"Impossible de récupérer la position: {ex.Message}");
}
finally
{
IsBusy = false;
}
}
protected static BillingLocationDto BuildLocationPayload(string address, double? latitude, double? longitude, long? locationId = null)
{
if (latitude.HasValue && longitude.HasValue)
@ -150,10 +156,9 @@ public partial class RdvViewModel : BillingCommandPageViewModel
public void ApplyLocationFromMap(double latitude, double longitude)
{
Latitude = Math.Round(latitude, 6);
Longitude = Math.Round(longitude, 6);
PhysicalAddress.ApplyLocationFromMap(latitude, longitude);
if (string.IsNullOrWhiteSpace(Address))
if (string.IsNullOrWhiteSpace(PhysicalAddress.Address))
{
this.SetInfoStatus("Position sélectionnée sur la carte. Complétez l'adresse puis envoyez la commande.");
return;
@ -164,8 +169,8 @@ public partial class RdvViewModel : BillingCommandPageViewModel
public void NotifyReverseGeocodingStarted()
{
IsResolvingAddress = true;
this.SetInfoStatus(string.IsNullOrWhiteSpace(Address)
PhysicalAddress.NotifyReverseGeocodingStarted();
this.SetInfoStatus(string.IsNullOrWhiteSpace(PhysicalAddress.Address)
? "Recherche de l'adresse depuis la carte..."
: "Recherche d'une adresse suggérée..."
);
@ -173,8 +178,8 @@ public partial class RdvViewModel : BillingCommandPageViewModel
public void NotifyReverseGeocodingUnavailable()
{
IsResolvingAddress = false;
if (HasSuggestedAddress || !string.IsNullOrWhiteSpace(Address))
PhysicalAddress.NotifyReverseGeocodingUnavailable();
if (PhysicalAddress.HasSuggestedAddress || !string.IsNullOrWhiteSpace(PhysicalAddress.Address))
return;
this.SetInfoStatus("Position sélectionnée sur la carte. Complétez l'adresse puis envoyez la commande.");
@ -182,85 +187,30 @@ public partial class RdvViewModel : BillingCommandPageViewModel
public void ApplyResolvedAddress(string address)
{
PhysicalAddress.ApplyResolvedAddress(address);
if (string.IsNullOrWhiteSpace(address))
return;
var trimmedAddress = address.Trim();
if (string.IsNullOrWhiteSpace(Address))
if (string.IsNullOrWhiteSpace(PhysicalAddress.Address))
{
Address = trimmedAddress;
SuggestedAddress = string.Empty;
IsResolvingAddress = false;
this.SetInfoStatus("Adresse mise à jour depuis la carte.");
return;
}
if (string.Equals(Address.Trim(), trimmedAddress, StringComparison.Ordinal))
if (string.Equals(PhysicalAddress.Address.Trim(), trimmedAddress, StringComparison.Ordinal))
{
SuggestedAddress = string.Empty;
IsResolvingAddress = false;
return;
}
SuggestedAddress = trimmedAddress;
IsResolvingAddress = false;
this.SetInfoStatus("Adresse suggérée depuis la carte. Appliquez-la si besoin.");
}
[RelayCommand(CanExecute = nameof(HasSuggestedAddress))]
private void ApplySuggestedAddress()
{
if (string.IsNullOrWhiteSpace(SuggestedAddress))
return;
Address = SuggestedAddress.Trim();
SuggestedAddress = string.Empty;
IsResolvingAddress = false;
this.SetInfoStatus("Adresse suggérée appliquée.");
}
partial void OnSuggestedAddressChanged(string value)
{
OnPropertyChanged(nameof(HasSuggestedAddress));
OnPropertyChanged(nameof(HasSuggestedAddressPanel));
ApplySuggestedAddressCommand.NotifyCanExecuteChanged();
}
partial void OnIsResolvingAddressChanged(bool value)
{
OnPropertyChanged(nameof(HasSuggestedAddressPanel));
}
partial void OnEventDateChanged(DateTime value)
{
OnPropertyChanged(nameof(EventDateSelection));
}
partial void OnAddressChanged(string value)
{
if (_hydratingExistingQuery)
return;
_existingLocationId = null;
}
partial void OnLatitudeChanged(double? value)
{
if (_hydratingExistingQuery)
return;
_existingLocationId = null;
}
partial void OnLongitudeChanged(double? value)
{
if (_hydratingExistingQuery)
return;
_existingLocationId = null;
}
protected override async Task SubmitAsync()
{
if (!IsSupported)
@ -275,26 +225,23 @@ public partial class RdvViewModel : BillingCommandPageViewModel
return;
}
if (string.IsNullOrWhiteSpace(Address))
if (string.IsNullOrWhiteSpace(PhysicalAddress.Address))
{
this.SetWarningStatus("L'adresse du rendez-vous est requise.");
return;
}
if (string.IsNullOrWhiteSpace(Reason))
{
this.SetWarningStatus("Le motif du rendez-vous est requis.");
return;
}
IsBusy = true;
try
{
var address = Address.Trim();
var locationPayload = BuildLocationPayload(address, Latitude, Longitude, IsEditingExisting ? _existingLocationId : null);
var address = PhysicalAddress.Address.Trim();
var locationPayload = BuildLocationPayload(address, PhysicalAddress.Latitude, PhysicalAddress.Longitude, IsEditingExisting ? _existingLocationId : null);
var payload = new BillingQueryDetailsDto
{

View file

@ -1,4 +1,6 @@
using Microsoft.Extensions.DependencyInjection;
using PostIt.Models;
using PostIt.Services;
namespace PostIt.ViewModels;
@ -22,13 +24,22 @@ public static class ActionStatusViewModelExtensions
public static void SetStatus(this IActionStatusViewModel viewModel, string message, StatusSeverity severity)
{
var normalizedMessage = string.IsNullOrWhiteSpace(message) ? "Pret." : message.Trim();
viewModel.StatusMessage = normalizedMessage;
viewModel.ActionStatus = severity switch
var statusNotice = severity switch
{
StatusSeverity.Error => StatusNotice.Error(normalizedMessage),
StatusSeverity.Warning => StatusNotice.Warning(normalizedMessage),
_ => StatusNotice.Info(normalizedMessage),
};
viewModel.StatusMessage = normalizedMessage;
viewModel.ActionStatus = statusNotice;
if (App.Current is App app && app.ServiceProvider is { } serviceProvider)
{
var settings = serviceProvider.GetRequiredService<Settings>();
settings.SetActionStatus(normalizedMessage, severity);
var notificationService = serviceProvider.GetRequiredService<NotificationService>();
notificationService.Show(normalizedMessage, severity);
}
}
}

View file

@ -9,6 +9,8 @@ using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using PostIt.Models;
using PostIt.Services;
@ -67,6 +69,8 @@ public partial class Settings : ViewModelBase
[ObservableProperty]
public partial bool AndroidKeepChatConnected { get; set; }
[ObservableProperty]
public partial bool ShareExceptionReports { get; set; }
[ObservableProperty]
public partial Dictionary<string, string[]> ChatRoomsByAccount { get; set; } = new();
[JsonIgnore]
public bool SupportsBackgroundChatService => OperatingSystem.IsAndroid();
@ -174,6 +178,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<string, string[]> value) => MarkDirty();
/// <summary>
@ -441,6 +446,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 +527,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;
}
/// <summary>

View file

@ -11,11 +11,10 @@ public sealed class StatusNotice
public string Background { get; }
public string BorderBrush { get; }
public string Foreground { get; }
public bool HasCheckCommand { get => CheckCommand != null; }
public bool HasCheckCommand => CheckCommand is not null;
public bool IsTransient => Severity == StatusSeverity.Info && CheckCommand is null;
public bool IsModal => !IsTransient;
public ICommand? CheckCommand { get; }
public string CheckCommandLabel { get; }
public StatusNotice(string message, StatusSeverity severity, ICommand? checkCommand)
@ -27,7 +26,7 @@ public sealed class StatusNotice
{
StatusSeverity.Error => ("!", "#7F1D1D", "#C62828", "#e1f0f6"),
StatusSeverity.Warning => ("~", "#7C4A03", "#E6A700", "#eaeaea"),
_ => ("i", "#E8F0FE", "#5B8DEF", "#1E3A8A"),
_ => ("✓", "#E8F0FE", "#5B8DEF", "#1E3A8A"),
};
CheckCommand = checkCommand;
CheckCommandLabel = HasCheckCommand ?

View file

@ -48,8 +48,7 @@
<!-- Action buttons -->
<Grid Grid.Row="3" ColumnDefinitions="*,Auto,Auto" Margin="0,8,0,0">
<postitControls:StatusBar Grid.Column="0"
DataContext="{Binding ActionStatus}" />
<Button Grid.Column="1" Content="Ajouter"
x:Name="AddButton"
Command="{Binding AddAsync}"

View file

@ -102,8 +102,7 @@
<!-- Status bar -->
<Grid Grid.Row="2" ColumnDefinitions="*,Auto" Margin="12,0,12,12">
<postitControls:StatusBar Grid.Column="0"
DataContext="{Binding ActionStatus}" />
<ProgressBar Grid.Column="1" IsIndeterminate="True"
IsVisible="{Binding IsBusy}"
Width="120"/>

View file

@ -54,8 +54,7 @@
<!-- Status bar -->
<Grid Grid.Row="3" ColumnDefinitions="*,Auto">
<postitControls:StatusBar Grid.Column="0"
DataContext="{Binding ActionStatus}" />
<ProgressBar Grid.Column="1" IsIndeterminate="True"
IsVisible="{Binding IsBusy}"
Width="120"/>

View file

@ -132,8 +132,7 @@
</Grid>
<Grid Grid.Row="2" ColumnDefinitions="*,Auto">
<postitControls:StatusBar Grid.Column="0"
DataContext="{Binding ActionStatus}" />
<ProgressBar Grid.Column="1" Width="120" IsIndeterminate="True" IsVisible="{Binding IsBusy}" />
</Grid>
</Grid>

View file

@ -82,8 +82,7 @@
</ListBox>
<Grid Grid.Row="4" ColumnDefinitions="*,Auto" Margin="0,12,0,0">
<postitControls:StatusBar Grid.Column="0"
DataContext="{Binding ActionStatus}" />
<ProgressBar Grid.Column="1" Width="120" IsIndeterminate="True" IsVisible="{Binding IsBusy}" />
</Grid>
</Grid>

View file

@ -174,8 +174,7 @@
</ScrollViewer>
<Grid Grid.Row="3" ColumnDefinitions="*,Auto" Margin="0,8,0,0">
<postitControls:StatusBar Grid.Column="0"
DataContext="{Binding ActionStatus}" />
<ProgressBar Grid.Column="1"
Width="120"
IsIndeterminate="True"

View file

@ -42,8 +42,7 @@
<Button Grid.Column="4"
Content="Demandes en cours (validées, en lecture seule)"
Command="{Binding OpenOngoingQueriesCommand}" />
<postitControls:StatusBar Grid.Column="6"
DataContext="{Binding ActionStatus}" />
</Grid>
</Grid>
</ContentPage>

View file

@ -187,8 +187,7 @@
<Button Grid.Column="0"
Content="{Binding SendLabel}"
Command="{Binding SendCommand}" />
<postitControls:StatusBar Grid.Column="2"
DataContext="{Binding ActionStatus}" />
<ProgressBar Grid.Column="3"
Width="120"
IsIndeterminate="True"

View file

@ -69,8 +69,7 @@
</ListBox>
<Grid Grid.Row="3" ColumnDefinitions="*,Auto" Margin="0,12,0,0">
<postitControls:StatusBar Grid.Column="0"
DataContext="{Binding ActionStatus}" />
<ProgressBar Grid.Column="1" Width="120" IsIndeterminate="True" IsVisible="{Binding IsBusy}" />
</Grid>
</Grid>

View file

@ -139,7 +139,7 @@
<ProgressBar Width="120"
IsIndeterminate="True"
IsVisible="{Binding IsBusy}" />
<postitControls:StatusBar DataContext="{Binding ActionStatus}" />
</StackPanel>
</Grid>
</Grid>

View file

@ -97,8 +97,7 @@
</Grid>
<Grid Grid.Row="4" ColumnDefinitions="*,Auto" Margin="0,12,0,0">
<postitControls:StatusBar Grid.Column="0"
DataContext="{Binding ActionStatus}" />
<ProgressBar Grid.Column="1" Width="120" IsIndeterminate="True" IsVisible="{Binding IsBusy}" />
</Grid>
</Grid>

View file

@ -55,8 +55,8 @@
</StackPanel>
</DataTemplate>
</ContentPage.DataTemplates>
<Grid RowDefinitions="Auto,Auto,*" Margin="16" RowSpacing="12">
<ScrollViewer HorizontalScrollBarVisibility="Disabled">
<Grid RowDefinitions="Auto,Auto,*" Margin="16" RowSpacing="12" >
<TextBlock Grid.Row="0"
Text="Administration"
FontSize="22"
@ -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"/>
@ -271,4 +283,5 @@
</TabItem>
</TabControl>
</Grid>
</ScrollViewer>
</ContentPage>

View file

@ -321,9 +321,6 @@
Text="Choisissez un billet dans la liste pour le lire."
TextWrapping="Wrap" />
</Grid>
<postitControls:StatusBar
x:Name="StatusBar"
Grid.Row="5"
DataContext="{Binding ActionStatus}" />
</Grid>
</ContentPage>

View file

@ -70,8 +70,6 @@ public partial class BlogsPage : ContentPage
PostEditor.Margin = new Thickness(compact ? 4 : 12);
PostEditor.RowSpacing = compact ? 2 : 10;
}
SetArea(StatusBar, sideBySide ? 1 : isWide ? 3 : 5, sideBySide ? 2 : 0,
columnSpan: isWide && !sideBySide ? 3 : 1);
if (_isWideLayout == isWide)
return;
_isWideLayout = isWide;

View file

@ -107,10 +107,7 @@
IsVisible="{Binding LanCall.Incoming}" />
</StackPanel>
<postitControls:StatusBar
x:Name="StatusBar"
Grid.Row="4"
DataContext="{Binding Status}" />
</Grid>
</ContentPage>

View file

@ -0,0 +1,53 @@
<ContentPage xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cvm="using:PostIt.ViewModels.Commands"
xmlns:mapsui="using:Mapsui.UI.Avalonia"
x:Class="PostIt.Views.Commands.AddressEditorPage"
x:DataType="cvm:PhysicalAddressViewModel"
Header="Adresse">
<Grid RowDefinitions="Auto,*" MaxWidth="760" Margin="16">
<StackPanel Grid.Row="0" Spacing="10">
<TextBlock Text="Adresse" FontWeight="SemiBold" />
<TextBox Text="{Binding Address, Mode=TwoWay}" />
<Button Content="Utiliser ma position"
HorizontalAlignment="Stretch"
Click="OnUseCurrentLocationClicked"
IsEnabled="{Binding CanUseCurrentLocation}" />
<StackPanel Spacing="8" IsVisible="{Binding HasSuggestedAddressPanel}">
<TextBlock Text="{Binding SuggestedAddress, StringFormat='Adresse suggérée: {0}'}"
TextWrapping="Wrap"
Opacity="0.8" />
<Button Content="Utiliser"
HorizontalAlignment="Stretch"
IsVisible="{Binding HasSuggestedAddress}"
Command="{Binding ApplySuggestedAddressCommand}" />
<ProgressBar Height="4"
IsIndeterminate="True"
IsVisible="{Binding IsResolvingAddress}" />
</StackPanel>
<Grid ColumnDefinitions="*,12,*">
<Button Grid.Column="0"
Content="Retour"
HorizontalAlignment="Stretch"
Click="OnBackClicked" />
<Button Grid.Column="2"
Content="Valider"
HorizontalAlignment="Stretch"
Click="OnValidateClicked" />
</Grid>
</StackPanel>
<Border Grid.Row="1" Margin="0,12,0,0" CornerRadius="8" ClipToBounds="True">
<StackPanel Spacing="6">
<TextBlock Text="Carte: cliquez pour positionner le rendez-vous"
TextWrapping="Wrap"
Opacity="0.85" />
<mapsui:MapControl x:Name="LocationMap"
Height="360" />
</StackPanel>
</Border>
</Grid>
</ContentPage>

View file

@ -0,0 +1,188 @@
using System;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using Mapsui;
using Mapsui.Layers;
using Mapsui.Projections;
using Mapsui.Styles;
using Mapsui.Tiling;
using Mapsui.UI.Avalonia;
using PostIt.ViewModels.Commands;
namespace PostIt.Views.Commands;
public partial class AddressEditorPage : ContentPage
{
private const double DefaultLatitude = 48.8566;
private const double DefaultLongitude = 2.3522;
private const int DefaultZoomLevel = 4;
private const int SelectedZoomLevel = 13;
private MapControl? _locationMap;
private MemoryLayer? _selectionLayer;
private PhysicalAddressViewModel? _currentViewModel;
public AddressEditorPage()
{
InitializeComponent();
InitializeMap();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void InitializeMap()
{
_locationMap = this.FindControl<MapControl>("LocationMap");
if (_locationMap is null)
return;
var map = new Map();
map.Layers.Add(OpenStreetMap.CreateTileLayer());
_selectionLayer = CreateSelectionLayer();
map.Layers.Add(_selectionLayer);
_locationMap.Map = map;
_locationMap.MapTapped += OnMapTapped;
DataContextChanged += OnDataContextChanged;
AttachViewModel(DataContext as PhysicalAddressViewModel);
}
private void OnDataContextChanged(object? sender, EventArgs e)
{
AttachViewModel(DataContext as PhysicalAddressViewModel);
CenterFromViewModel();
}
private async void OnMapTapped(object? sender, MapEventArgs e)
{
if (DataContext is not PhysicalAddressViewModel vm)
return;
var (longitude, latitude) = SphericalMercator.ToLonLat(e.WorldPosition.X, e.WorldPosition.Y);
vm.ApplyLocationFromMap(latitude, longitude);
UpdateMarkerFromViewModel();
CenterMap(latitude, longitude, zoomLevel: SelectedZoomLevel);
await TryResolveAddressAsync(vm, latitude, longitude);
}
private async void OnUseCurrentLocationClicked(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
if (DataContext is not PhysicalAddressViewModel vm)
return;
await vm.UseCurrentLocationCommand.ExecuteAsync(null);
UpdateMarkerFromViewModel();
CenterFromViewModel();
if (vm.Latitude.HasValue && vm.Longitude.HasValue)
await vm.TryResolveAddressAsync(vm.Latitude.Value, vm.Longitude.Value);
}
private async void OnBackClicked(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
if (Application.Current is App app)
await app.GoBackAsync();
}
private async void OnValidateClicked(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
if (Application.Current is App app)
await app.GoBackAsync();
}
private void AttachViewModel(PhysicalAddressViewModel? vm)
{
if (_currentViewModel is not null)
_currentViewModel.PropertyChanged -= OnViewModelPropertyChanged;
_currentViewModel = vm;
if (_currentViewModel is not null)
_currentViewModel.PropertyChanged += OnViewModelPropertyChanged;
UpdateMarkerFromViewModel();
}
private void OnViewModelPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(PhysicalAddressViewModel.Latitude)
|| e.PropertyName == nameof(PhysicalAddressViewModel.Longitude))
{
UpdateMarkerFromViewModel();
}
}
private void CenterFromViewModel()
{
if (DataContext is not PhysicalAddressViewModel vm)
{
CenterMap(DefaultLatitude, DefaultLongitude, zoomLevel: DefaultZoomLevel);
return;
}
if (vm.Latitude.HasValue && vm.Longitude.HasValue)
{
CenterMap(vm.Latitude.Value, vm.Longitude.Value, zoomLevel: SelectedZoomLevel);
return;
}
CenterMap(DefaultLatitude, DefaultLongitude, zoomLevel: DefaultZoomLevel);
}
private void CenterMap(double latitude, double longitude, int zoomLevel)
{
if (_locationMap?.Map is null)
return;
var (x, y) = SphericalMercator.FromLonLat(longitude, latitude);
_locationMap.Map.Navigator.CenterOn(x, y);
_locationMap.Map.Navigator.ZoomToLevel(zoomLevel);
}
private void UpdateMarkerFromViewModel()
{
if (_selectionLayer is null)
return;
if (DataContext is not PhysicalAddressViewModel vm
|| !vm.Latitude.HasValue
|| !vm.Longitude.HasValue)
{
_selectionLayer.Features = Enumerable.Empty<IFeature>();
_locationMap?.RefreshData(ChangeType.Discrete);
return;
}
var (x, y) = SphericalMercator.FromLonLat(vm.Longitude.Value, vm.Latitude.Value);
_selectionLayer.Features = new IFeature[] { new PointFeature(x, y) };
_locationMap?.RefreshData(ChangeType.Discrete);
}
private static MemoryLayer CreateSelectionLayer()
{
return new MemoryLayer("selected-location")
{
Style = new SymbolStyle
{
SymbolType = SymbolType.Ellipse,
Fill = new Brush(Color.Crimson),
Outline = new Pen(Color.White, 2),
SymbolScale = 0.9,
},
Features = Enumerable.Empty<IFeature>(),
};
}
private Task TryResolveAddressAsync(PhysicalAddressViewModel vm, double latitude, double longitude)
{
return vm.TryResolveAddressAsync(latitude, longitude);
}
}

View file

@ -94,8 +94,7 @@
Content="{Binding SubmitLabel}"
Command="{Binding SubmitCommand}"
IsEnabled="{Binding IsSupported}" />
<postitControls:StatusBar Grid.Column="2"
DataContext="{Binding ActionStatus}" />
<ProgressBar Grid.Column="3"
Width="120"
IsIndeterminate="True"

View file

@ -2,124 +2,79 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cvm="using:PostIt.ViewModels.Commands"
xmlns:mapsui="using:Mapsui.UI.Avalonia"
xmlns:postitControls="using:PostIt.Controls"
x:Class="PostIt.Views.Commands.RdvPage"
x:DataType="cvm:RdvViewModel"
Header="Commande billing">
<ScrollViewer>
<Grid RowDefinitions="Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto" ColumnDefinitions="Auto,*" Margin="12">
<TextBlock Grid.Row="0" Grid.ColumnSpan="2"
Text="{Binding Title}"
FontSize="18"
FontWeight="Bold" />
<ScrollViewer HorizontalScrollBarVisibility="Disabled">
<StackPanel Margin="16" Spacing="10" MaxWidth="760">
<TextBlock Text="{Binding Title}"
FontSize="22"
FontWeight="Bold"
TextWrapping="Wrap" />
<TextBlock Grid.Row="1" Grid.ColumnSpan="2"
Margin="0,4,0,12"
Text="{Binding SupportMessage}"
<TextBlock Text="{Binding SupportMessage}"
Margin="0,0,0,6"
TextWrapping="Wrap"
Opacity="0.8" />
<TextBlock Grid.Row="2" Text="Utilisateur" VerticalAlignment="Center" Margin="0,0,12,8" />
<TextBox Grid.Row="2" Grid.Column="1" Text="{Binding PerformerLabel}" IsReadOnly="True" Margin="0,0,0,8" />
<TextBlock Text="Utilisateur" FontWeight="SemiBold" />
<TextBox Text="{Binding PerformerLabel}" IsReadOnly="True" />
<TextBlock Grid.Row="3" Text="Activité" VerticalAlignment="Center" Margin="0,0,12,8" />
<TextBox Grid.Row="3" Grid.Column="1" Text="{Binding ActivityLabel}" IsReadOnly="True" Margin="0,0,0,8" />
<TextBlock Text="Activité" FontWeight="SemiBold" />
<TextBox Text="{Binding ActivityLabel}" IsReadOnly="True" />
<TextBlock Grid.Row="4" Text="Date" VerticalAlignment="Center" Margin="0,0,12,8" />
<DatePicker Grid.Row="4" Grid.Column="1" DayFormat="ddd dd" SelectedDate="{Binding EventDateSelection, Mode=TwoWay}" Margin="0,0,0,8" />
<TextBlock Text="Date" FontWeight="SemiBold" />
<DatePicker DayFormat="ddd dd"
SelectedDate="{Binding EventDateSelection, Mode=TwoWay}" />
<TextBlock Grid.Row="5"
Text="Motif"
VerticalAlignment="Center"
Margin="0,0,12,8" />
<TextBox Grid.Row="5"
Grid.Column="1"
Text="{Binding Reason, Mode=TwoWay}"
Margin="0,0,0,8" />
<TextBlock Text="Motif" FontWeight="SemiBold" />
<TextBox Text="{Binding Reason, Mode=TwoWay}" />
<TextBlock Grid.Row="6" Text="Adresse" VerticalAlignment="Center" Margin="0,0,12,8" />
<TextBox Grid.Row="6" Grid.Column="1" Text="{Binding Address, Mode=TwoWay}" Margin="0,0,0,8" />
<TextBlock Text="Adresse" FontWeight="SemiBold" />
<TextBox Text="{Binding PhysicalAddress.Address}" IsReadOnly="True" />
<Button Content="Modifier l'adresse sur la carte"
HorizontalAlignment="Stretch"
Click="OnEditAddressClicked" />
<Grid Grid.Row="7"
x:Name="SuggestedAddressPanel"
Grid.ColumnSpan="2"
ColumnDefinitions="*,12,Auto,12,Auto"
Margin="0,0,0,8"
IsVisible="{Binding HasSuggestedAddressPanel}">
<TextBlock Grid.Column="0"
VerticalAlignment="Center"
Text="{Binding SuggestedAddress, StringFormat='Adresse suggérée: {0}'}"
TextWrapping="Wrap"
Opacity="0.8" />
<Button Grid.Column="2"
x:Name="ApplySuggestedAddressButton"
Content="Utiliser"
IsVisible="{Binding HasSuggestedAddress}"
Command="{Binding ApplySuggestedAddressCommand}" />
<ProgressBar Grid.Column="4"
x:Name="SuggestedAddressProgress"
Width="80"
IsIndeterminate="True"
IsVisible="{Binding IsResolvingAddress}" />
</Grid>
<Grid Grid.Row="8"
Grid.ColumnSpan="2"
ColumnDefinitions="Auto,12,Auto"
Margin="0,0,0,8">
<Button Grid.Column="0"
HorizontalAlignment="Left"
Content="Utiliser ma position"
Command="{Binding UseCurrentLocationCommand}" />
<Button Grid.Column="2"
HorizontalAlignment="Left"
Content="Me localiser sur la carte"
Click="OnCenterCurrentLocationClicked"
IsEnabled="{Binding CanUseCurrentLocation}" />
</Grid>
<TextBlock Grid.Row="9" Text="Latitude" VerticalAlignment="Center" Margin="0,0,12,8" />
<TextBox Grid.Row="9" Grid.Column="1" Text="{Binding Latitude, Mode=TwoWay}" PlaceholderText="Optionnel" Margin="0,0,0,8" />
<TextBlock Grid.Row="10" Text="Longitude" VerticalAlignment="Center" Margin="0,0,12,8" />
<TextBox Grid.Row="10" Grid.Column="1" Text="{Binding Longitude, Mode=TwoWay}" PlaceholderText="Optionnel" Margin="0,0,0,8" />
<TextBlock Grid.Row="11" Grid.ColumnSpan="2"
Text="Carte: cliquez pour positionner le rendez-vous"
Margin="0,0,0,8"
Opacity="0.85" />
<mapsui:MapControl Grid.Row="12"
Grid.ColumnSpan="2"
x:Name="LocationMap"
Height="260"
Margin="0,0,0,8" />
<TextBlock Grid.Row="13"
Text="Informations"
VerticalAlignment="Center"
Margin="0,0,12,8" />
<TextBox Grid.Row="13"
Grid.Column="1"
Text="{Binding AdditionalInfo, Mode=TwoWay}"
Margin="0,0,0,8" />
<CheckBox Grid.Row="14" Grid.ColumnSpan="2"
Content="Je consens à la création de cette commande"
IsChecked="{Binding Consent, Mode=TwoWay}"
Margin="0,4,0,12" />
<Grid Grid.Row="15" Grid.ColumnSpan="2" ColumnDefinitions="Auto,12,*,Auto">
<Button Grid.Column="0"
Content="{Binding SubmitLabel}"
Command="{Binding SubmitCommand}"
IsEnabled="{Binding IsSupported}" />
<postitControls:StatusBar Grid.Column="2"
DataContext="{Binding ActionStatus}" />
<ProgressBar Grid.Column="3"
Width="120"
<StackPanel Spacing="8" IsVisible="{Binding HasSuggestedAddressPanel}">
<TextBlock Text="{Binding SuggestedAddress, StringFormat='Adresse suggérée: {0}'}"
TextWrapping="Wrap"
Opacity="0.8" />
<Button Content="Utiliser"
HorizontalAlignment="Stretch"
IsVisible="{Binding HasSuggestedAddress}"
Command="{Binding ApplySuggestedAddressCommand}" />
<ProgressBar Height="4"
IsIndeterminate="True"
IsVisible="{Binding IsBusy}" />
</Grid>
</Grid>
IsVisible="{Binding IsResolvingAddress}" />
</StackPanel>
<Button Content="Utiliser ma position"
HorizontalAlignment="Stretch"
Command="{Binding UseCurrentLocationCommand}" />
<TextBlock Text="Latitude" FontWeight="SemiBold" />
<TextBox Text="{Binding Latitude}" IsReadOnly="True" PlaceholderText="Optionnel" />
<TextBlock Text="Longitude" FontWeight="SemiBold" />
<TextBox Text="{Binding Longitude}" IsReadOnly="True" PlaceholderText="Optionnel" />
<TextBlock Text="Informations" FontWeight="SemiBold" />
<TextBox Text="{Binding AdditionalInfo, Mode=TwoWay}" />
<CheckBox IsChecked="{Binding Consent, Mode=TwoWay}"
Margin="0,4,0,0">
<TextBlock Text="Je consens à la création de cette commande"
TextWrapping="Wrap" />
</CheckBox>
<Button Content="{Binding SubmitLabel}"
HorizontalAlignment="Stretch"
Command="{Binding SubmitCommand}"
IsEnabled="{Binding IsSupported}" />
<ProgressBar Height="4"
IsIndeterminate="True"
IsVisible="{Binding IsBusy}" />
</StackPanel>
</ScrollViewer>
</ContentPage>

View file

@ -1,62 +1,16 @@
using System;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using Mapsui;
using Mapsui.Layers;
using Mapsui.Projections;
using Mapsui.Styles;
using Mapsui.Tiling;
using Mapsui.UI.Avalonia;
using PostIt.Services;
using PostIt.ViewModels.Commands;
namespace PostIt.Views.Commands;
using Mapsui.Tiling; // Ensure you have this namespace
public partial class RdvPage : ContentPage
{
private const double DefaultLatitude = 48.8566;
private const double DefaultLongitude = 2.3522;
private const int DefaultZoomLevel = 4;
private const int SelectedZoomLevel = 13;
internal const double ReverseGeocodingCacheToleranceDegrees = 0.0001;
private static readonly TimeSpan ReverseGeocodingDebounce = TimeSpan.FromMilliseconds(350);
private MapControl? _locationMap;
private MemoryLayer? _selectionLayer;
private RdvViewModel? _currentViewModel;
private readonly IReverseGeocodingService _reverseGeocodingService;
private CancellationTokenSource? _reverseGeocodeCts;
private double? _lastResolvedLatitude;
private double? _lastResolvedLongitude;
private string? _lastResolvedAddress;
public RdvPage()
: this(null)
{
}
public RdvPage(IReverseGeocodingService? reverseGeocodingService)
{
_reverseGeocodingService = reverseGeocodingService ?? new NominatimReverseGeocodingService();
InitializeComponent();
InitializeMap();
// ... inside your Map setup logic ...
string version = GetType().Assembly.GetName().Version?.ToString() ?? "1.1";
// 1. Create a unique user-agent string for your app (e.g., "AppName/Version (ContactEmail)")
string myCustomUserAgent = $"PostIt/{version} (paul@pschneider.fr)";
// 2. Pass your custom user agent into the OpenStreetMap helper
var osmLayer = OpenStreetMap.CreateTileLayer(myCustomUserAgent);
// 3. add your newly identified layer
_locationMap.Map.Layers.Add(osmLayer);
}
private void InitializeComponent()
@ -64,186 +18,12 @@ public partial class RdvPage : ContentPage
AvaloniaXamlLoader.Load(this);
}
private void InitializeMap()
{
_locationMap = this.FindControl<MapControl>("LocationMap");
if (_locationMap is null)
return;
var map = new Map();
map.Layers.Add(OpenStreetMap.CreateTileLayer());
_selectionLayer = CreateSelectionLayer();
map.Layers.Add(_selectionLayer);
_locationMap.Map = map;
_locationMap.MapTapped += OnMapTapped;
DataContextChanged += OnDataContextChanged;
AttachViewModel(DataContext as RdvViewModel);
}
private void OnDataContextChanged(object? sender, System.EventArgs e)
{
AttachViewModel(DataContext as RdvViewModel);
CenterFromViewModel();
}
private async void OnMapTapped(object? sender, MapEventArgs e)
private async void OnEditAddressClicked(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
if (DataContext is not RdvViewModel vm)
return;
var (longitude, latitude) = SphericalMercator.ToLonLat(e.WorldPosition.X, e.WorldPosition.Y);
vm.ApplyLocationFromMap(latitude, longitude);
UpdateMarkerFromViewModel();
CenterMap(latitude, longitude, zoomLevel: SelectedZoomLevel);
await TryResolveAddressAsync(vm, latitude, longitude);
}
private async void OnCenterCurrentLocationClicked(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
if (DataContext is not RdvViewModel vm || !vm.CanUseCurrentLocation)
return;
await vm.UseCurrentLocationCommand.ExecuteAsync(null);
UpdateMarkerFromViewModel();
CenterFromViewModel();
if (vm.Latitude.HasValue && vm.Longitude.HasValue)
await TryResolveAddressAsync(vm, vm.Latitude.Value, vm.Longitude.Value);
}
private void AttachViewModel(RdvViewModel? vm)
{
if (_currentViewModel is not null)
_currentViewModel.PropertyChanged -= OnViewModelPropertyChanged;
_currentViewModel = vm;
if (_currentViewModel is not null)
_currentViewModel.PropertyChanged += OnViewModelPropertyChanged;
UpdateMarkerFromViewModel();
}
private void OnViewModelPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(RdvViewModel.Latitude)
|| e.PropertyName == nameof(RdvViewModel.Longitude))
{
UpdateMarkerFromViewModel();
}
}
private void CenterFromViewModel()
{
if (DataContext is not RdvViewModel vm)
{
CenterMap(DefaultLatitude, DefaultLongitude, zoomLevel: DefaultZoomLevel);
return;
}
if (vm.Latitude.HasValue && vm.Longitude.HasValue)
{
CenterMap(vm.Latitude.Value, vm.Longitude.Value, zoomLevel: SelectedZoomLevel);
return;
}
CenterMap(DefaultLatitude, DefaultLongitude, zoomLevel: DefaultZoomLevel);
}
private void CenterMap(double latitude, double longitude, int zoomLevel)
{
if (_locationMap?.Map is null)
return;
var (x, y) = SphericalMercator.FromLonLat(longitude, latitude);
_locationMap.Map.Navigator.CenterOn(x, y);
_locationMap.Map.Navigator.ZoomToLevel(zoomLevel);
}
private void UpdateMarkerFromViewModel()
{
if (_selectionLayer is null)
return;
if (DataContext is not RdvViewModel vm
|| !vm.Latitude.HasValue
|| !vm.Longitude.HasValue)
{
_selectionLayer.Features = Enumerable.Empty<IFeature>();
_locationMap?.RefreshData(ChangeType.Discrete);
return;
}
var (x, y) = SphericalMercator.FromLonLat(vm.Longitude.Value, vm.Latitude.Value);
_selectionLayer.Features = new IFeature[] { new PointFeature(x, y) };
_locationMap?.RefreshData(ChangeType.Discrete);
}
private static MemoryLayer CreateSelectionLayer()
{
return new MemoryLayer("selected-location")
{
Style = new SymbolStyle
{
SymbolType = SymbolType.Ellipse,
Fill = new Brush(Color.Crimson),
Outline = new Pen(Color.White, 2),
SymbolScale = 0.9,
},
Features = Enumerable.Empty<IFeature>(),
};
}
private async Task TryResolveAddressAsync(RdvViewModel vm, double latitude, double longitude)
{
if (_lastResolvedLatitude.HasValue
&& _lastResolvedLongitude.HasValue
&& AreCoordinatesClose(_lastResolvedLatitude.Value, _lastResolvedLongitude.Value, latitude, longitude)
&& !string.IsNullOrWhiteSpace(_lastResolvedAddress))
{
vm.ApplyResolvedAddress(_lastResolvedAddress);
return;
}
_reverseGeocodeCts?.Cancel();
_reverseGeocodeCts?.Dispose();
_reverseGeocodeCts = new CancellationTokenSource();
var cancellationToken = _reverseGeocodeCts.Token;
try
{
vm.NotifyReverseGeocodingStarted();
await Task.Delay(ReverseGeocodingDebounce, cancellationToken).ConfigureAwait(true);
var resolved = await _reverseGeocodingService
.TryResolveAddressAsync(latitude, longitude, cancellationToken)
.ConfigureAwait(true);
if (!string.IsNullOrWhiteSpace(resolved))
{
_lastResolvedLatitude = latitude;
_lastResolvedLongitude = longitude;
_lastResolvedAddress = resolved;
vm.ApplyResolvedAddress(resolved);
return;
}
vm.NotifyReverseGeocodingUnavailable();
}
catch (OperationCanceledException)
{
vm.IsResolvingAddress = false;
}
}
internal static bool AreCoordinatesClose(
double latitudeA,
double longitudeA,
double latitudeB,
double longitudeB)
{
return Math.Abs(latitudeA - latitudeB) <= ReverseGeocodingCacheToleranceDegrees
&& Math.Abs(longitudeA - longitudeB) <= ReverseGeocodingCacheToleranceDegrees;
if (Application.Current is App app)
await app.PushPageAsync(vm.PhysicalAddress);
}
}

View file

@ -14,6 +14,68 @@
<Grid>
<NavigationPage x:Name="NavRoot"/>
<Border x:Name="NotificationToast"
IsVisible="False"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Margin="16"
CornerRadius="10"
Padding="12"
BorderThickness="1"
BorderBrush="#5B8DEF"
Background="#E8F0FE"
BoxShadow="0 6 16 0 #26000000"
PointerPressed="NotificationToast_PointerPressed">
<Grid ColumnDefinitions="Auto,*" ColumnSpacing="10">
<TextBlock x:Name="NotificationToastGlyph"
VerticalAlignment="Center"
FontSize="18"
FontWeight="Bold"
Foreground="#1E3A8A"
Text="✓"/>
<TextBlock x:Name="NotificationToastMessage"
Grid.Column="1"
MaxWidth="420"
TextWrapping="Wrap"
VerticalAlignment="Center"
Foreground="#1E3A8A"
Text=""/>
</Grid>
</Border>
<Border x:Name="NotificationModal"
IsVisible="False"
Background="#80000000"
Padding="12"
KeyboardNavigation.TabNavigation="Cycle">
<Border MaxWidth="420"
HorizontalAlignment="Stretch"
VerticalAlignment="Center"
Padding="20"
CornerRadius="8"
Background="{DynamicResource SystemControlBackgroundAltHighBrush}">
<StackPanel Spacing="12">
<TextBlock x:Name="NotificationModalTitle"
FontSize="22"
FontWeight="SemiBold"
TextWrapping="Wrap"
Text="Notification"/>
<TextBlock x:Name="NotificationModalMessage"
TextWrapping="Wrap"
Text=""/>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8">
<Button x:Name="NotificationModalCloseButton"
Content="Fermer"
Click="NotificationModalCloseButton_Click"/>
<Button x:Name="NotificationModalActionButton"
IsVisible="False"
Click="NotificationModalActionButton_Click"/>
</StackPanel>
</StackPanel>
</Border>
</Border>
<Border x:Name="AuthenticationModal"
IsVisible="{Binding SessionStatus.IsAuthenticationRequired, FallbackValue=False}"
Background="#80000000"

View file

@ -1,9 +1,15 @@
using System;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Platform;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using Microsoft.Extensions.DependencyInjection;
using PostIt.Models;
using PostIt.Services;
namespace PostIt.Views;
@ -14,11 +20,15 @@ public partial class MainView : UserControl
private Thickness _safeArea;
private Rect? _keyboardRect;
private IInputElement? _previousFocus;
private bool _toastIsVisible;
private readonly NotificationService _notificationService = NotificationService.Instance;
internal bool IsSoftKeyboardOpen { get; private set; }
public MainView()
{
InitializeComponent();
_notificationService.NotificationRequested += OnNotificationRequested;
AuthenticationModal.PropertyChanged += (_, e) =>
{
if (e.Property != IsVisibleProperty) return;
@ -40,46 +50,74 @@ public partial class MainView : UserControl
}, DispatcherPriority.Input);
}
};
LoginButton.PropertyChanged += (_, e) =>
{
if (e.Property == IsEnabledProperty && LoginButton.IsEnabled && AuthenticationModal.IsVisible)
Dispatcher.UIThread.Post(FocusAuthentication, DispatcherPriority.Input);
};
Loaded += (_, _) =>
{
Dispatcher.UIThread.Post(FocusAuthentication, DispatcherPriority.Input);
};
Loaded += (_, _) => Dispatcher.UIThread.Post(FocusAuthentication, DispatcherPriority.Input);
NotificationModalCloseButton.Click += (_, _) => HideNotificationModal();
NotificationModalActionButton.Click += (_, _) => HideNotificationModal(executeAction: true);
NavRoot.IsEnabled = !AuthenticationModal.IsVisible;
TopLevel.SetAutoSafeAreaPadding(this, false);
AttachedToVisualTree += (_, _) =>
{
var topLevel = TopLevel.GetTopLevel(this);
_inputPane = topLevel?.InputPane;
_insetsManager = topLevel?.InsetsManager;
if (_insetsManager is not null)
{
_insetsManager.SafeAreaChanged += SafeAreaChanged;
_safeArea = _insetsManager.SafeAreaPadding;
}
if (_inputPane is not null)
{
_inputPane.StateChanged += InputPaneStateChanged;
ApplyKeyboardOcclusion(_inputPane.State == InputPaneState.Open ? _inputPane.OccludedRect : null);
}
ApplyKeyboardOcclusion(_keyboardRect);
};
DetachedFromVisualTree += (_, _) =>
{
if (_inputPane is not null)
_inputPane.StateChanged -= InputPaneStateChanged;
_inputPane = null;
if (_insetsManager is not null)
_insetsManager.SafeAreaChanged -= SafeAreaChanged;
_insetsManager = null;
};
SizeChanged += (_, _) => ApplyKeyboardOcclusion(_keyboardRect);
}
private void OnNotificationRequested(object? sender, NotificationRequest request)
{
if (string.IsNullOrWhiteSpace(request.Message))
{
HideToast();
HideNotificationModal();
return;
}
if (request.Severity is StatusSeverity.Warning or StatusSeverity.Error)
{
ShowNotificationModal(request.Message, request.Severity, request.ActionLabel, request.Action);
return;
}
ShowToast(request.Message, request.Severity, request.ActionLabel, request.Action);
}
private void FocusAuthentication()
{
if (AuthenticationModal.IsVisible)
@ -104,10 +142,10 @@ public partial class MainView : UserControl
IsSoftKeyboardOpen = keyboardRect is { Height: > 0 };
var topLevel = TopLevel.GetTopLevel(this);
var bottom = topLevel is null ? null : this.TranslatePoint(new Point(0, Bounds.Height), topLevel);
// Subtract only actual overlap: AdjustResize may already have removed the keyboard area.
var overlap = keyboardRect is { Height: > 0 } rect && bottom is { } point
? Math.Clamp(point.Y - rect.Top, 0, Bounds.Height)
: 0;
Padding = new Thickness(_safeArea.Left, _safeArea.Top, _safeArea.Right,
Math.Max(_safeArea.Bottom, overlap));
}
@ -115,12 +153,132 @@ public partial class MainView : UserControl
protected override void OnDataContextChanged(EventArgs e)
{
base.OnDataContextChanged(e);
if (DataContext is ViewModels.BlogsViewModel vm)
if (DataContext is ViewModels.BlogsViewModel vm && !vm.IsLoaded)
vm.RefreshAsync().Wait();
}
private void NotificationToast_PointerPressed(object? sender, PointerPressedEventArgs e)
=> HideToast();
private void NotificationModalCloseButton_Click(object? sender, RoutedEventArgs e)
=> HideNotificationModal();
private void NotificationModalActionButton_Click(object? sender, RoutedEventArgs e)
=> HideNotificationModal(executeAction: true);
internal void ShowToast(string message, StatusSeverity severity = StatusSeverity.Info, string? actionLabel = null, Action? action = null)
{
var glyph = severity switch
{
if (!vm.IsLoaded)
{
vm.RefreshAsync().Wait();
}
StatusSeverity.Error => "!",
StatusSeverity.Warning => "~",
_ => "✓"
};
var background = severity switch
{
StatusSeverity.Error => Color.Parse("#7F1D1D"),
StatusSeverity.Warning => Color.Parse("#7C4A03"),
_ => Color.Parse("#E8F0FE")
};
var borderBrush = severity switch
{
StatusSeverity.Error => Color.Parse("#C62828"),
StatusSeverity.Warning => Color.Parse("#E6A700"),
_ => Color.Parse("#5B8DEF")
};
var foreground = severity switch
{
StatusSeverity.Error => Color.Parse("#E1F0F6"),
StatusSeverity.Warning => Color.Parse("#EAEAEA"),
_ => Color.Parse("#1E3A8A")
};
NotificationToastGlyph.Text = glyph;
NotificationToastGlyph.Foreground = new SolidColorBrush(foreground);
NotificationToastMessage.Text = message;
NotificationToastMessage.Foreground = new SolidColorBrush(foreground);
NotificationToast.Background = new SolidColorBrush(background);
NotificationToast.BorderBrush = new SolidColorBrush(borderBrush);
NotificationToast.IsVisible = true;
_toastIsVisible = true;
if (action is not null && !string.IsNullOrWhiteSpace(actionLabel))
{
NotificationModalActionButton.Content = actionLabel;
NotificationModalActionButton.IsVisible = true;
NotificationModalActionButton.Tag = action;
}
else
{
NotificationModalActionButton.Content = string.Empty;
NotificationModalActionButton.IsVisible = false;
NotificationModalActionButton.Tag = null;
}
if (severity is StatusSeverity.Warning or StatusSeverity.Error)
{
ShowNotificationModal(message, severity, actionLabel, action);
return;
}
Dispatcher.UIThread.Post(async () =>
{
await Task.Delay(2800);
if (_toastIsVisible)
HideToast();
});
}
internal void HideToast()
{
_toastIsVisible = false;
NotificationToast.IsVisible = false;
}
internal void ShowNotificationModal(string message, StatusSeverity severity, string? actionLabel = null, Action? action = null)
{
var title = severity switch
{
StatusSeverity.Error => "Erreur",
StatusSeverity.Warning => "Attention",
_ => "Information"
};
NotificationModalTitle.Text = title;
NotificationModalMessage.Text = message;
if (action is not null && !string.IsNullOrWhiteSpace(actionLabel))
{
NotificationModalActionButton.Content = actionLabel;
NotificationModalActionButton.IsVisible = true;
NotificationModalActionButton.Tag = action;
}
else
{
NotificationModalActionButton.Content = string.Empty;
NotificationModalActionButton.IsVisible = false;
NotificationModalActionButton.Tag = null;
}
NotificationModal.IsVisible = true;
HideToast();
}
internal void HideNotificationModal(bool executeAction = false)
{
NotificationModal.IsVisible = false;
if (executeAction && NotificationModalActionButton.Tag is Action action)
{
NotificationModalActionButton.Tag = null;
action();
}
else
{
NotificationModalActionButton.Tag = null;
}
}
}

View file

@ -7,6 +7,7 @@
xmlns:vm="using:PostIt.ViewModels"
x:DataType="vm:Settings"
>
<ScrollViewer HorizontalScrollBarVisibility="Disabled">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
@ -55,12 +56,14 @@
<TextBlock Text="SignalR uniquement, sans notification permanente. Les alertes s'affichent seulement a reception d'un message ou evenement. Sauver avec cette option active demande l'exemption batterie Android seulement si PostIt n'est pas deja exempte. Vous restez libre de refuser. Autorisez aussi les donnees en arriere-plan dans Android. Ces reglages ne garantissent pas la survie du service ni sa reprise au demarrage. Sans cette option, la connexion dure pendant la vie du processus PostIt."
TextWrapping="Wrap" />
</StackPanel>
<CheckBox Content="Partager les exceptions techniques avec Yavsc"
IsChecked="{Binding ShareExceptionReports, Mode=TwoWay}" />
<TextBlock Text="Desactive par defaut. Si vous activez cette option, PostIt transmet le type, le message et la trace technique des exceptions signalees pour aider au diagnostic. Ces details peuvent contenir des informations issues de l'environnement de l'application."
TextWrapping="Wrap" />
<TextBlock Text="Avatar: PNG, JPG/JPEG, WEBP, GIF. Taille max 2 MB."
Opacity="0.8"
TextWrapping="Wrap" />
<postitControls:StatusBar DataContext="{Binding ActionStatus}"/>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Button x:Name="ChooseAvatarButton"
Content="Choisir l'avatar"
@ -74,4 +77,5 @@
</StackPanel>
</Grid>
</ScrollViewer>
</ContentPage>

View file

@ -79,8 +79,7 @@
</ScrollViewer>
<Grid Grid.Row="3" ColumnDefinitions="Auto,8,*,Auto" Margin="0,12,0,0">
<postitControls:StatusBar Grid.Column="0"
DataContext="{Binding ActionStatus}" />
<ProgressBar Grid.Column="3"
Width="120"
IsIndeterminate="True"

View file

@ -46,10 +46,7 @@
<Button Content="Capturer" Command="{Binding CaptureAsync}" />
</StackPanel>
<postitControls:StatusBar Grid.Row="3"
DataContext="{Binding ActionStatus}" />
<TextBlock Grid.Row="4"
<TextBlock Grid.Row="3"
FontSize="11"
Foreground="DarkSlateGray"
TextWrapping="Wrap">

View file

@ -37,6 +37,7 @@
"PodcastBlurBackground": false,
"LanCallAddress": null,
"AndroidKeepChatConnected": false,
"ShareExceptionReports": true,
"ChatRoomsByAccount": {
"1E801AB5E07C3365EDFE78054C60FB3A13A84182A65DDCC7F85DBE3F8B5D142D": [
"General"

View file

@ -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);

View file

@ -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; }
}
}

View file

@ -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)

View file

@ -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));

View file

@ -1,4 +1,3 @@
using Newtonsoft.Json;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Yavsc.Models;
@ -7,6 +6,7 @@ using Microsoft.EntityFrameworkCore;
namespace Yavsc.ApiControllers
{
[Authorize]
[Produces("application/json")]
[Route("~/api/bug")]
public class BugApiController : Controller
@ -22,22 +22,26 @@ namespace Yavsc.ApiControllers
[HttpPost("signal")]
[Authorize]
public IActionResult Signal([FromBody] BugReport report)
public async Task<IActionResult> 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 +52,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);
}

View file

@ -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);

View file

@ -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);

View file

@ -5,17 +5,9 @@
@if (Context.User?.Identity?.IsAuthenticated ?? false)
{
string userName = User.GetUserName();
var plateformeControllers = new[] { "Bug", "HyperLink", "Feature" };
var administrationControllers = new[] { "Administration", "Announces", "Activity", "CommandForms", "Notifications", "SIRENExceptions", "Client", "MailingTemplate" };
var administrationControllers = new[] { "Administration", "Announces", "Activity", "CommandForms", "Notifications", "SIRENExceptions", "Client", "MailingTemplate", "Bug", "HyperLink" };
var accountMenuControllers = new[] { "Manage", "Grants", "Device", "Diagnostics", "Account" };
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle @PageHelpers.ActivePageAny(ViewContext, plateformeControllers)" href="#" id="dropdown04" data-bs-toggle="dropdown" aria-expanded="false">Plateforme</a>
<ul class="dropdown-menu" aria-labelledby="dropdown04">
<li><a class="dropdown-item @PageHelpers.ActivePage(ViewContext, "Bug")" asp-controller="Bug" asp-action="Index">Bugs</a></li>
<li><a class="dropdown-item @PageHelpers.ActivePage(ViewContext, "Feature")" asp-controller="Feature" asp-action="Index">Features</a></li>
</ul>
</li>
@if (User.IsInMsRole(Constants.AdminName)) {
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle @PageHelpers.ActivePageAny(ViewContext, administrationControllers)" href="#" id="dropdown05" data-bs-toggle="dropdown" aria-expanded="false">
@ -30,7 +22,8 @@
<li><a class="dropdown-item @PageHelpers.ActivePage(ViewContext, "SIRENExceptions")" asp-controller="SIRENExceptions" asp-action="Index">Excéptions au numéro de SIREN</a></li>
<li><a class="dropdown-item @PageHelpers.ActivePage(ViewContext, "Client")" asp-controller="Client" asp-action="Index">Accès API</a></li>
<li><a class="dropdown-item @PageHelpers.ActivePage(ViewContext, "MailingTemplate")" asp-controller="MailingTemplate" asp-action="Index">Emailing</a></li>
</ul>
<li><a class="dropdown-item @PageHelpers.ActivePage(ViewContext, "Bug")" asp-controller="Bug" asp-action="Index">Bugs</a></li>
</ul>
</li>}
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle @PageHelpers.ActivePageAny(ViewContext, accountMenuControllers)" href="#" id="dropdown04" data-bs-toggle="dropdown" aria-expanded="false">Hello @userName!</a>