Refactor rendez-vous address editing

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Paul Schneider 2026-11-14 23:28:19 +00:00
commit c4d599cda1
Signed by: notazof
GPG key ID: AD4B9B545FBD7D12
11 changed files with 580 additions and 501 deletions

View file

@ -8,6 +8,8 @@
* [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

View file

@ -1,29 +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">
<WrapPanel Orientation="Horizontal" >
<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}"
/>
</WrapPanel>
</Border>
</UserControl>

View file

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

View file

@ -88,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

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

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

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

@ -2,122 +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 HorizontalScrollBarVisibility="Disabled">
<StackPanel Margin="16" Spacing="10" MaxWidth="760">
<TextBlock Text="{Binding Title}"
FontSize="22"
FontWeight="Bold"
TextWrapping="Wrap" />
<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" />
<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}" />
<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);
}
}