Merge pull request 'postit: persist settings save and apply ApiUrl changes without restart' (#51) from feat/estimate into main

Reviewed-on: #51
This commit is contained in:
Paul Schneider 2026-09-06 21:05:57 +01:00
commit ff9c6c7209
141 changed files with 2228 additions and 349 deletions

View file

@ -1,5 +1,58 @@
# Changelog # Changelog
## [1.0.8-rc14] - unstable
### Added
* [PostIt] Ajout d'un `BillingQueryDetailsPageViewModel` et de sa page associee pour afficher le detail d'une commande billing depuis l'historique.
* [PostIt] Ajout d'un mode detail avec section metier (statut, date, description, motif, infos) et section technique repliable (code, client, provision, lieu, prestations).
* [PostIt] Ajout d'un badge de statut enrichi (couleur + pictogramme) sur le detail d'une commande pour visualiser l'etat en un coup d'oeil.
* [PostIt] Ajout d'un bloc d'actions rapide en tete du detail (`Retour`, `Ouvrir en edition`) pour eviter le scroll jusqu'au bas de page.
* [PostIt] Ajout d'un style monospace sur les metadonnees techniques (code billing, client, provision, lieu, prestations) pour faciliter la lecture des identifiants et valeurs brutes.
### Changed
* [PostIt] Le bouton d'ouverture depuis la liste billing ouvre maintenant une page de detail dediee avant l'eventuelle edition.
* [PostIt] Amelioration UX des pages billing: badges de statut colores, actions remontees en haut de page, et typographie monospace sur les metadonnees techniques.
### Fixed
* [Yavsc.Api] Correction d'un 500 sur le refresh du catalogue d'activites lorsque `Activity.Description` est `NULL` en base (nullabilite explicite + projection null-safe + gardes sur codes vides).
* [Yavsc.Api] Correction des erreurs 400/500 sur les routes billing (`Rdv`, `Brush`, `MBrush`) en imposant `ClientId` depuis l'utilisateur authentifie et en ignorant les champs server-owned lors de la validation modele.
* [Yavsc.Api] Correction du `PUT /api/v1/billing/Rdv/{id}`: mise a jour controlee de l'entite existante (et non remplacement brut du graphe JSON), ce qui supprime les `BadRequest` parasites.
* [Yavsc.Api] Correction PostgreSQL `timestamptz` sur RDV: normalisation UTC de `EventDate` sur `POST/PUT /api/v1/billing/Rdv` pour eviter l'erreur `Cannot write DateTime with Kind=Local`.
* [Yavsc.Api] Correction du flux FrontOffice accept/reject de query: sauvegarde avec contexte utilisateur et fallback d'injection pour `IBillingService` afin d'eviter les erreurs serveur en environnement de test.
* [Yavsc.Blogs] Correction des `BadRequest` sur `POST/PUT /api/v1/blogspot` avec payload JSON (PostIt): les proprietes de navigation/serveur (`Author`, `Tags`, `Comments`, audit) ne bloquent plus la validation.
* [Yavsc.Org] Correction du flux MVC de creation de commentaire: `SaveChangesAsync(userId)` est utilise pour renseigner les champs d'audit requis (`UserCreated`/`UserModified`).
* [Yavsc.Api.Test] Stabilisation des fixtures de seed billing: remplissage des metadonnees d'audit (`UserCreated`, `UserModified`, dates) pour eviter les echecs SQLite `NOT NULL`.
## [1.0.8-rc13] - unstable
### Added
* [PostIt] Integration d'un selecteur de lieu RDV base sur Mapsui (carte interactive dans le formulaire `Rdv`).
* [PostIt] Ajout d'un marqueur de position et d'une action de recentrage sur la carte RDV.
* [PostIt] Ajout d'un service de reverse geocoding pour suggerer une adresse a partir des coordonnees carte.
* [PostIt] Cache et debounce des resolutions d'adresse RDV pour limiter les appels reseau et lisser l'UX.
* [PostIt.Tests] Nouvelles non-regressions sur le panneau d'adresse suggeree RDV et le comportement de la carte.
* [Yavsc.Abstract] Activation de `#nullable enable annotations` sur les fichiers legacy avec annotations nullable.
* [Yavsc.Server] Activation de `#nullable enable annotations` sur les fichiers legacy avec annotations nullable.
### Changed
* [PostIt] Generalisation de la barre de statut d'action (severite explicite) sur pages principales, dialogues et formulaires billing.
* [PostIt] Harmonisation des messages de statut utilisateur en francais.
* [PostIt] Renforcement des gardes de navigation dans les flux de gestion des membres de cercle.
* [PostIt] Le flux RDV conserve l'adresse saisie manuellement et propose l'adresse resolue comme suggestion explicite.
* [PostIt] Le flux de geolocalisation RDV tolere les positions proches dans le cache de suggestion d'adresse.
### Fixed
* [PostIt.Desktop] Correction d'un crash au demarrage OIDC (`No authority specified`) via durcissement des valeurs par defaut de configuration d'authentification.
* [PostIt] Correction de la persistance des settings: l'etat runtime de statut n'est plus serialize dans le JSON utilisateur.
* [PostIt.Tests] Ajout d'un verrou de non-regression sur le premier chargement des settings.
* [PostIt] Correction du binding de la date RDV: `DatePicker.SelectedDate` est aligne sur un proxy `DateTimeOffset?` (`EventDateSelection`).
## [1.0.8-rc12] - unstable ## [1.0.8-rc12] - unstable
### Added ### Added
@ -13,12 +66,14 @@
* [PostIt] Les avatars ne sont plus relies en string sur `Image.Source`: ils sont telecharges et lies en `Bitmap`. * [PostIt] Les avatars ne sont plus relies en string sur `Image.Source`: ils sont telecharges et lies en `Bitmap`.
* [Yavsc.Api.Client] `ActivityApiClient` accepte une base d'avatar dediee et construit les URLs avatar depuis l'autorite d'identification. * [Yavsc.Api.Client] `ActivityApiClient` accepte une base d'avatar dediee et construit les URLs avatar depuis l'autorite d'identification.
* [PostIt] Les clients Activites/Billing utilisent maintenant `ApiUrl` en lecture dynamique: un changement via Parametres prend effet sans redemarrer l'application (apres sauvegarde et rafraichissement de la page).
* [PostIt] Le header de `MainPage` n'utilise plus `ScrollViewer`; remplacement par une barre de commandes basee sur `WrapPanel`. * [PostIt] Le header de `MainPage` n'utilise plus `ScrollViewer`; remplacement par une barre de commandes basee sur `WrapPanel`.
* [PostIt] Alignement de la navigation blogs: renommage `PushMainPageAsync` -> `PushBlogsPageAsync` et ajustement de `HomePageViewModel`. * [PostIt] Alignement de la navigation blogs: renommage `PushMainPageAsync` -> `PushBlogsPageAsync` et ajustement de `HomePageViewModel`.
### Fixed ### Fixed
néant * [PostIt.Android] Correction d'un 404 sur la page Activites au premier lancement: la configuration embarquee pointait `ApiUrl` vers le host Blogs au lieu de l'API metier.
* [PostIt] Correction du bouton Sauver de la page Parametres: binding vers `SaveCommand` pour persister correctement `ApiUrl`/`BlogsApiUrl`.
## [1.0.8-rc11] - unstable ## [1.0.8-rc11] - unstable

View file

@ -16,6 +16,8 @@
<PackageVersion Include="Avalonia.Headless" Version="$(AvaloniaVersionBase)" /> <PackageVersion Include="Avalonia.Headless" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Headless.Xunit" Version="$(AvaloniaVersionBase)" /> <PackageVersion Include="Avalonia.Headless.Xunit" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Avalonia.Fonts.Inter" Version="$(AvaloniaVersionBase)" /> <PackageVersion Include="Avalonia.Fonts.Inter" Version="$(AvaloniaVersionBase)" />
<PackageVersion Include="Mapsui" Version="5.1.0" />
<PackageVersion Include="Mapsui.Avalonia12" Version="5.1.0" />
<PackageVersion Include="Material.Avalonia" Version="3.19.0" /> <PackageVersion Include="Material.Avalonia" Version="3.19.0" />
<PackageVersion Include="AvaloniaUI.DiagnosticsSupport" Version="2.2.3" /> <PackageVersion Include="AvaloniaUI.DiagnosticsSupport" Version="2.2.3" />

View file

@ -39,6 +39,22 @@ public class ActivitiesPageViewModelTests
Assert.Equal("https://business.example/api/v1/billing/Rdv", api.Paths[3]); Assert.Equal("https://business.example/api/v1/billing/Rdv", api.Paths[3]);
} }
[Fact]
public async Task ActivityApiClient_uses_updated_business_base_without_restart()
{
var api = new StubActivityApi();
var baseUrl = "https://business-a.example/api/v1/";
var client = new ActivityApiClient(api, () => baseUrl);
await client.GetCatalogAsync(ct: TestContext.Current.CancellationToken);
baseUrl = "https://business-b.example/api/v1/";
await client.GetUsersAsync("brush", TestContext.Current.CancellationToken);
Assert.Equal("https://business-a.example/api/v1/activity/catalog", api.Paths[0]);
Assert.Equal("https://business-b.example/api/v1/activity/brush/users", api.Paths[1]);
}
[Fact] [Fact]
public async Task RefreshAsync_loads_first_activity_then_specialization_performers() public async Task RefreshAsync_loads_first_activity_then_specialization_performers()
{ {

View file

@ -115,6 +115,89 @@ public class BillingCommandPageViewModelTests
} }
} }
[Fact]
public void ApplyLocationFromMap_sets_coordinates_and_updates_status()
{
var api = new RecordingApi();
var client = new BillingApiClient(api, "https://business.example/api/v1/");
var vm =
new CommandFormSummary { Id = 12, ActionName = "Rdv", Title = "Rendez-vous" }
.CreateCommandPageViewModel(
new ActivityInfo { Code = "dev", Name = "Développement" },
new ActivityUserDisplayItem { PerformerId = "perf-1", UserName = "Alice" },
client) as RdvViewModel;
vm!.Address = string.Empty;
vm.ApplyLocationFromMap(48.85661234, 2.35224567);
Assert.Equal(48.856612, vm.Latitude);
Assert.Equal(2.352246, vm.Longitude);
Assert.Contains("Position sélectionnée", vm.StatusMessage, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void EventDateSelection_round_trips_with_EventDate_for_DatePicker_binding()
{
var api = new RecordingApi();
var client = new BillingApiClient(api, "https://business.example/api/v1/");
var vm =
new CommandFormSummary { Id = 12, ActionName = "Rdv", Title = "Rendez-vous" }
.CreateCommandPageViewModel(
new ActivityInfo { Code = "dev", Name = "Développement" },
new ActivityUserDisplayItem { PerformerId = "perf-1", UserName = "Alice" },
client) as RdvViewModel;
var selected = new DateTimeOffset(2026, 9, 7, 14, 30, 0, TimeSpan.FromHours(2));
vm!.EventDateSelection = selected;
Assert.Equal(selected.LocalDateTime, vm.EventDate);
Assert.Equal(vm.EventDate, vm.EventDateSelection!.Value.LocalDateTime);
}
[Fact]
public void ApplyResolvedAddress_populates_empty_address_directly()
{
var api = new RecordingApi();
var client = new BillingApiClient(api, "https://business.example/api/v1/");
var vm =
new CommandFormSummary { Id = 12, ActionName = "Rdv", Title = "Rendez-vous" }
.CreateCommandPageViewModel(
new ActivityInfo { Code = "dev", Name = "Développement" },
new ActivityUserDisplayItem { PerformerId = "perf-1", UserName = "Alice" },
client) as RdvViewModel;
vm!.Address = string.Empty;
vm.ApplyResolvedAddress("10 rue de Rivoli, 75001 Paris");
Assert.Equal("10 rue de Rivoli, 75001 Paris", vm.Address);
Assert.False(vm.HasSuggestedAddress);
}
[Fact]
public void ApplyResolvedAddress_preserves_manual_address_and_exposes_suggestion()
{
var api = new RecordingApi();
var client = new BillingApiClient(api, "https://business.example/api/v1/");
var vm =
new CommandFormSummary { Id = 12, ActionName = "Rdv", Title = "Rendez-vous" }
.CreateCommandPageViewModel(
new ActivityInfo { Code = "dev", Name = "Développement" },
new ActivityUserDisplayItem { PerformerId = "perf-1", UserName = "Alice" },
client) as RdvViewModel;
vm!.Address = "Saisie manuelle";
vm.ApplyResolvedAddress("10 rue de Rivoli, 75001 Paris");
Assert.Equal("Saisie manuelle", vm.Address);
Assert.True(vm.HasSuggestedAddress);
Assert.Equal("10 rue de Rivoli, 75001 Paris", vm.SuggestedAddress);
vm.ApplySuggestedAddressCommand.Execute(null);
Assert.Equal("10 rue de Rivoli, 75001 Paris", vm.Address);
Assert.False(vm.HasSuggestedAddress);
}
[Fact] [Fact]
public async Task InitializeAsync_loads_prestations_for_brush_and_submit_posts_selected_prestation() public async Task InitializeAsync_loads_prestations_for_brush_and_submit_posts_selected_prestation()
{ {

View file

@ -0,0 +1,72 @@
using System.Net;
using System.Text;
using PostIt.Services;
namespace PostIt.Tests;
public class NominatimReverseGeocodingServiceTests
{
[Fact]
public async Task TryResolveAddressAsync_formats_compact_street_address_from_nominatim_payload()
{
var handler = new StubHandler("""
{
"display_name": "6, Place de l'Hôtel-de-Ville - Esplanade de la Libération, Paris, 75004, France",
"address": {
"house_number": "6",
"road": "Place de l'Hôtel-de-Ville - Esplanade de la Libération",
"postcode": "75004",
"city": "Paris"
}
}
""");
var service = new NominatimReverseGeocodingService(new HttpClient(handler)
{
BaseAddress = new Uri("https://nominatim.openstreetmap.org/")
});
var result = await service.TryResolveAddressAsync(48.8566, 2.3522);
Assert.Equal("6, Place de l'Hôtel-de-Ville - Esplanade de la Libération, 75004, Paris", result);
Assert.NotNull(handler.LastRequest);
Assert.Contains("reverse?format=jsonv2", handler.LastRequest!.RequestUri!.ToString(), StringComparison.Ordinal);
}
[Fact]
public async Task TryResolveAddressAsync_returns_null_on_unsuccessful_response()
{
var handler = new StubHandler("{}", HttpStatusCode.TooManyRequests);
var service = new NominatimReverseGeocodingService(new HttpClient(handler)
{
BaseAddress = new Uri("https://nominatim.openstreetmap.org/")
});
var result = await service.TryResolveAddressAsync(48.8566, 2.3522);
Assert.Null(result);
}
private sealed class StubHandler : HttpMessageHandler
{
private readonly string _payload;
private readonly HttpStatusCode _statusCode;
public HttpRequestMessage? LastRequest { get; private set; }
public StubHandler(string payload, HttpStatusCode statusCode = HttpStatusCode.OK)
{
_payload = payload;
_statusCode = statusCode;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
LastRequest = request;
return Task.FromResult(new HttpResponseMessage(_statusCode)
{
Content = new StringContent(_payload, Encoding.UTF8, "application/json")
});
}
}
}

View file

@ -0,0 +1,79 @@
using Avalonia.Controls;
using Avalonia.Headless.XUnit;
using PostIt.ViewModels;
using PostIt.ViewModels.Commands;
using PostIt.Views.Commands;
using Yavsc.Abstract.Workflow;
using Yavsc.Api.Client;
namespace PostIt.Tests;
public class RdvPageHeadlessTests
{
[AvaloniaFact]
public void Suggested_address_panel_is_hidden_by_default()
{
var page = CreatePage(out _);
var panel = page.FindControl<Grid>("SuggestedAddressPanel");
var progress = page.FindControl<ProgressBar>("SuggestedAddressProgress");
Assert.NotNull(panel);
Assert.NotNull(progress);
Assert.False(panel!.IsVisible);
Assert.False(progress!.IsVisible);
}
[AvaloniaFact]
public async Task Suggested_address_panel_and_spinner_follow_viewmodel_state()
{
var page = CreatePage(out var vm);
var panel = page.FindControl<Grid>("SuggestedAddressPanel")!;
var progress = page.FindControl<ProgressBar>("SuggestedAddressProgress")!;
var applyButton = page.FindControl<Button>("ApplySuggestedAddressButton")!;
vm.Address = "Saisie manuelle";
vm.NotifyReverseGeocodingStarted();
await Task.Delay(50);
Assert.True(panel.IsVisible);
Assert.True(progress.IsVisible);
Assert.False(applyButton.IsVisible);
vm.ApplyResolvedAddress("10 rue de Rivoli, 75001 Paris");
await Task.Delay(50);
Assert.True(panel.IsVisible);
Assert.False(progress.IsVisible);
Assert.True(applyButton.IsVisible);
}
private static RdvPage CreatePage(out RdvViewModel vm)
{
vm = new RdvViewModel(
new ActivityInfo { Code = "dev", Name = "Développement" },
new ActivityUserDisplayItem { PerformerId = "perf-1", UserName = "Alice" },
new CommandFormSummary { Id = 12, ActionName = "Rdv", Title = "Rendez-vous" },
new BillingApiClient(new RecordingApi(), "https://business.example/api/v1/"));
var page = new RdvPage { DataContext = vm };
var nav = new NavigationPage();
_ = nav.PushAsync(page);
var window = new Window { Content = nav };
window.Show();
return page;
}
private sealed class RecordingApi : IYavscApiClient
{
public HttpClient Http { get; } = new();
public Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
=> Task.FromResult(default(T)!);
public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
=> Task.CompletedTask;
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}

View file

@ -0,0 +1,30 @@
using PostIt.Views.Commands;
namespace PostIt.Tests;
public class RdvPageTests
{
[Fact]
public void AreCoordinatesClose_returns_true_for_nearby_points_within_cache_tolerance()
{
var result = RdvPage.AreCoordinatesClose(
48.8566,
2.3522,
48.85665,
2.35225);
Assert.True(result);
}
[Fact]
public void AreCoordinatesClose_returns_false_for_points_outside_cache_tolerance()
{
var result = RdvPage.AreCoordinatesClose(
48.8566,
2.3522,
48.85685,
2.3522);
Assert.False(result);
}
}

View file

@ -173,4 +173,51 @@ public class SettingsLoadTests
Assert.NotNull(roundTrip); Assert.NotNull(roundTrip);
Assert.Equal("bonjour", roundTrip.SearchText); Assert.Equal("bonjour", roundTrip.SearchText);
} }
/// <summary>
/// First-start regression guard: older settings payloads can
/// still contain <c>ActionStatus</c> from a previous write. This
/// runtime-only UI state must not be persisted anymore and must
/// not break deserialization when present.
/// </summary>
[Fact]
public void ActionStatus_is_not_persisted_and_legacy_payload_with_it_still_deserializes()
{
var settings = new PostIt.ViewModels.Settings
{
Authentication = new AuthenticationSettings
{
Authority = "https://example.test/",
ClientId = "postit-tests",
Scopes = new[] { "openid" }
}
};
var serialized = JsonSerializer.Serialize(settings);
Assert.DoesNotContain("\"ActionStatus\"", serialized, StringComparison.Ordinal);
const string legacyPayload = """
{
"Authentication": {
"Authority": "https://example.test/",
"ClientId": "postit-tests",
"Scopes": ["openid"],
"RedirectUri": "postit://callback"
},
"DarkMode": false,
"BlogsApiUrl": "https://blogs.example.test/api/v1/",
"ApiUrl": "https://api.example.test/api/v1/",
"SearchText": "hello",
"ActionStatus": {
"Message": "runtime only",
"Severity": "Error"
}
}
""";
var roundTrip = JsonSerializer.Deserialize<PostIt.ViewModels.Settings>(legacyPayload);
Assert.NotNull(roundTrip);
Assert.Equal("hello", roundTrip.SearchText);
}
} }

View file

@ -0,0 +1,22 @@
<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"/>
<TextBlock Text="{Binding Message}"
Foreground="{Binding Foreground}"
TextWrapping="Wrap"
VerticalAlignment="Center"/>
</StackPanel>
</Border>
</UserControl>

View file

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

View file

@ -26,10 +26,11 @@ public static class ServiceCollectionHelpers
var userSearchClient = new UserSearchClient(api, settings.BlogsApiUrl); var userSearchClient = new UserSearchClient(api, settings.BlogsApiUrl);
var activityClient = new ActivityApiClient( var activityClient = new ActivityApiClient(
api, api,
settings.ApiUrl, () => settings.ApiUrl,
settings.Authentication?.Authority); () => settings.Authentication?.Authority);
var billingClient = new BillingApiClient(api, settings.ApiUrl); var billingClient = new BillingApiClient(api, () => settings.ApiUrl);
var userDirectory = new UserDirectory(userSearchClient); var userDirectory = new UserDirectory(userSearchClient);
var reverseGeocoding = new NominatimReverseGeocodingService();
// Vues // Vues
services.AddSingleton<MainView>(); services.AddSingleton<MainView>();
@ -56,6 +57,7 @@ public static class ServiceCollectionHelpers
services.AddTransient<RdvPage>(); services.AddTransient<RdvPage>();
services.AddTransient<BrushPage>(); services.AddTransient<BrushPage>();
services.AddTransient<BillingQueriesPage>(); services.AddTransient<BillingQueriesPage>();
services.AddTransient<BillingQueryDetailsPage>();
// ViewModels // ViewModels
services.AddSingleton(settings); services.AddSingleton(settings);
services.AddSingleton<YavscApiClient>(api); services.AddSingleton<YavscApiClient>(api);
@ -65,6 +67,7 @@ public static class ServiceCollectionHelpers
services.AddSingleton(userSearchClient); services.AddSingleton(userSearchClient);
services.AddSingleton(activityClient); services.AddSingleton(activityClient);
services.AddSingleton(billingClient); services.AddSingleton(billingClient);
services.AddSingleton<IReverseGeocodingService>(reverseGeocoding);
services.AddSingleton<IUserDirectory>(userDirectory); services.AddSingleton<IUserDirectory>(userDirectory);
services.AddSingleton<HomePageViewModel>(); services.AddSingleton<HomePageViewModel>();
services.AddSingleton<SignaturePageViewModel>(); services.AddSingleton<SignaturePageViewModel>();

View file

@ -29,6 +29,8 @@
<IncludeAssets Condition="'$(Configuration)' != 'Debug'">None</IncludeAssets> <IncludeAssets Condition="'$(Configuration)' != 'Debug'">None</IncludeAssets>
<PrivateAssets Condition="'$(Configuration)' != 'Debug'">All</PrivateAssets> <PrivateAssets Condition="'$(Configuration)' != 'Debug'">All</PrivateAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Mapsui" />
<PackageReference Include="Mapsui.Avalonia12" />
<PackageReference Include="CommunityToolkit.Mvvm" /> <PackageReference Include="CommunityToolkit.Mvvm" />
<PackageReference Include="IdentityModel.OidcClient" /> <PackageReference Include="IdentityModel.OidcClient" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection" />

View file

@ -0,0 +1,9 @@
using System.Threading;
using System.Threading.Tasks;
namespace PostIt.Services;
public interface IReverseGeocodingService
{
Task<string?> TryResolveAddressAsync(double latitude, double longitude, CancellationToken cancellationToken = default);
}

View file

@ -0,0 +1,119 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace PostIt.Services;
public sealed class NominatimReverseGeocodingService : IReverseGeocodingService
{
private static readonly Uri BaseUri = new("https://nominatim.openstreetmap.org/");
private readonly HttpClient _httpClient;
public NominatimReverseGeocodingService(HttpClient? httpClient = null)
{
_httpClient = httpClient ?? CreateDefaultClient();
}
public async Task<string?> TryResolveAddressAsync(double latitude, double longitude, CancellationToken cancellationToken = default)
{
var requestUri = BuildReverseUri(latitude, longitude);
try
{
using var response = await _httpClient.GetAsync(requestUri, cancellationToken).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
return null;
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
using var json = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false);
return FormatAddress(json.RootElement);
}
catch (OperationCanceledException)
{
throw;
}
catch
{
return null;
}
}
private static HttpClient CreateDefaultClient()
{
var client = new HttpClient
{
BaseAddress = BaseUri,
Timeout = TimeSpan.FromSeconds(10),
};
client.DefaultRequestHeaders.UserAgent.Clear();
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("PostIt", "1.1"));
client.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("fr-FR"));
client.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("fr", 0.9));
return client;
}
private static Uri BuildReverseUri(double latitude, double longitude)
{
var lat = latitude.ToString("0.######", CultureInfo.InvariantCulture);
var lon = longitude.ToString("0.######", CultureInfo.InvariantCulture);
var path = $"reverse?format=jsonv2&addressdetails=1&accept-language=fr&zoom=18&lat={lat}&lon={lon}";
return new Uri(path, UriKind.Relative);
}
private static string? FormatAddress(JsonElement root)
{
if (root.TryGetProperty("address", out var address))
{
var street = JoinNonEmpty(
TryGetString(address, "house_number"),
TryGetString(address, "road"));
var locality = JoinNonEmpty(
TryGetString(address, "postcode"),
TryGetString(address, "city")
?? TryGetString(address, "town")
?? TryGetString(address, "village")
?? TryGetString(address, "municipality"));
var formatted = JoinNonEmpty(street, locality);
if (!string.IsNullOrWhiteSpace(formatted))
return formatted;
}
if (root.TryGetProperty("display_name", out var displayName))
{
var value = displayName.GetString();
if (!string.IsNullOrWhiteSpace(value))
return value;
}
return null;
}
private static string? TryGetString(JsonElement element, string propertyName)
{
return element.TryGetProperty(propertyName, out var property)
? property.GetString()
: null;
}
private static string? JoinNonEmpty(params string?[] values)
{
List<string>? parts = null;
foreach (var value in values)
{
if (string.IsNullOrWhiteSpace(value))
continue;
parts ??= new List<string>();
parts.Add(value.Trim());
}
return parts is null || parts.Count == 0 ? null : string.Join(", ", parts);
}
}

View file

@ -19,7 +19,7 @@ namespace PostIt;
public class ViewLocator : IDataTemplate public class ViewLocator : IDataTemplate
{ {
public Control Build(object? data) public Control Build(object? data)
{ {
try try
{ {
@ -49,10 +49,12 @@ public class ViewLocator : IDataTemplate
AddCircleMemberDialogViewModel => services.GetRequiredService<AddCircleMemberDialog>(), AddCircleMemberDialogViewModel => services.GetRequiredService<AddCircleMemberDialog>(),
CirclesPageViewModel => services.GetRequiredService<CirclesPage>(), CirclesPageViewModel => services.GetRequiredService<CirclesPage>(),
PostAclDialogViewModel => services.GetRequiredService<PostAclDialog>(), PostAclDialogViewModel => services.GetRequiredService<PostAclDialog>(),
BillingQueriesPageViewModel => services.GetRequiredService<BillingQueriesPage>(),
BillingQueryDetailsPageViewModel => services.GetRequiredService<BillingQueryDetailsPage>(),
null => new TextBlock { Text = "No view for <null>" }, null => new TextBlock { Text = "No view for <null>" },
_ => new TextBlock { Text = $"No view for {data.GetType().Name}" } _ => new TextBlock { Text = $"No view for {data.GetType().Name}" }
}; };
} }
public bool Match(object? data) => data is ViewModelBase; public bool Match(object? data) => data is ViewModelBase;
} }

View file

@ -0,0 +1,32 @@
namespace PostIt.ViewModels;
public interface IActionStatusViewModel
{
string StatusMessage { get; set; }
StatusNotice ActionStatus { get; set; }
}
public static class ActionStatusViewModelExtensions
{
public static void SetInfoStatus(this IActionStatusViewModel viewModel, string message)
=> viewModel.SetStatus(message, StatusSeverity.Info);
public static void SetWarningStatus(this IActionStatusViewModel viewModel, string message)
=> viewModel.SetStatus(message, StatusSeverity.Warning);
public static void SetErrorStatus(this IActionStatusViewModel viewModel, string message)
=> viewModel.SetStatus(message, StatusSeverity.Error);
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
{
StatusSeverity.Error => StatusNotice.Error(normalizedMessage),
StatusSeverity.Warning => StatusNotice.Warning(normalizedMessage),
_ => StatusNotice.Info(normalizedMessage),
};
}
}

View file

@ -13,7 +13,7 @@ using Yavsc.Api.Client;
namespace PostIt.ViewModels; namespace PostIt.ViewModels;
public partial class ActivitiesPageViewModel : ViewModelBase public partial class ActivitiesPageViewModel : ViewModelBase, IActionStatusViewModel
{ {
private readonly ActivityApiClient _client; private readonly ActivityApiClient _client;
private readonly BillingApiClient _billingClient; private readonly BillingApiClient _billingClient;
@ -43,6 +43,9 @@ public partial class ActivitiesPageViewModel : ViewModelBase
[ObservableProperty] [ObservableProperty]
public partial string StatusMessage { get; set; } = "Choisissez une activité."; public partial string StatusMessage { get; set; } = "Choisissez une activité.";
[ObservableProperty]
public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Choisissez une activité.");
public ActivityInfo? CurrentActivity => SelectedSpecialization ?? SelectedActivity; public ActivityInfo? CurrentActivity => SelectedSpecialization ?? SelectedActivity;
public string SelectedActivityLabel => SelectedActivity?.Name ?? "(aucune activité)"; public string SelectedActivityLabel => SelectedActivity?.Name ?? "(aucune activité)";
public string CurrentActivityLabel => CurrentActivity?.Name ?? "(aucune)"; public string CurrentActivityLabel => CurrentActivity?.Name ?? "(aucune)";
@ -86,11 +89,11 @@ public partial class ActivitiesPageViewModel : ViewModelBase
} }
catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
{ {
StatusMessage = "Accès refusé pour les activités (scope 'api'). Déconnectez puis reconnectez-vous."; this.SetWarningStatus("Accès refusé pour les activités (scope 'api'). Déconnectez puis reconnectez-vous.");
} }
catch (Exception ex) catch (Exception ex)
{ {
StatusMessage = $"Erreur: {ex.Message}"; this.SetErrorStatus($"Erreur: {ex.Message}");
} }
} }
@ -102,11 +105,11 @@ public partial class ActivitiesPageViewModel : ViewModelBase
} }
catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
{ {
StatusMessage = "Accès refusé pour les activités (scope 'api'). Déconnectez puis reconnectez-vous."; this.SetWarningStatus("Accès refusé pour les activités (scope 'api'). Déconnectez puis reconnectez-vous.");
} }
catch (Exception ex) catch (Exception ex)
{ {
StatusMessage = $"Erreur: {ex.Message}"; this.SetErrorStatus($"Erreur: {ex.Message}");
} }
} }
@ -123,7 +126,7 @@ public partial class ActivitiesPageViewModel : ViewModelBase
await ShowActivityAsync(first); await ShowActivityAsync(first);
if (first is null) if (first is null)
{ {
StatusMessage = "Aucune activité disponible."; this.SetInfoStatus("Aucune activité disponible.");
} }
} }
catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
@ -131,14 +134,14 @@ public partial class ActivitiesPageViewModel : ViewModelBase
Activities = new ObservableCollection<ActivityInfo>(); Activities = new ObservableCollection<ActivityInfo>();
Specializations = new ObservableCollection<ActivityInfo>(); Specializations = new ObservableCollection<ActivityInfo>();
Performers = new ObservableCollection<ActivityUserDisplayItem>(); Performers = new ObservableCollection<ActivityUserDisplayItem>();
StatusMessage = "Accès refusé pour les activités (scope 'api'). Déconnectez puis reconnectez-vous."; this.SetWarningStatus("Accès refusé pour les activités (scope 'api'). Déconnectez puis reconnectez-vous.");
} }
catch (Exception ex) catch (Exception ex)
{ {
Activities = new ObservableCollection<ActivityInfo>(); Activities = new ObservableCollection<ActivityInfo>();
Specializations = new ObservableCollection<ActivityInfo>(); Specializations = new ObservableCollection<ActivityInfo>();
Performers = new ObservableCollection<ActivityUserDisplayItem>(); Performers = new ObservableCollection<ActivityUserDisplayItem>();
StatusMessage = $"Erreur: {ex.Message}"; this.SetErrorStatus($"Erreur: {ex.Message}");
} }
finally finally
{ {
@ -230,19 +233,19 @@ public partial class ActivitiesPageViewModel : ViewModelBase
Performers = new ObservableCollection<ActivityUserDisplayItem>(items); Performers = new ObservableCollection<ActivityUserDisplayItem>(items);
SelectedPerformer = null; SelectedPerformer = null;
StatusMessage = $"{activity.Name} · {Performers.Count} utilisateur(s)"; this.SetInfoStatus($"{activity.Name} · {Performers.Count} utilisateur(s)");
} }
catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
{ {
Performers = new ObservableCollection<ActivityUserDisplayItem>(); Performers = new ObservableCollection<ActivityUserDisplayItem>();
SelectedPerformer = null; SelectedPerformer = null;
StatusMessage = "Accès refusé pour les activités (scope 'api'). Déconnectez puis reconnectez-vous."; this.SetWarningStatus("Accès refusé pour les activités (scope 'api'). Déconnectez puis reconnectez-vous.");
} }
catch (Exception ex) catch (Exception ex)
{ {
Performers = new ObservableCollection<ActivityUserDisplayItem>(); Performers = new ObservableCollection<ActivityUserDisplayItem>();
SelectedPerformer = null; SelectedPerformer = null;
StatusMessage = $"Erreur: {ex.Message}"; this.SetErrorStatus($"Erreur: {ex.Message}");
} }
finally finally
{ {
@ -259,7 +262,7 @@ public partial class ActivitiesPageViewModel : ViewModelBase
{ {
if (SelectedPerformer is null || CurrentActivity is null) if (SelectedPerformer is null || CurrentActivity is null)
{ {
StatusMessage = "Sélectionnez un utilisateur et une activité avec formulaire."; this.SetWarningStatus("Sélectionnez un utilisateur et une activité avec formulaire.");
return; return;
} }

View file

@ -29,7 +29,7 @@ namespace PostIt.ViewModels;
/// <c>CirclesPage</c> then calls /// <c>CirclesPage</c> then calls
/// <see cref="CircleApiClient.AddMemberAsync"/>.</para> /// <see cref="CircleApiClient.AddMemberAsync"/>.</para>
/// </summary> /// </summary>
public partial class AddCircleMemberDialogViewModel : ViewModelBase public partial class AddCircleMemberDialogViewModel : ViewModelBase, IActionStatusViewModel
{ {
private readonly IUserDirectory _directory; private readonly IUserDirectory _directory;
@ -46,7 +46,10 @@ public partial class AddCircleMemberDialogViewModel : ViewModelBase
public partial bool IsBusy { get; set; } public partial bool IsBusy { get; set; }
[ObservableProperty] [ObservableProperty]
public partial string StatusMessage { get; set; } = string.Empty; public partial string StatusMessage { get; set; } = "Pret.";
[ObservableProperty]
public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Pret.");
/// <summary> /// <summary>
/// Raised when the user confirms a selection. The hosting /// Raised when the user confirms a selection. The hosting
@ -79,7 +82,7 @@ public partial class AddCircleMemberDialogViewModel : ViewModelBase
if (string.IsNullOrWhiteSpace(SearchQuery)) if (string.IsNullOrWhiteSpace(SearchQuery))
{ {
Results.Clear(); Results.Clear();
StatusMessage = "Tapez un nom ou un email"; this.SetWarningStatus("Tapez un nom ou un email");
return; return;
} }
@ -88,11 +91,11 @@ public partial class AddCircleMemberDialogViewModel : ViewModelBase
{ {
var hits = await _directory.SearchAsync(SearchQuery, CancellationToken.None).ConfigureAwait(true); var hits = await _directory.SearchAsync(SearchQuery, CancellationToken.None).ConfigureAwait(true);
Results = new ObservableCollection<UserSummary>(hits ?? Array.Empty<UserSummary>()); Results = new ObservableCollection<UserSummary>(hits ?? Array.Empty<UserSummary>());
StatusMessage = $"{Results.Count} résultat(s)"; this.SetInfoStatus($"{Results.Count} résultat(s)");
} }
catch (Exception ex) catch (Exception ex)
{ {
StatusMessage = $"Erreur: {ex.Message}"; this.SetErrorStatus($"Erreur: {ex.Message}");
} }
finally finally
{ {
@ -110,18 +113,20 @@ public partial class AddCircleMemberDialogViewModel : ViewModelBase
{ {
if (Selected is null) if (Selected is null)
{ {
StatusMessage = "Sélectionnez un utilisateur"; this.SetWarningStatus("Sélectionnez un utilisateur");
return; return;
} }
Confirmed?.Invoke(this, Selected); Confirmed?.Invoke(this, Selected);
var app = App.Current as App; var app = App.Current as App
?? throw new InvalidOperationException("Application PostIt indisponible.");
await app.GoBackAsync(); await app.GoBackAsync();
} }
[RelayCommand] [RelayCommand]
public async Task CloseAsync() public async Task CloseAsync()
{ {
var app = App.Current as App; var app = App.Current as App
?? throw new InvalidOperationException("Application PostIt indisponible.");
await app.GoBackAsync(); await app.GoBackAsync();
} }
} }

View file

@ -14,7 +14,7 @@ using Yavsc.Abstract.Workflow;
namespace PostIt.ViewModels; namespace PostIt.ViewModels;
public partial class BillingQueriesPageViewModel : ViewModelBase public partial class BillingQueriesPageViewModel : ViewModelBase, IActionStatusViewModel
{ {
private readonly BillingApiClient _billingClient; private readonly BillingApiClient _billingClient;
@ -36,11 +36,14 @@ public partial class BillingQueriesPageViewModel : ViewModelBase
[ObservableProperty] [ObservableProperty]
public partial string StatusMessage { get; set; } = "Chargement des commandes..."; public partial string StatusMessage { get; set; } = "Chargement des commandes...";
[ObservableProperty]
public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Chargement des commandes...");
public string Title => IsReadOnly public string Title => IsReadOnly
? $"Demandes en cours ({Form.Title})" ? $"Demandes en cours ({Form.Title})"
: $"Commandes {Form.Title}"; : $"Commandes {Form.Title}";
public string ContextLabel => $"{Performer.UserName} · {Activity.Name}"; public string ContextLabel => $"{Performer.UserName} · {Activity.Name}";
public bool CanOpenDetails => !IsReadOnly; public bool CanOpenDetails => true;
public override bool CanNavigateNext public override bool CanNavigateNext
{ {
@ -72,7 +75,7 @@ public partial class BillingQueriesPageViewModel : ViewModelBase
public Task InitializeAsync() => RefreshAsync(); public Task InitializeAsync() => RefreshAsync();
private bool CanOpenSelectedQuery() => !IsReadOnly && SelectedQuery is not null; private bool CanOpenSelectedQuery() => SelectedQuery is not null;
[RelayCommand] [RelayCommand]
public async Task RefreshAsync() public async Task RefreshAsync()
@ -90,17 +93,17 @@ public partial class BillingQueriesPageViewModel : ViewModelBase
.ToList(); .ToList();
Queries = new ObservableCollection<BillingQueryDisplayItem>(filtered); Queries = new ObservableCollection<BillingQueryDisplayItem>(filtered);
StatusMessage = BuildLoadedStatusMessage(filtered.Count); this.SetInfoStatus(BuildLoadedStatusMessage(filtered.Count));
} }
catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
{ {
Queries = new ObservableCollection<BillingQueryDisplayItem>(); Queries = new ObservableCollection<BillingQueryDisplayItem>();
StatusMessage = "Accès refusé au billing (scope 'api'). Déconnectez puis reconnectez-vous."; this.SetWarningStatus("Accès refusé au billing (scope 'api'). Déconnectez puis reconnectez-vous.");
} }
catch (Exception ex) catch (Exception ex)
{ {
Queries = new ObservableCollection<BillingQueryDisplayItem>(); Queries = new ObservableCollection<BillingQueryDisplayItem>();
StatusMessage = $"Erreur: {ex.Message}"; this.SetErrorStatus($"Erreur: {ex.Message}");
} }
finally finally
{ {
@ -111,15 +114,9 @@ public partial class BillingQueriesPageViewModel : ViewModelBase
[RelayCommand(CanExecute = nameof(CanOpenSelectedQuery))] [RelayCommand(CanExecute = nameof(CanOpenSelectedQuery))]
public async Task OpenSelectedQueryAsync() public async Task OpenSelectedQueryAsync()
{ {
if (IsReadOnly)
{
StatusMessage = "Mode lecture seule: l'ouverture en modification est désactivée.";
return;
}
if (SelectedQuery is null) if (SelectedQuery is null)
{ {
StatusMessage = "Sélectionnez une commande."; this.SetWarningStatus("Sélectionnez une commande.");
return; return;
} }
@ -133,17 +130,22 @@ public partial class BillingQueriesPageViewModel : ViewModelBase
try try
{ {
var details = await _billingClient.GetQueryAsync(Form.ActionName, SelectedQuery.Id).ConfigureAwait(true); var details = await _billingClient.GetQueryAsync(Form.ActionName, SelectedQuery.Id).ConfigureAwait(true);
var vm = Form.CreateCommandPageViewModel(Activity, Performer, _billingClient); var vm = new BillingQueryDetailsPageViewModel(
await vm!.InitializeAsync(details).ConfigureAwait(true); Activity,
Performer,
Form,
_billingClient,
details,
IsReadOnly);
await app.PushPageAsync(vm).ConfigureAwait(true); await app.PushPageAsync(vm).ConfigureAwait(true);
} }
catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
{ {
StatusMessage = "Accès refusé au billing (scope 'api'). Déconnectez puis reconnectez-vous."; this.SetWarningStatus("Accès refusé au billing (scope 'api'). Déconnectez puis reconnectez-vous.");
} }
catch (Exception ex) catch (Exception ex)
{ {
StatusMessage = $"Erreur lors de l'ouverture: {ex.Message}"; this.SetErrorStatus($"Erreur lors de l'ouverture: {ex.Message}");
} }
finally finally
{ {

View file

@ -0,0 +1,208 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using PostIt.Helpers;
using Yavsc;
using Yavsc.Abstract.Workflow;
using Yavsc.Api.Client;
namespace PostIt.ViewModels;
public partial class BillingQueryDetailsPageViewModel : ViewModelBase, IActionStatusViewModel
{
private readonly BillingApiClient _billingClient;
private readonly BillingQueryDetailsDto _details;
public ActivityInfo Activity { get; }
public ActivityUserDisplayItem Performer { get; }
public CommandFormSummary Form { get; }
public bool IsReadOnly { get; }
public long Id => _details.Id;
public string Title => $"Detail commande #{_details.Id}";
public string ContextLabel => $"{Performer.UserName} · {Activity.Name} · {Form.Title}";
public string StatusLabel => _details.Status.ToString();
public string StatusGlyph => GetStatusGlyph(_details.Status);
public string StatusBadgeBackground => GetStatusBadgeBackground(_details.Status);
public string StatusBadgeBorder => GetStatusBadgeBorder(_details.Status);
public string StatusBadgeForeground => GetStatusBadgeForeground(_details.Status);
public string TitleForeground => StatusBadgeForeground;
public string BillingCode => _details.BillingCode;
public string Description => EmptyAsPlaceholder(_details.Description, "(sans description)");
public string Reason => EmptyAsPlaceholder(_details.Reason, "(aucun motif)");
public string AdditionalInfo => EmptyAsPlaceholder(_details.AdditionalInfo, "(aucune info complementaire)");
public string ClientId => EmptyAsPlaceholder(_details.ClientId, "(non renseigne)");
public string EventDateLabel => _details.EventDate?.ToLocalTime().ToString("f") ?? "Date non precisee";
public string ConsentLabel => _details.Consent ? "Oui" : "Non";
public string ProvisionalLabel => _details.Provisional.HasValue ? _details.Provisional.Value.ToString("0.00") : "(non renseigne)";
public string LocationLabel => BuildLocationLabel(_details.Location);
public string PrestationsLabel => BuildPrestationsLabel(_details);
public bool CanEdit => !IsReadOnly;
[ObservableProperty]
public partial bool IsBusy { get; set; }
[ObservableProperty]
public partial string StatusMessage { get; set; } = "Pret.";
[ObservableProperty]
public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Pret.");
public override bool CanNavigateNext
{
get => false;
protected set { _ = value; }
}
public override bool CanNavigatePrevious
{
get => true;
protected set { _ = value; }
}
public BillingQueryDetailsPageViewModel(
ActivityInfo activity,
ActivityUserDisplayItem performer,
CommandFormSummary form,
BillingApiClient billingClient,
BillingQueryDetailsDto details,
bool isReadOnly)
{
Activity = activity ?? throw new ArgumentNullException(nameof(activity));
Performer = performer ?? throw new ArgumentNullException(nameof(performer));
Form = form ?? throw new ArgumentNullException(nameof(form));
_billingClient = billingClient ?? throw new ArgumentNullException(nameof(billingClient));
_details = details ?? throw new ArgumentNullException(nameof(details));
IsReadOnly = isReadOnly;
this.SetInfoStatus("Details de commande charges.");
}
[RelayCommand]
private async Task OpenEditorAsync()
{
if (IsReadOnly)
{
this.SetWarningStatus("Mode lecture seule: edition desactivee.");
return;
}
var app = (App?)Application.Current;
if (app is null)
{
throw new InvalidOperationException("Application PostIt indisponible.");
}
IsBusy = true;
try
{
var vm = Form.CreateCommandPageViewModel(Activity, Performer, _billingClient);
if (vm is null)
{
this.SetWarningStatus("Ce formulaire n'est pas encore pris en charge en edition.");
return;
}
await vm.InitializeAsync(_details).ConfigureAwait(true);
await app.PushPageAsync(vm).ConfigureAwait(true);
}
catch (Exception ex)
{
this.SetErrorStatus($"Erreur lors de l'ouverture en edition: {ex.Message}");
}
finally
{
IsBusy = false;
}
}
[RelayCommand]
private async Task BackAsync()
{
var app = (App?)Application.Current;
if (app is null)
{
throw new InvalidOperationException("Application PostIt indisponible.");
}
await app.GoBackAsync().ConfigureAwait(true);
}
private static string EmptyAsPlaceholder(string? value, string placeholder)
=> string.IsNullOrWhiteSpace(value) ? placeholder : value;
private static string BuildLocationLabel(BillingLocationDto? location)
{
if (location is null)
{
return "(non renseignee)";
}
var text = EmptyAsPlaceholder(location.Address, "adresse vide");
if (location.Latitude.HasValue && location.Longitude.HasValue)
{
text += $" ({location.Latitude.Value:0.####}, {location.Longitude.Value:0.####})";
}
return text;
}
private static string BuildPrestationsLabel(BillingQueryDetailsDto details)
{
if (details.PrestationIds.Count > 0)
{
return string.Join(", ", details.PrestationIds.Select(static id => id.ToString()));
}
return details.PrestationId.HasValue
? details.PrestationId.Value.ToString()
: "(aucune)";
}
private static string GetStatusBadgeBackground(QueryStatus status)
=> status switch
{
QueryStatus.Accepted => "#E6F7EC",
QueryStatus.InProgress => "#FFF4D6",
QueryStatus.Rejected => "#FDECEA",
QueryStatus.Failed => "#ECEFF1",
QueryStatus.Success => "#E8F8EF",
_ => "#EAF3FF",
};
private static string GetStatusBadgeBorder(QueryStatus status)
=> status switch
{
QueryStatus.Accepted => "#2E7D32",
QueryStatus.InProgress => "#B26A00",
QueryStatus.Rejected => "#C62828",
QueryStatus.Failed => "#607D8B",
QueryStatus.Success => "#1E8E3E",
_ => "#2A5EA8",
};
private static string GetStatusBadgeForeground(QueryStatus status)
=> status switch
{
QueryStatus.Accepted => "#1B5E20",
QueryStatus.InProgress => "#7A4A00",
QueryStatus.Rejected => "#8E0000",
QueryStatus.Failed => "#37474F",
QueryStatus.Success => "#145A2A",
_ => "#1A4178",
};
private static string GetStatusGlyph(QueryStatus status)
=> status switch
{
QueryStatus.Accepted => "OK",
QueryStatus.InProgress => "~",
QueryStatus.Rejected => "!",
QueryStatus.Failed => "X",
QueryStatus.Success => "V",
_ => "i",
};
}

View file

@ -34,7 +34,7 @@ namespace PostIt.ViewModels;
/// <see cref="OnAddMemberConfirmedAsync"/>. The "remove" /// <see cref="OnAddMemberConfirmedAsync"/>. The "remove"
/// command is per-row and runs inline.</para> /// command is per-row and runs inline.</para>
/// </summary> /// </summary>
public partial class CirclesPageViewModel : ViewModelBase public partial class CirclesPageViewModel : ViewModelBase, IActionStatusViewModel
{ {
private readonly CircleApiClient _client; private readonly CircleApiClient _client;
@ -63,8 +63,10 @@ public partial class CirclesPageViewModel : ViewModelBase
public partial bool IsBusy { get; set; } public partial bool IsBusy { get; set; }
[ObservableProperty] [ObservableProperty]
public partial string StatusMessage { get; set; } = string.Empty; public partial string StatusMessage { get; set; } = "Pret.";
[ObservableProperty]
public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Pret.");
public CirclesPageViewModel(CircleApiClient client) public CirclesPageViewModel(CircleApiClient client)
{ {
@ -100,11 +102,11 @@ public partial class CirclesPageViewModel : ViewModelBase
{ {
var list = await _client.GetMyCirclesAsync(); var list = await _client.GetMyCirclesAsync();
Circles = new ObservableCollection<CircleDto>(list ?? new()); Circles = new ObservableCollection<CircleDto>(list ?? new());
StatusMessage = $"{Circles.Count} cercle(s)"; this.SetInfoStatus($"{Circles.Count} cercle(s)");
} }
catch (Exception ex) catch (Exception ex)
{ {
StatusMessage = $"Erreur: {ex.Message}"; this.SetErrorStatus($"Erreur: {ex.Message}");
} }
finally finally
{ {
@ -115,8 +117,10 @@ public partial class CirclesPageViewModel : ViewModelBase
[RelayCommand] [RelayCommand]
internal async Task OpenAddMemberAsync() internal async Task OpenAddMemberAsync()
{ {
var app = Application.Current as App; var app = Application.Current as App
var services = app?.ServiceProvider; ?? throw new InvalidOperationException("Application PostIt indisponible.");
var services = app.ServiceProvider
?? throw new InvalidOperationException("ServiceProvider PostIt indisponible.");
var directory = services.GetRequiredService<IUserDirectory>(); var directory = services.GetRequiredService<IUserDirectory>();
AddCircleMemberDialogViewModel model = AddCircleMemberDialogViewModel model =
new AddCircleMemberDialogViewModel(directory); new AddCircleMemberDialogViewModel(directory);
@ -147,11 +151,11 @@ public partial class CirclesPageViewModel : ViewModelBase
{ {
var list = await _client.GetMembersAsync(circleId); var list = await _client.GetMembersAsync(circleId);
Members = new ObservableCollection<CircleMemberDto>(list ?? new()); Members = new ObservableCollection<CircleMemberDto>(list ?? new());
StatusMessage = $"{Members.Count} membre(s)"; this.SetInfoStatus($"{Members.Count} membre(s)");
} }
catch (Exception ex) catch (Exception ex)
{ {
StatusMessage = $"Erreur: {ex.Message}"; this.SetErrorStatus($"Erreur: {ex.Message}");
Members = new ObservableCollection<CircleMemberDto>(); Members = new ObservableCollection<CircleMemberDto>();
} }
finally finally
@ -166,7 +170,7 @@ public partial class CirclesPageViewModel : ViewModelBase
SelectedCircle = null; SelectedCircle = null;
DraftName = string.Empty; DraftName = string.Empty;
DraftPublic = false; DraftPublic = false;
StatusMessage = "Nouveau cercle"; this.SetInfoStatus("Nouveau cercle");
} }
[RelayCommand] [RelayCommand]
@ -176,7 +180,7 @@ public partial class CirclesPageViewModel : ViewModelBase
SelectedCircle = circle; SelectedCircle = circle;
DraftName = circle.Name; DraftName = circle.Name;
DraftPublic = circle.Public; DraftPublic = circle.Public;
StatusMessage = $"Édition de « {circle.Name} »"; this.SetInfoStatus($"Édition de « {circle.Name} »");
} }
[RelayCommand] [RelayCommand]
@ -184,7 +188,7 @@ public partial class CirclesPageViewModel : ViewModelBase
{ {
if (string.IsNullOrWhiteSpace(DraftName)) if (string.IsNullOrWhiteSpace(DraftName))
{ {
StatusMessage = "Le nom est obligatoire"; this.SetWarningStatus("Le nom est obligatoire");
return; return;
} }
@ -198,22 +202,22 @@ public partial class CirclesPageViewModel : ViewModelBase
Name = DraftName.Trim(), Name = DraftName.Trim(),
Public = DraftPublic, Public = DraftPublic,
}); });
StatusMessage = created is null this.SetStatus(
? "Création échouée" created is null ? "Création échouée" : $"Cercle « {created.Name} » créé",
: $"Cercle « {created.Name} » créé"; created is null ? StatusSeverity.Warning : StatusSeverity.Info);
} }
else else
{ {
SelectedCircle.Name = DraftName.Trim(); SelectedCircle.Name = DraftName.Trim();
SelectedCircle.Public = DraftPublic; SelectedCircle.Public = DraftPublic;
await _client.UpdateCircleAsync(SelectedCircle.Id, SelectedCircle); await _client.UpdateCircleAsync(SelectedCircle.Id, SelectedCircle);
StatusMessage = $"Cercle « {SelectedCircle.Name} » mis à jour"; this.SetInfoStatus($"Cercle « {SelectedCircle.Name} » mis à jour");
} }
await RefreshAsync(); await RefreshAsync();
} }
catch (Exception ex) catch (Exception ex)
{ {
StatusMessage = $"Erreur: {ex.Message}"; this.SetErrorStatus($"Erreur: {ex.Message}");
} }
finally finally
{ {
@ -229,7 +233,7 @@ public partial class CirclesPageViewModel : ViewModelBase
try try
{ {
await _client.DeleteCircleAsync(circle.Id); await _client.DeleteCircleAsync(circle.Id);
StatusMessage = $"Cercle « {circle.Name} » supprimé"; this.SetInfoStatus($"Cercle « {circle.Name} » supprimé");
// If the deleted circle was the selected one, // If the deleted circle was the selected one,
// clear the selection so the Members view goes // clear the selection so the Members view goes
// empty too (the partial setter on // empty too (the partial setter on
@ -240,7 +244,7 @@ public partial class CirclesPageViewModel : ViewModelBase
} }
catch (Exception ex) catch (Exception ex)
{ {
StatusMessage = $"Erreur: {ex.Message}"; this.SetErrorStatus($"Erreur: {ex.Message}");
} }
finally finally
{ {
@ -261,7 +265,7 @@ public partial class CirclesPageViewModel : ViewModelBase
try try
{ {
await _client.AddMemberAsync(SelectedCircle.Id, picked.Id); await _client.AddMemberAsync(SelectedCircle.Id, picked.Id);
StatusMessage = $"« {picked.DisplayName} » ajouté au cercle"; this.SetInfoStatus($"« {picked.DisplayName} » ajouté au cercle");
await LoadMembersAsync(SelectedCircle.Id); await LoadMembersAsync(SelectedCircle.Id);
} }
catch (Exception ex) catch (Exception ex)
@ -276,7 +280,7 @@ public partial class CirclesPageViewModel : ViewModelBase
var msg = ex.Message.Contains("409") || ex.Message.Contains("Conflict") var msg = ex.Message.Contains("409") || ex.Message.Contains("Conflict")
? "Déjà membre du cercle" ? "Déjà membre du cercle"
: $"Erreur: {ex.Message}"; : $"Erreur: {ex.Message}";
StatusMessage = msg; this.SetStatus(msg, msg == "Déjà membre du cercle" ? StatusSeverity.Warning : StatusSeverity.Error);
} }
finally finally
{ {
@ -297,11 +301,11 @@ public partial class CirclesPageViewModel : ViewModelBase
{ {
await _client.RemoveMemberAsync(SelectedCircle.Id, member.Id); await _client.RemoveMemberAsync(SelectedCircle.Id, member.Id);
Members.Remove(member); Members.Remove(member);
StatusMessage = $"« {member.UserName} » retiré du cercle"; this.SetInfoStatus($"« {member.UserName} » retiré du cercle");
} }
catch (Exception ex) catch (Exception ex)
{ {
StatusMessage = $"Erreur: {ex.Message}"; this.SetErrorStatus($"Erreur: {ex.Message}");
} }
finally finally
{ {

View file

@ -11,7 +11,7 @@ using Yavsc.Api.Client;
namespace PostIt.ViewModels; namespace PostIt.ViewModels;
public partial class CommandFormsPageViewModel : ViewModelBase public partial class CommandFormsPageViewModel : ViewModelBase, IActionStatusViewModel
{ {
private readonly BillingApiClient _billingClient; private readonly BillingApiClient _billingClient;
@ -25,7 +25,10 @@ public partial class CommandFormsPageViewModel : ViewModelBase
public partial CommandFormSummary? SelectedForm { get; set; } public partial CommandFormSummary? SelectedForm { get; set; }
[ObservableProperty] [ObservableProperty]
public partial string StatusMessage { get; set; } public partial string StatusMessage { get; set; } = "Pret.";
[ObservableProperty]
public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Pret.");
public string Title => $"Formulaires pour {Performer.UserName}"; public string Title => $"Formulaires pour {Performer.UserName}";
public string ContextLabel => $"{Activity.Name} · {Forms.Count} formulaire(s)"; public string ContextLabel => $"{Activity.Name} · {Forms.Count} formulaire(s)";
@ -55,9 +58,11 @@ public partial class CommandFormsPageViewModel : ViewModelBase
.OrderBy(f => f.Title) .OrderBy(f => f.Title)
.ThenBy(f => f.ActionName)); .ThenBy(f => f.ActionName));
SelectedForm = Forms.FirstOrDefault(); SelectedForm = Forms.FirstOrDefault();
StatusMessage = Forms.Count == 0 this.SetStatus(
? "Aucun formulaire n'est disponible pour cette activité." Forms.Count == 0
: "Choisissez le formulaire à utiliser."; ? "Aucun formulaire n'est disponible pour cette activité."
: "Choisissez le formulaire à utiliser.",
Forms.Count == 0 ? StatusSeverity.Warning : StatusSeverity.Info);
} }
private bool CanOpenSelectedForm() => SelectedForm is not null; private bool CanOpenSelectedForm() => SelectedForm is not null;
@ -71,7 +76,7 @@ public partial class CommandFormsPageViewModel : ViewModelBase
{ {
if (SelectedForm is null) if (SelectedForm is null)
{ {
StatusMessage = "Sélectionnez un formulaire."; this.SetWarningStatus("Sélectionnez un formulaire.");
return; return;
} }
@ -92,7 +97,7 @@ public partial class CommandFormsPageViewModel : ViewModelBase
{ {
if (SelectedForm is null) if (SelectedForm is null)
{ {
StatusMessage = "Sélectionnez un formulaire."; this.SetWarningStatus("Sélectionnez un formulaire.");
return; return;
} }
@ -112,7 +117,7 @@ public partial class CommandFormsPageViewModel : ViewModelBase
{ {
if (SelectedForm is null) if (SelectedForm is null)
{ {
StatusMessage = "Sélectionnez un formulaire."; this.SetWarningStatus("Sélectionnez un formulaire.");
return; return;
} }

View file

@ -9,7 +9,7 @@ using Yavsc.Models.Billing;
namespace PostIt.ViewModels; namespace PostIt.ViewModels;
public abstract partial class BillingCommandPageViewModel : RemoteViewModelBase public abstract partial class BillingCommandPageViewModel : RemoteViewModelBase, IActionStatusViewModel
{ {
protected readonly BillingApiClient _billingClient; protected readonly BillingApiClient _billingClient;
@ -21,7 +21,10 @@ public abstract partial class BillingCommandPageViewModel : RemoteViewModelBase
public partial bool IsBusy { get; set; } public partial bool IsBusy { get; set; }
[ObservableProperty] [ObservableProperty]
public partial string StatusMessage { get; set; } public partial string StatusMessage { get; set; } = "Pret.";
[ObservableProperty]
public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Pret.");
[ObservableProperty] [ObservableProperty]
public partial string Reason { get; set; } = string.Empty; public partial string Reason { get; set; } = string.Empty;
@ -75,7 +78,7 @@ public abstract partial class BillingCommandPageViewModel : RemoteViewModelBase
Form = form ?? throw new ArgumentNullException(nameof(form)); Form = form ?? throw new ArgumentNullException(nameof(form));
_billingClient = billingClient ?? throw new ArgumentNullException(nameof(billingClient)); _billingClient = billingClient ?? throw new ArgumentNullException(nameof(billingClient));
StatusMessage = SupportMessage; this.SetInfoStatus(SupportMessage);
} }
partial void OnExistingQueryIdChanged(long? value) partial void OnExistingQueryIdChanged(long? value)

View file

@ -58,18 +58,20 @@ public partial class BrushViewModel : RdvViewModel
SelectedPrestation = AvailablePrestations.FirstOrDefault(); SelectedPrestation = AvailablePrestations.FirstOrDefault();
} }
StatusMessage = AvailablePrestations.Count == 0 this.SetStatus(
? "Aucune prestation coiffure disponible." AvailablePrestations.Count == 0
: SupportMessage; ? "Aucune prestation coiffure disponible."
: SupportMessage,
AvailablePrestations.Count == 0 ? StatusSeverity.Warning : StatusSeverity.Info);
} }
catch (HttpRequestException ex) catch (HttpRequestException ex)
when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
{ {
StatusMessage = "Accès refusé au catalogue de prestations (scope 'api'). Déconnectez puis reconnectez-vous."; this.SetWarningStatus("Accès refusé au catalogue de prestations (scope 'api'). Déconnectez puis reconnectez-vous.");
} }
catch (Exception ex) catch (Exception ex)
{ {
StatusMessage = $"Erreur lors du chargement des prestations: {ex.Message}"; this.SetErrorStatus($"Erreur lors du chargement des prestations: {ex.Message}");
} }
finally finally
{ {
@ -81,19 +83,19 @@ public partial class BrushViewModel : RdvViewModel
{ {
if (!Consent) if (!Consent)
{ {
StatusMessage = "Le consentement est requis pour poster la commande."; this.SetWarningStatus("Le consentement est requis pour poster la commande.");
return; return;
} }
if (string.IsNullOrWhiteSpace(Address)) if (string.IsNullOrWhiteSpace(Address))
{ {
StatusMessage = "L'adresse du rendez-vous est requise."; this.SetWarningStatus("L'adresse du rendez-vous est requise.");
return; return;
} }
if (SelectedPrestation is null) if (SelectedPrestation is null)
{ {
StatusMessage = "Sélectionnez une prestation coiffure."; this.SetWarningStatus("Sélectionnez une prestation coiffure.");
return; return;
} }
@ -143,18 +145,18 @@ public partial class BrushViewModel : RdvViewModel
}).ConfigureAwait(true); }).ConfigureAwait(true);
} }
StatusMessage = IsEditingExisting this.SetInfoStatus(IsEditingExisting
? $"Commande #{ExistingQueryId} mise à jour sur {BillingRoute} pour {Performer.UserName}." ? $"Commande #{ExistingQueryId} mise à jour sur {BillingRoute} pour {Performer.UserName}."
: $"Commande transmise sur {BillingRoute} pour {Performer.UserName}."; : $"Commande transmise sur {BillingRoute} pour {Performer.UserName}.");
} }
catch (HttpRequestException ex) catch (HttpRequestException ex)
when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
{ {
StatusMessage = "Accès refusé au billing (scope 'api'). Déconnectez puis reconnectez-vous."; this.SetWarningStatus("Accès refusé au billing (scope 'api'). Déconnectez puis reconnectez-vous.");
} }
catch (Exception ex) catch (Exception ex)
{ {
StatusMessage = $"Erreur lors de l'envoi de la commande: {ex.Message}"; this.SetErrorStatus($"Erreur lors de l'envoi de la commande: {ex.Message}");
} }
finally finally
{ {

View file

@ -49,20 +49,20 @@ public partial class MBrushViewModel : BrushViewModel
{ {
if (!Consent) if (!Consent)
{ {
StatusMessage = "Le consentement est requis pour poster la commande."; this.SetWarningStatus("Le consentement est requis pour poster la commande.");
return; return;
} }
if (string.IsNullOrWhiteSpace(Address)) if (string.IsNullOrWhiteSpace(Address))
{ {
StatusMessage = "L'adresse du rendez-vous est requise."; this.SetWarningStatus("L'adresse du rendez-vous est requise.");
return; return;
} }
var selectedPrestations = MultiPrestations.Where(x => x.IsSelected).ToList(); var selectedPrestations = MultiPrestations.Where(x => x.IsSelected).ToList();
if (selectedPrestations.Count == 0) if (selectedPrestations.Count == 0)
{ {
StatusMessage = "Sélectionnez au moins une prestation coiffure."; this.SetWarningStatus("Sélectionnez au moins une prestation coiffure.");
return; return;
} }
@ -109,18 +109,18 @@ public partial class MBrushViewModel : BrushViewModel
}).ConfigureAwait(true); }).ConfigureAwait(true);
} }
StatusMessage = IsEditingExisting this.SetInfoStatus(IsEditingExisting
? $"Commande #{ExistingQueryId} mise à jour sur {BillingRoute} pour {Performer.UserName}." ? $"Commande #{ExistingQueryId} mise à jour sur {BillingRoute} pour {Performer.UserName}."
: $"Commande transmise sur {BillingRoute} pour {Performer.UserName}."; : $"Commande transmise sur {BillingRoute} pour {Performer.UserName}.");
} }
catch (HttpRequestException ex) catch (HttpRequestException ex)
when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
{ {
StatusMessage = "Accès refusé au billing (scope 'api'). Déconnectez puis reconnectez-vous."; this.SetWarningStatus("Accès refusé au billing (scope 'api'). Déconnectez puis reconnectez-vous.");
} }
catch (Exception ex) catch (Exception ex)
{ {
StatusMessage = $"Erreur lors de l'envoi de la commande: {ex.Message}"; this.SetErrorStatus($"Erreur lors de l'envoi de la commande: {ex.Message}");
} }
finally finally
{ {

View file

@ -17,6 +17,12 @@ public partial class RdvViewModel : BillingCommandPageViewModel
[ObservableProperty] [ObservableProperty]
public partial string Address { get; set; } = string.Empty; 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] [ObservableProperty]
public partial double? Latitude { get; set; } public partial double? Latitude { get; set; }
@ -27,12 +33,27 @@ public partial class RdvViewModel : BillingCommandPageViewModel
[ObservableProperty] [ObservableProperty]
public partial DateTime EventDate { get; set; } public partial DateTime EventDate { get; set; }
public DateTimeOffset? EventDateSelection
{
get => new(EventDate);
set
{
if (!value.HasValue)
return;
EventDate = value.Value.LocalDateTime;
}
}
public RdvViewModel(ActivityInfo activity, ActivityUserDisplayItem performer, CommandFormSummary form, BillingApiClient billingClient) public RdvViewModel(ActivityInfo activity, ActivityUserDisplayItem performer, CommandFormSummary form, BillingApiClient billingClient)
: base(activity, performer, form, billingClient) : base(activity, performer, form, billingClient)
{ {
EventDate = DateTime.Now.AddDays(1); EventDate = DateTime.Now.AddDays(1);
} }
public bool HasSuggestedAddress => !string.IsNullOrWhiteSpace(SuggestedAddress);
public bool HasSuggestedAddressPanel => HasSuggestedAddress || IsResolvingAddress;
protected override void ApplyExistingQuery(BillingQueryDetailsDto existingQuery) protected override void ApplyExistingQuery(BillingQueryDetailsDto existingQuery)
{ {
ExistingQueryId = existingQuery.Id; ExistingQueryId = existingQuery.Id;
@ -50,11 +71,12 @@ public partial class RdvViewModel : BillingCommandPageViewModel
if (existingQuery.Location is not null) if (existingQuery.Location is not null)
{ {
Address = existingQuery.Location.Address ?? string.Empty; Address = existingQuery.Location.Address ?? string.Empty;
SuggestedAddress = string.Empty;
Latitude = existingQuery.Location.Latitude; Latitude = existingQuery.Location.Latitude;
Longitude = existingQuery.Location.Longitude; Longitude = existingQuery.Location.Longitude;
} }
StatusMessage = $"Commande #{existingQuery.Id} chargée."; this.SetInfoStatus($"Commande #{existingQuery.Id} chargée.");
} }
[RelayCommand(CanExecute = nameof(CanUseCurrentLocation))] [RelayCommand(CanExecute = nameof(CanUseCurrentLocation))]
@ -71,23 +93,23 @@ public partial class RdvViewModel : BillingCommandPageViewModel
var result = await Platform.TryGetCurrentLocationAsync(default).ConfigureAwait(true); var result = await Platform.TryGetCurrentLocationAsync(default).ConfigureAwait(true);
if (!result.IsSuccess || !result.Latitude.HasValue || !result.Longitude.HasValue) if (!result.IsSuccess || !result.Latitude.HasValue || !result.Longitude.HasValue)
{ {
StatusMessage = result.Message; this.SetWarningStatus(result.Message);
return; return;
} }
Latitude = result.Latitude.Value; Latitude = result.Latitude.Value;
Longitude = result.Longitude.Value; Longitude = result.Longitude.Value;
StatusMessage = string.IsNullOrWhiteSpace(Address) this.SetInfoStatus(string.IsNullOrWhiteSpace(Address)
? "Position récupérée. Complétez l'adresse puis envoyez la commande." ? "Position récupérée. Complétez l'adresse puis envoyez la commande."
: result.Message; : result.Message);
} }
catch (OperationCanceledException) catch (OperationCanceledException)
{ {
StatusMessage = "La récupération de la position a été annulée."; this.SetWarningStatus("La récupération de la position a été annulée.");
} }
catch (Exception ex) catch (Exception ex)
{ {
StatusMessage = $"Impossible de récupérer la position: {ex.Message}"; this.SetErrorStatus($"Impossible de récupérer la position: {ex.Message}");
} }
finally finally
{ {
@ -113,31 +135,119 @@ public partial class RdvViewModel : BillingCommandPageViewModel
}; };
} }
public void ApplyLocationFromMap(double latitude, double longitude)
{
Latitude = Math.Round(latitude, 6);
Longitude = Math.Round(longitude, 6);
if (string.IsNullOrWhiteSpace(Address))
{
this.SetInfoStatus("Position sélectionnée sur la carte. Complétez l'adresse puis envoyez la commande.");
return;
}
this.SetInfoStatus("Position sélectionnée sur la carte.");
}
public void NotifyReverseGeocodingStarted()
{
IsResolvingAddress = true;
this.SetInfoStatus(string.IsNullOrWhiteSpace(Address)
? "Recherche de l'adresse depuis la carte..."
: "Recherche d'une adresse suggérée..."
);
}
public void NotifyReverseGeocodingUnavailable()
{
IsResolvingAddress = false;
if (HasSuggestedAddress || !string.IsNullOrWhiteSpace(Address))
return;
this.SetInfoStatus("Position sélectionnée sur la carte. Complétez l'adresse puis envoyez la commande.");
}
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;
this.SetInfoStatus("Adresse mise à jour depuis la carte.");
return;
}
if (string.Equals(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));
}
protected override async Task SubmitAsync() protected override async Task SubmitAsync()
{ {
if (!IsSupported) if (!IsSupported)
{ {
StatusMessage = SupportMessage; this.SetWarningStatus(SupportMessage);
return; return;
} }
if (!Consent) if (!Consent)
{ {
StatusMessage = "Le consentement est requis pour poster la commande."; this.SetWarningStatus("Le consentement est requis pour poster la commande.");
return; return;
} }
if (string.IsNullOrWhiteSpace(Address)) if (string.IsNullOrWhiteSpace(Address))
{ {
StatusMessage = "L'adresse du rendez-vous est requise."; this.SetWarningStatus("L'adresse du rendez-vous est requise.");
return; return;
} }
if (string.IsNullOrWhiteSpace(Reason)) if (string.IsNullOrWhiteSpace(Reason))
{ {
StatusMessage = "Le motif du rendez-vous est requis."; this.SetWarningStatus("Le motif du rendez-vous est requis.");
return; return;
} }
@ -186,17 +296,17 @@ public partial class RdvViewModel : BillingCommandPageViewModel
}).ConfigureAwait(true); }).ConfigureAwait(true);
} }
StatusMessage = IsEditingExisting this.SetInfoStatus(IsEditingExisting
? $"Commande #{ExistingQueryId} mise à jour sur {BillingRoute} pour {Performer.UserName}." ? $"Commande #{ExistingQueryId} mise à jour sur {BillingRoute} pour {Performer.UserName}."
: $"Commande transmise sur {BillingRoute} pour {Performer.UserName}."; : $"Commande transmise sur {BillingRoute} pour {Performer.UserName}.");
} }
catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
{ {
StatusMessage = "Accès refusé au billing (scope 'api'). Déconnectez puis reconnectez-vous."; this.SetWarningStatus("Accès refusé au billing (scope 'api'). Déconnectez puis reconnectez-vous.");
} }
catch (Exception ex) catch (Exception ex)
{ {
StatusMessage = $"Erreur lors de l'envoi: {ex.Message}"; this.SetErrorStatus($"Erreur lors de l'envoi: {ex.Message}");
} }
finally finally
{ {

View file

@ -12,7 +12,7 @@ using PostIt.Helpers;
namespace PostIt.ViewModels; namespace PostIt.ViewModels;
public partial class MainViewModel : ViewModelBase public partial class MainViewModel : ViewModelBase, IActionStatusViewModel
{ {
/// <summary>Window/tab title. Cosmetic — bound by /// <summary>Window/tab title. Cosmetic — bound by
/// <c>MainPage.axaml</c> if at all. Not the post title.</summary> /// <c>MainPage.axaml</c> if at all. Not the post title.</summary>
@ -54,6 +54,9 @@ public partial class MainViewModel : ViewModelBase
[ObservableProperty] [ObservableProperty]
public partial string StatusMessage { get; set; } public partial string StatusMessage { get; set; }
[ObservableProperty]
public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Pret.");
[ObservableProperty] [ObservableProperty]
public partial string SearchText { get; set; } public partial string SearchText { get; set; }
@ -84,7 +87,7 @@ public partial class MainViewModel : ViewModelBase
Posts.Add(post); Posts.Add(post);
} }
ApplyFilter(); ApplyFilter();
StatusMessage = $"Loaded {Posts.Count} posts."; this.SetInfoStatus($"{Posts.Count} billet(s) chargé(s).");
}); });
} }
@ -104,7 +107,7 @@ public partial class MainViewModel : ViewModelBase
// than to send a request the server will reject. // than to send a request the server will reject.
if (string.IsNullOrWhiteSpace(DraftTitle)) if (string.IsNullOrWhiteSpace(DraftTitle))
{ {
StatusMessage = "Title is required."; this.SetWarningStatus("Le titre est obligatoire.");
return; return;
} }
@ -134,7 +137,7 @@ public partial class MainViewModel : ViewModelBase
if (created is not null) if (created is not null)
{ {
SelectedPost = created; SelectedPost = created;
StatusMessage = $"Created post {created.Id}."; this.SetInfoStatus($"Billet {created.Id} créé.");
} }
} }
else else
@ -150,7 +153,7 @@ public partial class MainViewModel : ViewModelBase
DateModified = DateTime.UtcNow, DateModified = DateTime.UtcNow,
}; };
await BlogClient!.UpdatePostAsync(SelectedPost.Id, update); await BlogClient!.UpdatePostAsync(SelectedPost.Id, update);
StatusMessage = $"Saved post {SelectedPost.Id}."; this.SetInfoStatus($"Billet {SelectedPost.Id} enregistré.");
} }
await RefreshPostsAsync(); await RefreshPostsAsync();
@ -162,14 +165,14 @@ public partial class MainViewModel : ViewModelBase
{ {
if (SelectedPost is null || SelectedPost.Id == 0) if (SelectedPost is null || SelectedPost.Id == 0)
{ {
StatusMessage = "Select an existing post before deleting."; this.SetWarningStatus("Sélectionnez un billet existant avant suppression.");
return; return;
} }
await ExecuteAsync(async () => await ExecuteAsync(async () =>
{ {
await BlogClient!.DeletePostAsync(SelectedPost.Id); await BlogClient!.DeletePostAsync(SelectedPost.Id);
StatusMessage = $"Deleted post {SelectedPost.Id}."; this.SetInfoStatus($"Billet {SelectedPost.Id} supprimé.");
SelectedPost = null; SelectedPost = null;
await RefreshPostsAsync(); await RefreshPostsAsync();
}); });
@ -194,7 +197,7 @@ public partial class MainViewModel : ViewModelBase
{ {
if (SelectedPost is null || SelectedPost.Id == 0) if (SelectedPost is null || SelectedPost.Id == 0)
{ {
StatusMessage = "Sélectionnez un billet existant pour changer sa publication."; this.SetWarningStatus("Sélectionnez un billet existant pour changer sa publication.");
return; return;
} }
@ -211,9 +214,9 @@ public partial class MainViewModel : ViewModelBase
// locally flipped state until the round-trip // locally flipped state until the round-trip
// re-hydrates it. // re-hydrates it.
SelectedPost.IsPublished = publish; SelectedPost.IsPublished = publish;
StatusMessage = publish this.SetInfoStatus(publish
? $"Billet {SelectedPost.Id} publié." ? $"Billet {SelectedPost.Id} publié."
: $"Billet {SelectedPost.Id} remis en brouillon."; : $"Billet {SelectedPost.Id} remis en brouillon.");
}); });
} }
@ -247,7 +250,7 @@ public partial class MainViewModel : ViewModelBase
{ {
if (SelectedPost is null) if (SelectedPost is null)
{ {
StatusMessage = "Select an existing post before managing ACL."; this.SetWarningStatus("Sélectionnez un billet existant avant de gérer l'ACL.");
return; return;
} }
@ -346,7 +349,7 @@ public partial class MainViewModel : ViewModelBase
FilteredPosts = new ObservableCollection<BlogPostDto>(); FilteredPosts = new ObservableCollection<BlogPostDto>();
SelectedPost = null; SelectedPost = null;
IsBusy = false; IsBusy = false;
StatusMessage = "Ready"; this.SetInfoStatus("Prêt.");
Settings = settings ?? new Settings(); Settings = settings ?? new Settings();
SearchText = Settings.SearchText; SearchText = Settings.SearchText;
WindowTitle = "PostIt"; WindowTitle = "PostIt";
@ -476,12 +479,12 @@ public partial class MainViewModel : ViewModelBase
try try
{ {
IsBusy = true; IsBusy = true;
StatusMessage = "Working..."; this.SetInfoStatus("Traitement en cours...");
await action(); await action();
} }
catch (Exception ex) catch (Exception ex)
{ {
StatusMessage = $"Error: {ex.Message}"; this.SetErrorStatus($"Erreur: {ex.Message}");
} }
finally finally
{ {

View file

@ -37,7 +37,7 @@ public sealed class PostAclEntry
/// any 403 / 404 will surface as an exception caught by the /// any 403 / 404 will surface as an exception caught by the
/// command and routed to <see cref="StatusMessage"/>.</para> /// command and routed to <see cref="StatusMessage"/>.</para>
/// </summary> /// </summary>
public partial class PostAclDialogViewModel : ViewModelBase public partial class PostAclDialogViewModel : ViewModelBase, IActionStatusViewModel
{ {
private readonly BlogAclApiClient _aclClient; private readonly BlogAclApiClient _aclClient;
private readonly CircleApiClient _circleClient; private readonly CircleApiClient _circleClient;
@ -61,7 +61,10 @@ public partial class PostAclDialogViewModel : ViewModelBase
public partial bool IsBusy { get; set; } public partial bool IsBusy { get; set; }
[ObservableProperty] [ObservableProperty]
public partial string StatusMessage { get; set; } = string.Empty; public partial string StatusMessage { get; set; } = "Pret.";
[ObservableProperty]
public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Pret.");
/// <summary> /// <summary>
/// Idempotency gate for <see cref="LoadAsync"/>: the dialog /// Idempotency gate for <see cref="LoadAsync"/>: the dialog
@ -115,12 +118,12 @@ public partial class PostAclDialogViewModel : ViewModelBase
AclEntries = new ObservableCollection<PostAclEntry>(AclEntries.Select(a => ToAclEntry(a.CircleId))); AclEntries = new ObservableCollection<PostAclEntry>(AclEntries.Select(a => ToAclEntry(a.CircleId)));
StatusMessage = $"{AclEntries.Count} autorisation(s)"; this.SetInfoStatus($"{AclEntries.Count} autorisation(s)");
_loaded = true; _loaded = true;
} }
catch (Exception ex) catch (Exception ex)
{ {
StatusMessage = $"Erreur: {ex.Message}"; this.SetErrorStatus($"Erreur: {ex.Message}");
} }
finally finally
{ {
@ -133,7 +136,7 @@ public partial class PostAclDialogViewModel : ViewModelBase
{ {
if (SelectedCircleToAdd is null) if (SelectedCircleToAdd is null)
{ {
StatusMessage = "Sélectionnez un cercle à ajouter"; this.SetWarningStatus("Sélectionnez un cercle à ajouter");
return; return;
} }
@ -142,7 +145,7 @@ public partial class PostAclDialogViewModel : ViewModelBase
{ {
if (AclEntries.Any(a => a.CircleId == SelectedCircleToAdd.Id)) if (AclEntries.Any(a => a.CircleId == SelectedCircleToAdd.Id))
{ {
StatusMessage = $"Cercle « {SelectedCircleToAdd.Name} » déjà autorisé"; this.SetWarningStatus($"Cercle « {SelectedCircleToAdd.Name} » déjà autorisé");
return; return;
} }
@ -154,11 +157,11 @@ public partial class PostAclDialogViewModel : ViewModelBase
if (created is not null) if (created is not null)
{ {
AclEntries.Add(ToAclEntry(created.CircleId)); AclEntries.Add(ToAclEntry(created.CircleId));
StatusMessage = $"Cercle « {SelectedCircleToAdd.Name} » autorisé"; this.SetInfoStatus($"Cercle « {SelectedCircleToAdd.Name} » autorisé");
} }
else else
{ {
StatusMessage = "Autorisation refusée par le serveur"; this.SetWarningStatus("Autorisation refusée par le serveur");
} }
} }
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.Conflict) catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.Conflict)
@ -166,11 +169,11 @@ public partial class PostAclDialogViewModel : ViewModelBase
// Conflict means the link already exists in backend. Resync // Conflict means the link already exists in backend. Resync
// from the dedicated ACL API so the UI reflects server truth. // from the dedicated ACL API so the UI reflects server truth.
await ReloadAclEntriesFromServerAsync(); await ReloadAclEntriesFromServerAsync();
StatusMessage = $"Cercle « {SelectedCircleToAdd.Name} » déjà autorisé"; this.SetWarningStatus($"Cercle « {SelectedCircleToAdd.Name} » déjà autorisé");
} }
catch (Exception ex) catch (Exception ex)
{ {
StatusMessage = $"Erreur: {ex.Message}"; this.SetErrorStatus($"Erreur: {ex.Message}");
} }
finally finally
{ {
@ -189,11 +192,11 @@ public partial class PostAclDialogViewModel : ViewModelBase
var existing = AclEntries.FirstOrDefault(e => e.CircleId == acl.CircleId); var existing = AclEntries.FirstOrDefault(e => e.CircleId == acl.CircleId);
if (existing is not null) if (existing is not null)
AclEntries.Remove(existing); AclEntries.Remove(existing);
StatusMessage = "Autorisation révoquée"; this.SetInfoStatus("Autorisation révoquée");
} }
catch (Exception ex) catch (Exception ex)
{ {
StatusMessage = $"Erreur: {ex.Message}"; this.SetErrorStatus($"Erreur: {ex.Message}");
} }
finally finally
{ {

View file

@ -7,6 +7,7 @@ using System.Collections.Generic;
using System.IO; using System.IO;
using System.Net.Http; using System.Net.Http;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Serialization;
[assembly: InternalsVisibleTo("PostIt.Tests")] [assembly: InternalsVisibleTo("PostIt.Tests")]
@ -31,6 +32,20 @@ public partial class Settings : ViewModelBase
[ObservableProperty] [ObservableProperty]
public partial string SearchText { get; set; } = string.Empty; public partial string SearchText { get; set; } = string.Empty;
[ObservableProperty]
[JsonIgnore]
public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Pret.");
public void SetActionStatus(string message, StatusSeverity severity = StatusSeverity.Info)
{
ActionStatus = severity switch
{
StatusSeverity.Error => StatusNotice.Error(message),
StatusSeverity.Warning => StatusNotice.Warning(message),
_ => StatusNotice.Info(message),
};
}
/// <summary> /// <summary>
/// Catch top-level mutations: the four ObservableProperty /// Catch top-level mutations: the four ObservableProperty
/// setters above all funnel through here, and we flip /// setters above all funnel through here, and we flip
@ -110,6 +125,8 @@ public partial class Settings : ViewModelBase
// build options from a torn read. // build options from a torn read.
lock (_mutationGate) lock (_mutationGate)
{ {
EnsureAuthenticationDefaultsLocked();
var options = new OidcClientOptions var options = new OidcClientOptions
{ {
Authority = Authentication.Authority, Authority = Authentication.Authority,
@ -138,6 +155,25 @@ public partial class Settings : ViewModelBase
} }
} }
private void EnsureAuthenticationDefaultsLocked()
{
Authentication ??= new AuthenticationSettings();
if (string.IsNullOrWhiteSpace(Authentication.Authority))
Authentication.Authority = AuthenticationSettings.DefaultAuthority;
if (string.IsNullOrWhiteSpace(Authentication.ClientId))
Authentication.ClientId = AuthenticationSettings.DefaultClientId;
if (string.IsNullOrWhiteSpace(Authentication.RedirectUri))
Authentication.RedirectUri = AuthenticationSettings.DesktopRedirectUri;
if (Authentication.Scopes is null || Authentication.Scopes.Length == 0)
Authentication.Scopes = AuthenticationSettings.DefaultScopes;
Authentication.RefreshScopeListText();
}
/// <summary> /// <summary>
/// Scopes the PostIt client always requires from the OIDC provider, /// Scopes the PostIt client always requires from the OIDC provider,
/// regardless of what the user has in their settings file. /// regardless of what the user has in their settings file.
@ -321,11 +357,13 @@ public partial class Settings : ViewModelBase
AuthenticationSettings.DesktopRedirectUri : settings.Authentication.RedirectUri; AuthenticationSettings.DesktopRedirectUri : settings.Authentication.RedirectUri;
if (settings.Authentication.Scopes is null || settings.Authentication.Scopes.Length == 0) if (settings.Authentication.Scopes is null || settings.Authentication.Scopes.Length == 0)
{ {
settings.Authentication.Scopes = AuthenticationSettings.DefaultScopes; this.Authentication.Scopes = AuthenticationSettings.DefaultScopes;
} }
else else
this.Authentication.Scopes = settings.Authentication.Scopes; this.Authentication.Scopes = settings.Authentication.Scopes;
} }
EnsureAuthenticationDefaultsLocked();
} }
// A disk load (or an embedded-resource fallback) is the // A disk load (or an embedded-resource fallback) is the
// baseline, not a user edit. Clear the dirty flag last // baseline, not a user edit. Clear the dirty flag last
@ -406,6 +444,8 @@ public partial class Settings : ViewModelBase
[RelayCommand(CanExecute = nameof(CanSave))] [RelayCommand(CanExecute = nameof(CanSave))]
public void Save() public void Save()
{ {
SetActionStatus("Enregistrement des parametres...", StatusSeverity.Info);
var configDir = Path.Combine( var configDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"PostIt"); "PostIt");
@ -425,10 +465,13 @@ public partial class Settings : ViewModelBase
File.SetUnixFileMode(configPath, File.SetUnixFileMode(configPath,
UnixFileMode.UserRead | UnixFileMode.UserWrite); UnixFileMode.UserRead | UnixFileMode.UserWrite);
IsDirty = false; IsDirty = false;
SetActionStatus("Parametres sauvegardes.", StatusSeverity.Info);
Console.WriteLine($"💾 Settings saved to {configPath}"); Console.WriteLine($"💾 Settings saved to {configPath}");
} }
catch (Exception ex) catch (Exception ex)
{ {
SetActionStatus($"Echec sauvegarde parametres: {ex.Message}", StatusSeverity.Error);
Console.Error.WriteLine($"🩎 Error saving settings to {configPath}: {ex.Message}"); Console.Error.WriteLine($"🩎 Error saving settings to {configPath}: {ex.Message}");
throw; throw;
} }

View file

@ -30,7 +30,7 @@ namespace PostIt.ViewModels;
/// until the Yavsc.Org endpoint exists; the contract there will /// until the Yavsc.Org endpoint exists; the contract there will
/// be <c>POST /api/signature/{devisId}</c> with this same payload. /// be <c>POST /api/signature/{devisId}</c> with this same payload.
/// </summary> /// </summary>
public partial class SignaturePageViewModel : ViewModelBase public partial class SignaturePageViewModel : ViewModelBase, IActionStatusViewModel
{ {
/// <summary> /// <summary>
/// Default capture surface, in DIPs. 3:1 ratio matches a /// Default capture surface, in DIPs. 3:1 ratio matches a
@ -42,6 +42,9 @@ public partial class SignaturePageViewModel : ViewModelBase
[ObservableProperty] [ObservableProperty]
public partial string StatusMessage { get; set; } = "Prêt."; public partial string StatusMessage { get; set; } = "Prêt.";
[ObservableProperty]
public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Prêt.");
[ObservableProperty] [ObservableProperty]
public partial int StrokeCount { get; set; } public partial int StrokeCount { get; set; }
@ -107,7 +110,7 @@ public partial class SignaturePageViewModel : ViewModelBase
private void OnStrokeCompleted(object? sender, SignaturePadData data) private void OnStrokeCompleted(object? sender, SignaturePadData data)
{ {
StatusMessage = $"Trait terminé. {data.StrokeCount} trait(s)."; this.SetInfoStatus($"Trait terminé. {data.StrokeCount} trait(s).");
RefreshCounts(); RefreshCounts();
} }
@ -125,7 +128,7 @@ public partial class SignaturePageViewModel : ViewModelBase
public void Clear() public void Clear()
{ {
_control?.Clear(); _control?.Clear();
StatusMessage = "Effacé."; this.SetInfoStatus("Effacé.");
RefreshCounts(); RefreshCounts();
} }
@ -134,14 +137,14 @@ public partial class SignaturePageViewModel : ViewModelBase
{ {
if (_control is null) if (_control is null)
{ {
StatusMessage = "Contrôle non attaché."; this.SetWarningStatus("Contrôle non attaché.");
return; return;
} }
var data = _control.Snapshot(); var data = _control.Snapshot();
if (data.IsEmpty) if (data.IsEmpty)
{ {
StatusMessage = "Rien à capturer."; this.SetWarningStatus("Rien à capturer.");
return; return;
} }
@ -149,11 +152,11 @@ public partial class SignaturePageViewModel : ViewModelBase
{ {
var path = WriteCapture(data); var path = WriteCapture(data);
LastCapturedPath = path; LastCapturedPath = path;
StatusMessage = $"Capture enregistrée: {path}"; this.SetInfoStatus($"Capture enregistrée: {path}");
} }
catch (Exception ex) catch (Exception ex)
{ {
StatusMessage = $"Erreur: {ex.Message}"; this.SetErrorStatus($"Erreur: {ex.Message}");
} }
await Task.CompletedTask; await Task.CompletedTask;
} }

View file

@ -0,0 +1,35 @@
namespace PostIt.ViewModels;
public enum StatusSeverity
{
Info,
Warning,
Error
}
public sealed class StatusNotice
{
public string Message { get; }
public StatusSeverity Severity { get; }
public string Glyph { get; }
public string Background { get; }
public string BorderBrush { get; }
public string Foreground { get; }
private StatusNotice(string message, StatusSeverity severity)
{
Message = string.IsNullOrWhiteSpace(message) ? "Pret." : message;
Severity = severity;
(Glyph, Background, BorderBrush, Foreground) = severity switch
{
StatusSeverity.Error => ("!", "#FDECEA", "#C62828", "#7F1D1D"),
StatusSeverity.Warning => ("~", "#FFF8E1", "#E6A700", "#7C4A03"),
_ => ("i", "#E8F0FE", "#5B8DEF", "#1E3A8A"),
};
}
public static StatusNotice Info(string message) => new(message, StatusSeverity.Info);
public static StatusNotice Warning(string message) => new(message, StatusSeverity.Warning);
public static StatusNotice Error(string message) => new(message, StatusSeverity.Error);
}

View file

@ -1,6 +1,7 @@
<ContentPage xmlns="https://github.com/avaloniaui" <ContentPage xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:PostIt.ViewModels" xmlns:vm="using:PostIt.ViewModels"
xmlns:postitControls="using:PostIt.Controls"
xmlns:wf="using:Yavsc.Abstract.Workflow" xmlns:wf="using:Yavsc.Abstract.Workflow"
x:Class="PostIt.Views.ActivitiesPage" x:Class="PostIt.Views.ActivitiesPage"
x:DataType="vm:ActivitiesPageViewModel" x:DataType="vm:ActivitiesPageViewModel"
@ -131,16 +132,8 @@
</Grid> </Grid>
<Grid Grid.Row="2" ColumnDefinitions="*,Auto"> <Grid Grid.Row="2" ColumnDefinitions="*,Auto">
<TextBox Grid.Column="0" <postitControls:StatusBar Grid.Column="0"
Text="{Binding StatusMessage}" DataContext="{Binding ActionStatus}" />
IsReadOnly="True"
AcceptsReturn="True"
TextWrapping="Wrap"
BorderThickness="0"
BorderBrush="Transparent"
Padding="0"
Background="Transparent"
VerticalAlignment="Center" />
<ProgressBar Grid.Column="1" Width="120" IsIndeterminate="True" IsVisible="{Binding IsBusy}" /> <ProgressBar Grid.Column="1" Width="120" IsIndeterminate="True" IsVisible="{Binding IsBusy}" />
</Grid> </Grid>
</Grid> </Grid>

View file

@ -3,6 +3,7 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="PostIt.Views.AddCircleMemberDialog" x:Class="PostIt.Views.AddCircleMemberDialog"
xmlns:vm="using:PostIt.ViewModels" xmlns:vm="using:PostIt.ViewModels"
xmlns:postitControls="using:PostIt.Controls"
xmlns:services="using:PostIt.Services" xmlns:services="using:PostIt.Services"
x:DataType="vm:AddCircleMemberDialogViewModel" x:DataType="vm:AddCircleMemberDialogViewModel"
> >
@ -47,8 +48,8 @@
<!-- Action buttons --> <!-- Action buttons -->
<Grid Grid.Row="3" ColumnDefinitions="*,Auto,Auto" Margin="0,8,0,0"> <Grid Grid.Row="3" ColumnDefinitions="*,Auto,Auto" Margin="0,8,0,0">
<TextBlock Grid.Column="0" Text="{Binding StatusMessage}" <postitControls:StatusBar Grid.Column="0"
VerticalAlignment="Center"/> DataContext="{Binding ActionStatus}" />
<Button Grid.Column="1" Content="Ajouter" <Button Grid.Column="1" Content="Ajouter"
x:Name="AddButton" x:Name="AddButton"
Command="{Binding AddAsync}" Command="{Binding AddAsync}"

View file

@ -1,10 +1,8 @@
using Avalonia.Markup.Xaml; using Avalonia.Markup.Xaml;
using Avalonia.Interactivity;
using Avalonia.VisualTree; using Avalonia.VisualTree;
using PostIt.Services; using PostIt.Services;
using PostIt.ViewModels; using PostIt.ViewModels;
using System.Threading.Tasks;
namespace PostIt.Views; namespace PostIt.Views;
@ -41,10 +39,4 @@ public partial class AddCircleMemberDialog : Avalonia.Controls.ContentPage
/// </summary> /// </summary>
public AddCircleMemberDialogViewModel? ViewModel public AddCircleMemberDialogViewModel? ViewModel
=> DataContext as AddCircleMemberDialogViewModel; => DataContext as AddCircleMemberDialogViewModel;
private async Task OnCloseClicked(object? sender, RoutedEventArgs e)
{
App app = App.Current! as App;
await app!.GoBackAsync();
}
} }

View file

@ -1,51 +1,89 @@
<ContentPage xmlns="https://github.com/avaloniaui" <ContentPage xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:PostIt.ViewModels" xmlns:vm="using:PostIt.ViewModels"
xmlns:postitControls="using:PostIt.Controls"
x:Class="PostIt.Views.BillingQueriesPage" x:Class="PostIt.Views.BillingQueriesPage"
x:DataType="vm:BillingQueriesPageViewModel" x:DataType="vm:BillingQueriesPageViewModel"
Header="Commandes billing"> Header="Commandes billing">
<Grid RowDefinitions="Auto,Auto,*,Auto" Margin="12"> <Grid RowDefinitions="Auto,Auto,Auto,*,Auto" Margin="12">
<StackPanel Grid.Row="0" Spacing="2"> <StackPanel Grid.Row="0" Spacing="3">
<TextBlock Text="{Binding Title}" FontSize="18" FontWeight="Bold" /> <TextBlock Text="{Binding Title}" FontSize="20" FontWeight="Bold" />
<TextBlock Text="{Binding ContextLabel}" Opacity="0.75" /> <TextBlock Text="{Binding ContextLabel}" Opacity="0.75" />
</StackPanel> </StackPanel>
<StackPanel Grid.Row="1" Orientation="Horizontal" Spacing="8" Margin="0,12,0,12"> <Grid Grid.Row="1" Margin="0,10,0,0" ColumnDefinitions="Auto,8,Auto,8,*">
<Button Content="Rafraîchir" Command="{Binding RefreshCommand}" /> <Border Grid.Column="0" Background="#EAF3FF" BorderBrush="#2A5EA8" BorderThickness="1" CornerRadius="6" Padding="8,3">
<Button Content="Ouvrir la commande" <TextBlock Text="{Binding IsReadOnly, StringFormat='Lecture seule : {0}'}" FontSize="11" />
</Border>
<Border Grid.Column="2" Background="#F2F7F2" BorderBrush="#2F6D2F" BorderThickness="1" CornerRadius="6" Padding="8,3">
<TextBlock Text="{Binding OngoingOnly, StringFormat='En cours uniquement : {0}'}" FontSize="11" />
</Border>
<TextBlock Grid.Column="4"
HorizontalAlignment="Right"
VerticalAlignment="Center"
Text="{Binding Queries.Count, StringFormat='Résultats : {0}'}"
Opacity="0.7" />
</Grid>
<Grid Grid.Row="2" ColumnDefinitions="Auto,8,Auto,*" Margin="0,12,0,12">
<Button Grid.Column="0" Content="Rafraîchir" Command="{Binding RefreshCommand}" />
<Button Content="Voir le detail"
Grid.Column="2"
Command="{Binding OpenSelectedQueryCommand}" Command="{Binding OpenSelectedQueryCommand}"
IsVisible="{Binding CanOpenDetails}" /> IsVisible="{Binding CanOpenDetails}" />
</StackPanel> </Grid>
<ListBox Grid.Row="2" ItemsSource="{Binding Queries}" SelectedItem="{Binding SelectedQuery, Mode=TwoWay}"> <ListBox Grid.Row="3"
ItemsSource="{Binding Queries}"
SelectedItem="{Binding SelectedQuery, Mode=TwoWay}">
<ListBox.ItemTemplate> <ListBox.ItemTemplate>
<DataTemplate x:DataType="vm:BillingQueryDisplayItem"> <DataTemplate x:DataType="vm:BillingQueryDisplayItem">
<Border BorderThickness="0,0,0,1" BorderBrush="#22000000" Padding="0,0,0,10" Margin="0,0,0,10"> <Border BorderThickness="1"
<StackPanel Spacing="3"> BorderBrush="#22000000"
<TextBlock Text="{Binding Description}" FontWeight="Bold" /> CornerRadius="8"
<TextBlock Text="{Binding Summary}" TextWrapping="Wrap" FontSize="12" Opacity="0.8" /> Padding="10"
<StackPanel Orientation="Horizontal" Spacing="8"> Margin="0,0,0,8">
<TextBlock Text="{Binding EventDateLabel}" FontSize="11" Opacity="0.7" /> <Grid RowDefinitions="Auto,Auto,Auto" ColumnDefinitions="*,Auto">
<TextBlock Text="{Binding StatusLabel}" FontSize="11" Opacity="0.7" /> <TextBlock Grid.Row="0"
<TextBlock Text="{Binding BillingCode}" FontSize="11" Opacity="0.6" /> Grid.Column="0"
</StackPanel> Text="{Binding Description}"
</StackPanel> FontWeight="Bold"
TextWrapping="Wrap" />
<TextBlock Grid.Row="0"
Grid.Column="1"
Text="{Binding StatusLabel}"
FontSize="11"
Opacity="0.75"
HorizontalAlignment="Right" />
<TextBlock Grid.Row="1"
Grid.ColumnSpan="2"
Margin="0,4,0,0"
Text="{Binding Summary}"
TextWrapping="Wrap"
FontSize="12"
Opacity="0.85" />
<Grid Grid.Row="2" Grid.ColumnSpan="2" ColumnDefinitions="*,Auto" Margin="0,8,0,0">
<TextBlock Grid.Column="0"
Text="{Binding EventDateLabel, StringFormat='Date : {0}'}"
FontSize="11"
Opacity="0.7" />
<TextBlock Grid.Column="1"
Text="{Binding BillingCode, StringFormat='Code : {0}'}"
FontSize="11"
Opacity="0.65"
HorizontalAlignment="Right" />
</Grid>
</Grid>
</Border> </Border>
</DataTemplate> </DataTemplate>
</ListBox.ItemTemplate> </ListBox.ItemTemplate>
</ListBox> </ListBox>
<Grid Grid.Row="3" ColumnDefinitions="*,Auto" Margin="0,12,0,0"> <Grid Grid.Row="4" ColumnDefinitions="*,Auto" Margin="0,12,0,0">
<TextBox Grid.Column="0" <postitControls:StatusBar Grid.Column="0"
Text="{Binding StatusMessage}" DataContext="{Binding ActionStatus}" />
IsReadOnly="True"
AcceptsReturn="True"
TextWrapping="Wrap"
BorderThickness="0"
BorderBrush="Transparent"
Padding="0"
Background="Transparent"
VerticalAlignment="Center" />
<ProgressBar Grid.Column="1" Width="120" IsIndeterminate="True" IsVisible="{Binding IsBusy}" /> <ProgressBar Grid.Column="1" Width="120" IsIndeterminate="True" IsVisible="{Binding IsBusy}" />
</Grid> </Grid>
</Grid> </Grid>

View file

@ -0,0 +1,131 @@
<ContentPage xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:PostIt.ViewModels"
xmlns:postitControls="using:PostIt.Controls"
x:Class="PostIt.Views.BillingQueryDetailsPage"
x:DataType="vm:BillingQueryDetailsPageViewModel"
Header="Detail commande">
<Grid RowDefinitions="Auto,Auto,*,Auto" Margin="12">
<StackPanel Grid.Row="0" Spacing="4">
<TextBlock Text="{Binding Title}"
FontSize="20"
FontWeight="Bold"
Foreground="{Binding TitleForeground}" />
<TextBlock Text="{Binding ContextLabel}" Opacity="0.75" />
</StackPanel>
<Grid Grid.Row="1" Margin="0,10,0,0" ColumnDefinitions="Auto,8,Auto,*">
<Button Grid.Column="0"
Content="Retour"
Command="{Binding BackCommand}" />
<Button Grid.Column="2"
Content="Ouvrir en edition"
Command="{Binding OpenEditorCommand}"
IsVisible="{Binding CanEdit}" />
</Grid>
<ScrollViewer Grid.Row="2" Margin="0,12,0,12">
<StackPanel Spacing="10">
<Border BorderThickness="1"
BorderBrush="#22000000"
CornerRadius="8"
Padding="10">
<Grid ColumnDefinitions="Auto,12,*" RowDefinitions="Auto,Auto" RowSpacing="8">
<TextBlock Grid.Row="0" Grid.Column="0" Text="Statut" FontWeight="SemiBold" />
<Border Grid.Row="0"
Grid.Column="2"
Background="{Binding StatusBadgeBackground}"
BorderBrush="{Binding StatusBadgeBorder}"
BorderThickness="1"
CornerRadius="6"
Padding="8,3"
HorizontalAlignment="Left">
<StackPanel Orientation="Horizontal" Spacing="6">
<TextBlock Text="{Binding StatusGlyph}"
Foreground="{Binding StatusBadgeForeground}"
FontWeight="Bold" />
<TextBlock Text="{Binding StatusLabel}"
Foreground="{Binding StatusBadgeForeground}"
FontWeight="SemiBold" />
</StackPanel>
</Border>
<TextBlock Grid.Row="1" Grid.Column="0" Text="Date" FontWeight="SemiBold" />
<TextBlock Grid.Row="1" Grid.Column="2" Text="{Binding EventDateLabel}" />
</Grid>
</Border>
<Border BorderThickness="1"
BorderBrush="#22000000"
CornerRadius="8"
Padding="10">
<Grid ColumnDefinitions="Auto,12,*" RowDefinitions="Auto,Auto,Auto,Auto" RowSpacing="8">
<TextBlock Grid.Row="0" Grid.Column="0" Text="Description" FontWeight="SemiBold" />
<TextBlock Grid.Row="0" Grid.Column="2" Text="{Binding Description}" TextWrapping="Wrap" />
<TextBlock Grid.Row="1" Grid.Column="0" Text="Motif" FontWeight="SemiBold" />
<TextBlock Grid.Row="1" Grid.Column="2" Text="{Binding Reason}" TextWrapping="Wrap" />
<TextBlock Grid.Row="2" Grid.Column="0" Text="Infos" FontWeight="SemiBold" />
<TextBlock Grid.Row="2" Grid.Column="2" Text="{Binding AdditionalInfo}" TextWrapping="Wrap" />
<TextBlock Grid.Row="3" Grid.Column="0" Text="Consentement" FontWeight="SemiBold" />
<TextBlock Grid.Row="3" Grid.Column="2" Text="{Binding ConsentLabel}" />
</Grid>
</Border>
<Expander Header="Metadonnees techniques"
IsExpanded="False">
<Border BorderThickness="1"
BorderBrush="#22000000"
CornerRadius="8"
Padding="10"
Margin="0,6,0,0">
<Grid ColumnDefinitions="Auto,12,*" RowDefinitions="Auto,Auto,Auto,Auto,Auto" RowSpacing="8">
<TextBlock Grid.Row="0" Grid.Column="0" Text="Code" FontWeight="SemiBold" />
<TextBlock Grid.Row="0"
Grid.Column="2"
Text="{Binding BillingCode}"
FontFamily="Consolas, Courier New, monospace" />
<TextBlock Grid.Row="1" Grid.Column="0" Text="Client" FontWeight="SemiBold" />
<TextBlock Grid.Row="1"
Grid.Column="2"
Text="{Binding ClientId}"
FontFamily="Consolas, Courier New, monospace" />
<TextBlock Grid.Row="2" Grid.Column="0" Text="Provision" FontWeight="SemiBold" />
<TextBlock Grid.Row="2"
Grid.Column="2"
Text="{Binding ProvisionalLabel}"
FontFamily="Consolas, Courier New, monospace" />
<TextBlock Grid.Row="3" Grid.Column="0" Text="Lieu" FontWeight="SemiBold" />
<TextBlock Grid.Row="3"
Grid.Column="2"
Text="{Binding LocationLabel}"
TextWrapping="Wrap"
FontFamily="Consolas, Courier New, monospace" />
<TextBlock Grid.Row="4" Grid.Column="0" Text="Prestations" FontWeight="SemiBold" />
<TextBlock Grid.Row="4"
Grid.Column="2"
Text="{Binding PrestationsLabel}"
TextWrapping="Wrap"
FontFamily="Consolas, Courier New, monospace" />
</Grid>
</Border>
</Expander>
</StackPanel>
</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"
IsVisible="{Binding IsBusy}" />
</Grid>
</Grid>
</ContentPage>

View file

@ -0,0 +1,17 @@
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace PostIt.Views;
public partial class BillingQueryDetailsPage : ContentPage
{
public BillingQueryDetailsPage()
{
InitializeComponent();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}

View file

@ -1,6 +1,7 @@
<ContentPage <ContentPage
xmlns="https://github.com/avaloniaui" xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:postitControls="using:PostIt.Controls"
x:Class="PostIt.Views.CirclesPage" x:Class="PostIt.Views.CirclesPage"
xmlns:vm="using:PostIt.ViewModels" xmlns:vm="using:PostIt.ViewModels"
xmlns:dtos="using:Yavsc.Api.Client.Dtos" xmlns:dtos="using:Yavsc.Api.Client.Dtos"
@ -101,8 +102,8 @@
<!-- Status bar --> <!-- Status bar -->
<Grid Grid.Row="2" ColumnDefinitions="*,Auto" Margin="12,0,12,12"> <Grid Grid.Row="2" ColumnDefinitions="*,Auto" Margin="12,0,12,12">
<TextBlock Grid.Column="0" Text="{Binding StatusMessage}" <postitControls:StatusBar Grid.Column="0"
VerticalAlignment="Center"/> DataContext="{Binding ActionStatus}" />
<ProgressBar Grid.Column="1" IsIndeterminate="True" <ProgressBar Grid.Column="1" IsIndeterminate="True"
IsVisible="{Binding IsBusy}" IsVisible="{Binding IsBusy}"
Width="120"/> Width="120"/>

View file

@ -1,6 +1,7 @@
<ContentPage xmlns="https://github.com/avaloniaui" <ContentPage xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:PostIt.ViewModels" xmlns:vm="using:PostIt.ViewModels"
xmlns:postitControls="using:PostIt.Controls"
xmlns:wf="using:Yavsc.Abstract.Workflow" xmlns:wf="using:Yavsc.Abstract.Workflow"
x:Class="PostIt.Views.CommandFormsPage" x:Class="PostIt.Views.CommandFormsPage"
x:DataType="vm:CommandFormsPageViewModel" x:DataType="vm:CommandFormsPageViewModel"
@ -41,16 +42,8 @@
<Button Grid.Column="4" <Button Grid.Column="4"
Content="Demandes en cours (lecture seule)" Content="Demandes en cours (lecture seule)"
Command="{Binding OpenOngoingQueriesCommand}" /> Command="{Binding OpenOngoingQueriesCommand}" />
<TextBox Grid.Column="6" <postitControls:StatusBar Grid.Column="6"
Text="{Binding StatusMessage}" DataContext="{Binding ActionStatus}" />
IsReadOnly="True"
AcceptsReturn="True"
TextWrapping="Wrap"
BorderThickness="0"
BorderBrush="Transparent"
Padding="0"
Background="Transparent"
VerticalAlignment="Center" />
</Grid> </Grid>
</Grid> </Grid>
</ContentPage> </ContentPage>

View file

@ -3,6 +3,7 @@
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:cvm="using:PostIt.ViewModels.Commands" xmlns:cvm="using:PostIt.ViewModels.Commands"
xmlns:postitControls="using:PostIt.Controls"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450" mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
x:Class="PostIt.Views.Commands.BrushPage" x:Class="PostIt.Views.Commands.BrushPage"
@ -93,16 +94,8 @@
Content="{Binding SubmitLabel}" Content="{Binding SubmitLabel}"
Command="{Binding SubmitCommand}" Command="{Binding SubmitCommand}"
IsEnabled="{Binding IsSupported}" /> IsEnabled="{Binding IsSupported}" />
<TextBox Grid.Column="2" <postitControls:StatusBar Grid.Column="2"
Text="{Binding StatusMessage}" DataContext="{Binding ActionStatus}" />
IsReadOnly="True"
AcceptsReturn="True"
TextWrapping="Wrap"
BorderThickness="0"
BorderBrush="Transparent"
Padding="0"
Background="Transparent"
VerticalAlignment="Center" />
<ProgressBar Grid.Column="3" <ProgressBar Grid.Column="3"
Width="120" Width="120"
IsIndeterminate="True" IsIndeterminate="True"

View file

@ -1,11 +1,13 @@
<ContentPage xmlns="https://github.com/avaloniaui" <ContentPage xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cvm="using:PostIt.ViewModels.Commands" xmlns:cvm="using:PostIt.ViewModels.Commands"
xmlns:mapsui="using:Mapsui.UI.Avalonia"
xmlns:postitControls="using:PostIt.Controls"
x:Class="PostIt.Views.Commands.RdvPage" x:Class="PostIt.Views.Commands.RdvPage"
x:DataType="cvm:RdvViewModel" x:DataType="cvm:RdvViewModel"
Header="Commande billing"> Header="Commande billing">
<ScrollViewer> <ScrollViewer>
<Grid RowDefinitions="Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto" ColumnDefinitions="Auto,*" Margin="12"> <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" <TextBlock Grid.Row="0" Grid.ColumnSpan="2"
Text="{Binding Title}" Text="{Binding Title}"
FontSize="18" FontSize="18"
@ -24,7 +26,7 @@
<TextBox Grid.Row="3" Grid.Column="1" Text="{Binding ActivityLabel}" IsReadOnly="True" Margin="0,0,0,8" /> <TextBox Grid.Row="3" Grid.Column="1" Text="{Binding ActivityLabel}" IsReadOnly="True" Margin="0,0,0,8" />
<TextBlock Grid.Row="4" Text="Date" VerticalAlignment="Center" Margin="0,0,12,8" /> <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 EventDate, Mode=TwoWay}" Margin="0,0,0,8" /> <DatePicker Grid.Row="4" Grid.Column="1" DayFormat="ddd dd" SelectedDate="{Binding EventDateSelection, Mode=TwoWay}" Margin="0,0,0,8" />
<TextBlock Grid.Row="5" <TextBlock Grid.Row="5"
Text="Motif" Text="Motif"
@ -38,49 +40,81 @@
<TextBlock Grid.Row="6" Text="Adresse" VerticalAlignment="Center" Margin="0,0,12,8" /> <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" /> <TextBox Grid.Row="6" Grid.Column="1" Text="{Binding Address, Mode=TwoWay}" Margin="0,0,0,8" />
<Button Grid.Row="7" <Grid Grid.Row="7"
Grid.ColumnSpan="2" x:Name="SuggestedAddressPanel"
HorizontalAlignment="Left" Grid.ColumnSpan="2"
Margin="0,0,0,8" ColumnDefinitions="*,12,Auto,12,Auto"
Content="Utiliser ma position" Margin="0,0,0,8"
Command="{Binding UseCurrentLocationCommand}" /> 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>
<TextBlock Grid.Row="8" Text="Latitude" VerticalAlignment="Center" Margin="0,0,12,8" /> <Grid Grid.Row="8"
<TextBox Grid.Row="8" Grid.Column="1" Text="{Binding Latitude, Mode=TwoWay}" PlaceholderText="Optionnel" Margin="0,0,0,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="Longitude" VerticalAlignment="Center" Margin="0,0,12,8" /> <TextBlock Grid.Row="9" Text="Latitude" VerticalAlignment="Center" Margin="0,0,12,8" />
<TextBox Grid.Row="9" Grid.Column="1" Text="{Binding Longitude, Mode=TwoWay}" PlaceholderText="Optionnel" Margin="0,0,0,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="12" <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" Text="Informations"
VerticalAlignment="Center" VerticalAlignment="Center"
Margin="0,0,12,8" /> Margin="0,0,12,8" />
<TextBox Grid.Row="12" <TextBox Grid.Row="13"
Grid.Column="1" Grid.Column="1"
Text="{Binding AdditionalInfo, Mode=TwoWay}" Text="{Binding AdditionalInfo, Mode=TwoWay}"
Margin="0,0,0,8" /> Margin="0,0,0,8" />
<CheckBox Grid.Row="13" Grid.ColumnSpan="2" <CheckBox Grid.Row="14" Grid.ColumnSpan="2"
Content="Je consens à la création de cette commande" Content="Je consens à la création de cette commande"
IsChecked="{Binding Consent, Mode=TwoWay}" IsChecked="{Binding Consent, Mode=TwoWay}"
Margin="0,4,0,12" /> Margin="0,4,0,12" />
<Grid Grid.Row="14" Grid.ColumnSpan="2" ColumnDefinitions="Auto,12,*,Auto"> <Grid Grid.Row="15" Grid.ColumnSpan="2" ColumnDefinitions="Auto,12,*,Auto">
<Button Grid.Column="0" <Button Grid.Column="0"
Content="{Binding SubmitLabel}" Content="{Binding SubmitLabel}"
Command="{Binding SubmitCommand}" Command="{Binding SubmitCommand}"
IsEnabled="{Binding IsSupported}" /> IsEnabled="{Binding IsSupported}" />
<TextBox Grid.Column="2" <postitControls:StatusBar Grid.Column="2"
Text="{Binding StatusMessage}" DataContext="{Binding ActionStatus}" />
IsReadOnly="True"
AcceptsReturn="True"
TextWrapping="Wrap"
BorderThickness="0"
BorderBrush="Transparent"
Padding="0"
Background="Transparent"
VerticalAlignment="Center" />
<ProgressBar Grid.Column="3" <ProgressBar Grid.Column="3"
Width="120" Width="120"
IsIndeterminate="True" IsIndeterminate="True"

View file

@ -1,17 +1,236 @@
using System;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Markup.Xaml; 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; namespace PostIt.Views.Commands;
public partial class RdvPage : ContentPage 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() public RdvPage()
: this(null)
{ {
}
public RdvPage(IReverseGeocodingService? reverseGeocodingService)
{
_reverseGeocodingService = reverseGeocodingService ?? new NominatimReverseGeocodingService();
InitializeComponent(); InitializeComponent();
InitializeMap();
} }
private void InitializeComponent() private void InitializeComponent()
{ {
AvaloniaXamlLoader.Load(this); 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)
{
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;
}
} }

View file

@ -3,6 +3,7 @@
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="using:PostIt.ViewModels" xmlns:vm="using:PostIt.ViewModels"
xmlns:postitControls="using:PostIt.Controls"
xmlns:models="using:Yavsc.Blogspot" xmlns:models="using:Yavsc.Blogspot"
xmlns:views="using:PostIt.Views" xmlns:views="using:PostIt.Views"
xmlns:AvaloniaEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:AvaloniaEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
@ -104,7 +105,8 @@
VerticalAlignment="Stretch"> VerticalAlignment="Stretch">
</TextBox> </TextBox>
<TextBlock Grid.Row="3" Text="{Binding StatusMessage}" Foreground="Gray" /> <postitControls:StatusBar Grid.Row="3"
DataContext="{Binding ActionStatus}" />
</Grid> </Grid>
</Border> </Border>

View file

@ -3,6 +3,7 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="PostIt.Views.PostAclDialog" x:Class="PostIt.Views.PostAclDialog"
xmlns:vm="using:PostIt.ViewModels" xmlns:vm="using:PostIt.ViewModels"
xmlns:postitControls="using:PostIt.Controls"
xmlns:dtos="using:Yavsc.Api.Client.Dtos" xmlns:dtos="using:Yavsc.Api.Client.Dtos"
x:DataType="vm:PostAclDialogViewModel" x:DataType="vm:PostAclDialogViewModel"
> >
@ -53,8 +54,8 @@
<!-- Status bar --> <!-- Status bar -->
<Grid Grid.Row="3" ColumnDefinitions="*,Auto"> <Grid Grid.Row="3" ColumnDefinitions="*,Auto">
<TextBlock Grid.Column="0" Text="{Binding StatusMessage}" <postitControls:StatusBar Grid.Column="0"
VerticalAlignment="Center"/> DataContext="{Binding ActionStatus}" />
<ProgressBar Grid.Column="1" IsIndeterminate="True" <ProgressBar Grid.Column="1" IsIndeterminate="True"
IsVisible="{Binding IsBusy}" IsVisible="{Binding IsBusy}"
Width="120"/> Width="120"/>

View file

@ -2,6 +2,7 @@
xmlns="https://github.com/avaloniaui" xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="cl:avalonia.Controls" xmlns:controls="cl:avalonia.Controls"
xmlns:postitControls="using:PostIt.Controls"
x:Class="PostIt.Views.SettingsPage" x:Class="PostIt.Views.SettingsPage"
xmlns:vm="using:PostIt.ViewModels" xmlns:vm="using:PostIt.ViewModels"
x:DataType="vm:Settings" x:DataType="vm:Settings"
@ -51,9 +52,7 @@
Opacity="0.8" Opacity="0.8"
TextWrapping="Wrap" /> TextWrapping="Wrap" />
<TextBlock x:Name="AvatarUploadStatusText" <postitControls:StatusBar DataContext="{Binding ActionStatus}"/>
Text=""
TextWrapping="Wrap" />
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right"> <StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Button x:Name="ChooseAvatarButton" <Button x:Name="ChooseAvatarButton"
@ -61,16 +60,11 @@
Click="ChooseAvatar_Click" Click="ChooseAvatar_Click"
Margin="0,0,8,0"/> Margin="0,0,8,0"/>
<!-- Sauver: bound to the Save RelayCommand on the Settings <!-- Sauver: bind to the RelayCommand-generated property
VM. The source generator emits an ICommand property whose (SaveCommand). IsEnabled tracks IsDirty so the button
name matches the source method exactly (no "Command" auto-disables when there's nothing to persist. -->
suffix is added), so we bind {Binding Save} here. See
AGENTS.md "Avalonia + CommunityToolkit.Mvvm : conventions
de binding pour [RelayCommand]" for the full rationale.
IsEnabled tracks IsDirty so the button auto-disables
when there's nothing to persist. -->
<Button Content="Sauver" <Button Content="Sauver"
Command="{Binding Save}" Command="{Binding SaveCommand}"
IsEnabled="{Binding IsDirty}"/> IsEnabled="{Binding IsDirty}"/>
</StackPanel> </StackPanel>
</StackPanel> </StackPanel>

View file

@ -6,10 +6,10 @@ using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.Platform.Storage; using Avalonia.Platform.Storage;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using PostIt.Services; using PostIt.Services;
using PostIt.ViewModels;
namespace PostIt.Views; namespace PostIt.Views;
public partial class SettingsPage: ContentPage public partial class SettingsPage: ContentPage
@ -28,12 +28,12 @@ public partial class SettingsPage: ContentPage
{ {
var statusVersion = Interlocked.Increment(ref _avatarStatusVersion); var statusVersion = Interlocked.Increment(ref _avatarStatusVersion);
ChooseAvatarButton.IsEnabled = false; ChooseAvatarButton.IsEnabled = false;
SetAvatarStatus("Sélection d'un fichier avatar...", Brushes.Gray); SetAvatarStatus("Selection d'un fichier avatar...", StatusSeverity.Info);
var topLevel = TopLevel.GetTopLevel(this); var topLevel = TopLevel.GetTopLevel(this);
if (topLevel is null) if (topLevel is null)
{ {
SetAvatarStatus("Impossible d'accéder à la fenêtre active.", Brushes.IndianRed); SetAvatarStatus("Impossible d'acceder a la fenetre active.", StatusSeverity.Error);
ChooseAvatarButton.IsEnabled = true; ChooseAvatarButton.IsEnabled = true;
return; return;
} }
@ -54,27 +54,28 @@ public partial class SettingsPage: ContentPage
var file = files.FirstOrDefault(); var file = files.FirstOrDefault();
if (file is null) if (file is null)
{ {
SetAvatarStatus("Upload annulé.", Brushes.Gray); SetAvatarStatus("Upload annule.", StatusSeverity.Warning);
ChooseAvatarButton.IsEnabled = true; ChooseAvatarButton.IsEnabled = true;
return; return;
} }
try try
{ {
SetAvatarStatus("Upload avatar en cours...", Brushes.Gray); SetAvatarStatus("Upload avatar en cours...", StatusSeverity.Info);
await using var stream = await file.OpenReadAsync(); await using var stream = await file.OpenReadAsync();
var api = ((App)App.Current!).ServiceProvider!.GetRequiredService<YavscApiClient>(); var api = ((App)App.Current!).ServiceProvider!.GetRequiredService<YavscApiClient>();
var message = await api.SetAvatarAsync(stream, file.Name, GetMimeType(file.Name)); var message = await api.SetAvatarAsync(stream, file.Name, GetMimeType(file.Name));
SetAvatarStatus(string.IsNullOrWhiteSpace(message) SetAvatarStatus(string.IsNullOrWhiteSpace(message)
? "Avatar mis à jour." ? "Avatar mis a jour."
: message, Brushes.ForestGreen); : message,
StatusSeverity.Info);
_ = ClearSuccessStatusLaterAsync(statusVersion); _ = ClearSuccessStatusLaterAsync(statusVersion);
} }
catch (Exception ex) catch (Exception ex)
{ {
SetAvatarStatus($"Échec upload avatar: {ex.Message}", Brushes.IndianRed); SetAvatarStatus($"Echec upload avatar: {ex.Message}", StatusSeverity.Error);
Console.Error.WriteLine($"🩎 Avatar upload failed: {ex.Message}"); Console.Error.WriteLine($"🩎 Avatar upload failed: {ex.Message}");
} }
finally finally
@ -89,16 +90,15 @@ public partial class SettingsPage: ContentPage
if (statusVersion != _avatarStatusVersion) if (statusVersion != _avatarStatusVersion)
return; return;
if (AvatarUploadStatusText.Foreground == Brushes.ForestGreen) SetAvatarStatus($"Avatar pret. Formats supportes: {AcceptedAvatarFormats}. Taille max: {MaxAvatarSizeMegabytes} MB.", StatusSeverity.Info);
{
SetAvatarStatus($"Avatar prêt. Formats supportés: {AcceptedAvatarFormats}. Taille max: {MaxAvatarSizeMegabytes} MB.", Brushes.Gray);
}
} }
private void SetAvatarStatus(string message, IBrush color) private void SetAvatarStatus(string message, StatusSeverity severity)
{ {
AvatarUploadStatusText.Foreground = color; if (DataContext is Settings settings)
AvatarUploadStatusText.Text = message; {
settings.SetActionStatus(message, severity);
}
} }
private static string GetMimeType(string fileName) private static string GetMimeType(string fileName)

View file

@ -3,6 +3,7 @@
xmlns:d="http://github.com/avaloniaui/avalonia" xmlns:d="http://github.com/avaloniaui/avalonia"
xmlns:vm="using:PostIt.ViewModels" xmlns:vm="using:PostIt.ViewModels"
xmlns:controls="using:PostIt.Controls" xmlns:controls="using:PostIt.Controls"
xmlns:postitControls="using:PostIt.Controls"
x:Class="PostIt.Views.SignaturePage" x:Class="PostIt.Views.SignaturePage"
x:DataType="vm:SignaturePageViewModel" x:DataType="vm:SignaturePageViewModel"
HorizontalAlignment="Stretch" HorizontalAlignment="Stretch"
@ -59,10 +60,8 @@
<Button Content="Capturer" Command="{Binding CaptureAsync}" /> <Button Content="Capturer" Command="{Binding CaptureAsync}" />
</StackPanel> </StackPanel>
<TextBlock Grid.Row="3" <postitControls:StatusBar Grid.Row="3"
Text="{Binding StatusMessage}" DataContext="{Binding ActionStatus}" />
Foreground="Gray"
TextWrapping="Wrap" />
<TextBlock Grid.Row="4" <TextBlock Grid.Row="4"
FontSize="11" FontSize="11"

View file

@ -5,7 +5,7 @@
}, },
"RedirectUri": "postit://callback", "RedirectUri": "postit://callback",
"DarkMode": false, "DarkMode": false,
"ApiUrl": "https://blogs.pschneider.fr/api/v1/", "ApiUrl": "https://api.pschneider.fr/api/v1/",
"Scopes": [ "Scopes": [
"openid", "openid",
"profile", "profile",

View file

@ -5,7 +5,7 @@
}, },
"RedirectUri": "postit://callback", "RedirectUri": "postit://callback",
"DarkMode": true, "DarkMode": true,
"ApiUrl": "https://blogs.pschneider.fr/api/v1/", "ApiUrl": "https://api.pschneider.fr/api/v1/",
"Scopes": [ "Scopes": [
"openid", "openid",
"profile", "profile",

View file

@ -1,3 +1,5 @@
#nullable enable annotations
using Yavsc.Services; using Yavsc.Services;
namespace Yavsc.Billing namespace Yavsc.Billing

View file

@ -1,3 +1,5 @@
#nullable enable annotations
namespace Yavsc.Blogspot; namespace Yavsc.Blogspot;
/// <summary> /// <summary>

View file

@ -1,3 +1,5 @@
#nullable enable annotations
using Yavsc.Abstract.Identity.Security; using Yavsc.Abstract.Identity.Security;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;

View file

@ -1,3 +1,5 @@
#nullable enable annotations

View file

@ -1,3 +1,5 @@
#nullable enable annotations
namespace Yavsc.Abstract.Chat namespace Yavsc.Abstract.Chat
{ {
public static class ChatHubConstants public static class ChatHubConstants

View file

@ -1,3 +1,5 @@
#nullable enable annotations
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
namespace Yavsc.Abstract.Chat namespace Yavsc.Abstract.Chat

View file

@ -1,4 +1,6 @@
using System.Text; #nullable enable annotations
using System.Text;
using Yavsc.ViewModels.UserFiles; using Yavsc.ViewModels.UserFiles;
namespace Yavsc.Server.Helpers namespace Yavsc.Server.Helpers

View file

@ -1,3 +1,5 @@
#nullable enable annotations
namespace Yavsc.Abstract.Helpers namespace Yavsc.Abstract.Helpers
{ {
public enum ErrorCode { public enum ErrorCode {

View file

@ -1,3 +1,5 @@
#nullable enable annotations
using Yavsc.Server.Helpers; using Yavsc.Server.Helpers;
namespace Yavsc.ViewModels.UserFiles namespace Yavsc.ViewModels.UserFiles

View file

@ -1,3 +1,5 @@
#nullable enable annotations
// //
// GDate.cs // GDate.cs
// //

View file

@ -1,3 +1,5 @@
#nullable enable annotations
// //
// MessageWithPayloadResponse.cs // MessageWithPayloadResponse.cs
// //

View file

@ -1,3 +1,5 @@
#nullable enable annotations
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using Yavsc.Attributes.Validation; using Yavsc.Attributes.Validation;

View file

@ -1,4 +1,6 @@
namespace Yavsc.Abstract.Identity #nullable enable annotations
namespace Yavsc.Abstract.Identity
{ {
public interface IApplicationUser public interface IApplicationUser
{ {

View file

@ -1,3 +1,5 @@
#nullable enable annotations
namespace Yavsc.Abstract.Identity namespace Yavsc.Abstract.Identity
{ {
/// <summary> /// <summary>

View file

@ -1,4 +1,6 @@
using Yavsc.Abstract.Identity; #nullable enable annotations
using Yavsc.Abstract.Identity;
namespace Yavsc.Interfaces namespace Yavsc.Interfaces
{ {

View file

@ -1,3 +1,5 @@
#nullable enable annotations
using Yavsc.Interfaces; using Yavsc.Interfaces;

View file

@ -1,3 +1,5 @@
#nullable enable annotations
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;

View file

@ -1,3 +1,5 @@
#nullable enable annotations
// //
// BookQueryEvent.cs // BookQueryEvent.cs
// //

View file

@ -1,3 +1,5 @@
#nullable enable annotations
using Yavsc.Abstract.Identity; using Yavsc.Abstract.Identity;
using Yavsc.Models.Relationship; using Yavsc.Models.Relationship;

View file

@ -1,4 +1,6 @@
// Copyright (C) 2016 Paul Schneider #nullable enable annotations
// Copyright (C) 2016 Paul Schneider
// //
// This file is part of yavsc. // This file is part of yavsc.
// //

View file

@ -1,3 +1,5 @@
#nullable enable annotations
namespace Yavsc.Workflow namespace Yavsc.Workflow
{ {
public interface IPerformerProfile public interface IPerformerProfile

View file

@ -1,3 +1,5 @@
#nullable enable annotations
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;

View file

@ -19,19 +19,29 @@ public sealed class ActivityApiClient
private const string PathPrefix = "activity"; private const string PathPrefix = "activity";
private readonly IYavscApiClient _api; private readonly IYavscApiClient _api;
private readonly Uri _baseAddress; private readonly Func<string> _businessBaseAddress;
private readonly Uri _avatarBaseAddress; private readonly Func<string?> _avatarBaseAddress;
public ActivityApiClient(IYavscApiClient api, string businessBaseAddress, string? avatarBaseAddress = null) public ActivityApiClient(IYavscApiClient api, string businessBaseAddress, string? avatarBaseAddress = null)
: this(
api,
() => businessBaseAddress,
() => avatarBaseAddress)
{
}
public ActivityApiClient(
IYavscApiClient api,
Func<string> businessBaseAddress,
Func<string?>? avatarBaseAddress = null)
{ {
_api = api ?? throw new ArgumentNullException(nameof(api)); _api = api ?? throw new ArgumentNullException(nameof(api));
if (string.IsNullOrEmpty(businessBaseAddress)) _businessBaseAddress = businessBaseAddress ?? throw new ArgumentNullException(nameof(businessBaseAddress));
throw new ArgumentException("Base address is required.", nameof(businessBaseAddress)); _avatarBaseAddress = avatarBaseAddress ?? (() => null);
_baseAddress = new Uri(businessBaseAddress, UriKind.Absolute); // Validate initial values early to fail fast on invalid setup.
_avatarBaseAddress = string.IsNullOrWhiteSpace(avatarBaseAddress) _ = ResolveBusinessBaseAddress();
? _baseAddress _ = ResolveAvatarBaseAddress();
: new Uri(avatarBaseAddress, UriKind.Absolute);
} }
public Task<List<ActivityInfo>> GetCatalogAsync( public Task<List<ActivityInfo>> GetCatalogAsync(
@ -65,7 +75,7 @@ public sealed class ActivityApiClient
public string BuildAvatarXsUrl(string? userName) public string BuildAvatarXsUrl(string? userName)
{ {
var siteRoot = new Uri(_avatarBaseAddress, "/"); var siteRoot = new Uri(ResolveAvatarBaseAddress(), "/");
if (string.IsNullOrWhiteSpace(userName)) if (string.IsNullOrWhiteSpace(userName))
{ {
@ -75,5 +85,22 @@ public sealed class ActivityApiClient
return new Uri(siteRoot, $"avatars/{Uri.EscapeDataString(userName)}.xs.png").ToString(); return new Uri(siteRoot, $"avatars/{Uri.EscapeDataString(userName)}.xs.png").ToString();
} }
private string Absolute(string relativePath) => new Uri(_baseAddress, relativePath).ToString(); private string Absolute(string relativePath) => new Uri(ResolveBusinessBaseAddress(), relativePath).ToString();
private Uri ResolveBusinessBaseAddress()
{
var raw = _businessBaseAddress();
if (string.IsNullOrWhiteSpace(raw))
throw new InvalidOperationException("Business base address is required.");
return new Uri(raw, UriKind.Absolute);
}
private Uri ResolveAvatarBaseAddress()
{
var raw = _avatarBaseAddress();
return string.IsNullOrWhiteSpace(raw)
? ResolveBusinessBaseAddress()
: new Uri(raw, UriKind.Absolute);
}
} }

View file

@ -20,15 +20,20 @@ public sealed class BillingApiClient
private const string PathPrefix = "billing"; private const string PathPrefix = "billing";
private readonly IYavscApiClient _api; private readonly IYavscApiClient _api;
private readonly Uri _baseAddress; private readonly Func<string> _businessBaseAddress;
public BillingApiClient(IYavscApiClient api, string businessBaseAddress) public BillingApiClient(IYavscApiClient api, string businessBaseAddress)
: this(api, () => businessBaseAddress)
{
}
public BillingApiClient(IYavscApiClient api, Func<string> businessBaseAddress)
{ {
_api = api ?? throw new ArgumentNullException(nameof(api)); _api = api ?? throw new ArgumentNullException(nameof(api));
if (string.IsNullOrWhiteSpace(businessBaseAddress)) _businessBaseAddress = businessBaseAddress ?? throw new ArgumentNullException(nameof(businessBaseAddress));
throw new ArgumentException("Base address is required.", nameof(businessBaseAddress));
_baseAddress = new Uri(businessBaseAddress, UriKind.Absolute); // Validate initial value early to fail fast on invalid setup.
_ = ResolveBusinessBaseAddress();
} }
public Task CreateAsync(string billingCode, object payload, CancellationToken ct = default) public Task CreateAsync(string billingCode, object payload, CancellationToken ct = default)
@ -121,7 +126,16 @@ public sealed class BillingApiClient
ct: ct); ct: ct);
} }
private string Absolute(string relativePath) => new Uri(_baseAddress, relativePath).ToString(); private string Absolute(string relativePath) => new Uri(ResolveBusinessBaseAddress(), relativePath).ToString();
private Uri ResolveBusinessBaseAddress()
{
var raw = _businessBaseAddress();
if (string.IsNullOrWhiteSpace(raw))
throw new InvalidOperationException("Business base address is required.");
return new Uri(raw, UriKind.Absolute);
}
private static BillingQueryDetailsDto MapRdv(RdvQueryResponse dto, string billingCode) private static BillingQueryDetailsDto MapRdv(RdvQueryResponse dto, string billingCode)
{ {

View file

@ -204,6 +204,10 @@ public sealed class ApiWebServerFixture : WebHostFixture
ClientId = "alice", ClientId = "alice",
PerformerId = "alice", PerformerId = "alice",
Consent = true, Consent = true,
UserCreated = "alice",
UserModified = "alice",
DateCreated = DateTime.UtcNow,
DateModified = DateTime.UtcNow,
EventDate = DateTime.UtcNow.AddDays(1), EventDate = DateTime.UtcNow.AddDays(1),
Location = location, Location = location,
Reason = "Initial rendez-vous", Reason = "Initial rendez-vous",
@ -293,6 +297,10 @@ public sealed class ApiWebServerFixture : WebHostFixture
ClientId = "alice", ClientId = "alice",
PerformerId = "alice", PerformerId = "alice",
Consent = true, Consent = true,
UserCreated = "alice",
UserModified = "alice",
DateCreated = DateTime.UtcNow,
DateModified = DateTime.UtcNow,
EventDate = DateTime.UtcNow.AddDays(3), EventDate = DateTime.UtcNow.AddDays(3),
Location = location, Location = location,
PrestationId = prestation1.Id, PrestationId = prestation1.Id,
@ -308,6 +316,10 @@ public sealed class ApiWebServerFixture : WebHostFixture
ClientId = "alice", ClientId = "alice",
PerformerId = "alice", PerformerId = "alice",
Consent = true, Consent = true,
UserCreated = "alice",
UserModified = "alice",
DateCreated = DateTime.UtcNow,
DateModified = DateTime.UtcNow,
EventDate = DateTime.UtcNow.AddDays(4), EventDate = DateTime.UtcNow.AddDays(4),
Location = location, Location = location,
Prestations = new List<HairPrestationCollectionItem> Prestations = new List<HairPrestationCollectionItem>

View file

@ -0,0 +1,62 @@
using System.Net;
using System.Net.Http.Headers;
using Microsoft.Extensions.DependencyInjection;
using Yavsc.Api.Test.Fixtures;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Tests.Shared;
namespace Yavsc.Api.Test;
[Collection("Yavsc Api")]
public sealed class FrontOfficeApiControllerTests : IClassFixture<ApiWebServerFixture>
{
private readonly ApiWebServerFixture _fixture;
public FrontOfficeApiControllerTests(ApiWebServerFixture fixture)
{
_fixture = fixture;
}
private HttpClient NewClient(string subject = "alice", string scope = "api")
{
var handler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (_, _, _, _) => true
};
var http = new HttpClient(handler)
{
BaseAddress = new Uri(_fixture.BaseAddress)
};
http.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", TestTokenIssuer.Issue(subject, scope));
return http;
}
[Fact]
public async Task Front_accept_query_updates_status_without_server_error()
{
WorkflowHelpers.ConfigureBillingService();
_fixture.ResetAndSeedRdvQueryGraph();
long queryId;
using (var scope = _fixture.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
queryId = db.RdvQueries.Select(q => q.Id).Single();
}
using var http = NewClient();
var response = await http.PostAsync($"/api/v1/front/query/accept?billingCode=Rdv&queryId={queryId}", content: null, TestContext.Current.CancellationToken);
var body = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken);
Assert.True(response.StatusCode == HttpStatusCode.OK, $"Unexpected status {(int)response.StatusCode} ({response.StatusCode}): {body}");
using var assertScope = _fixture.Services.CreateScope();
var assertDb = assertScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var updated = assertDb.RdvQueries.Single(q => q.Id == queryId);
Assert.Equal(QueryStatus.Accepted, updated.Status);
}
}

View file

@ -82,4 +82,65 @@ public sealed class RdvQueryApiControllerTests : IClassFixture<ApiWebServerFixtu
var missingResponse = await http.GetAsync($"/api/v1/billing/Rdv/{fetched.Id}", TestContext.Current.CancellationToken); var missingResponse = await http.GetAsync($"/api/v1/billing/Rdv/{fetched.Id}", TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.NotFound, missingResponse.StatusCode); Assert.Equal(HttpStatusCode.NotFound, missingResponse.StatusCode);
} }
[Fact]
public async Task PostQuery_ignores_client_field_and_uses_authenticated_user()
{
_fixture.ResetAndSeedRdvQueryGraph();
using var http = NewClient(subject: "alice");
var createPayload = new
{
ActivityCode = "dev",
PerformerId = "alice",
Consent = true,
EventDate = DateTime.UtcNow.AddDays(2),
Location = new
{
Address = "2 rue du Test",
Latitude = 48.8567,
Longitude = 2.3523,
},
Reason = "Rendez-vous sans champ client",
Status = QueryStatus.Inserted,
};
var createResponse = await http.PostAsJsonAsync("/api/v1/billing/Rdv", createPayload, TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.Created, createResponse.StatusCode);
var created = await createResponse.Content.ReadFromJsonAsync<RdvQuery>(TestContext.Current.CancellationToken);
Assert.NotNull(created);
Assert.Equal("alice", created!.ClientId);
}
[Fact]
public async Task PostQuery_accepts_local_datetime_and_persists_as_utc()
{
_fixture.ResetAndSeedRdvQueryGraph();
using var http = NewClient(subject: "alice");
var localEventDate = DateTime.Now.AddDays(2);
var createPayload = new
{
ActivityCode = "dev",
PerformerId = "alice",
Consent = true,
EventDate = localEventDate,
Location = new
{
Address = "3 rue du Test",
Latitude = 48.8568,
Longitude = 2.3524,
},
Reason = "Rendez-vous date locale",
Status = QueryStatus.Inserted,
};
var createResponse = await http.PostAsJsonAsync("/api/v1/billing/Rdv", createPayload, TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.Created, createResponse.StatusCode);
var created = await createResponse.Content.ReadFromJsonAsync<RdvQuery>(TestContext.Current.CancellationToken);
Assert.NotNull(created);
Assert.Equal(DateTimeKind.Utc, created!.EventDate.Kind);
}
} }

View file

@ -51,6 +51,14 @@ namespace Yavsc.Controllers
.Distinct() .Distinct()
.ToArray(); .ToArray();
// Some providers are brittle when translating Contains over an
// empty in-memory array. If there is no candidate activity code,
// the catalog is empty by definition.
if (codes.Length == 0)
{
return Ok(new List<ActivityInfo>());
}
var performerCounts = await ( var performerCounts = await (
from ua in _context.UserActivities.AsNoTracking() from ua in _context.UserActivities.AsNoTracking()
where !string.IsNullOrWhiteSpace(ua.DoesCode) && codes.Contains(ua.DoesCode) where !string.IsNullOrWhiteSpace(ua.DoesCode) && codes.Contains(ua.DoesCode)
@ -64,10 +72,10 @@ namespace Yavsc.Controllers
var filteredActivities = activities var filteredActivities = activities
.Where(a => .Where(a =>
(performerCounts.TryGetValue(a.Code, out var ownCount) && ownCount > 0) (TryGetPerformerCount(performerCounts, a.Code, out var ownCount) && ownCount > 0)
|| (a.Children ?? new List<Activity>()) || (a.Children ?? new List<Activity>())
.Where(c => !c.Hidden) .Where(c => !c.Hidden)
.Any(c => performerCounts.TryGetValue(c.Code, out var childCount) && childCount > 0)) .Any(c => TryGetPerformerCount(performerCounts, c.Code, out var childCount) && childCount > 0))
.ToList(); .ToList();
return Ok(filteredActivities.Select(a => ToBrowseItem(a, performerCounts)).ToList()); return Ok(filteredActivities.Select(a => ToBrowseItem(a, performerCounts)).ToList());
@ -269,10 +277,10 @@ namespace Yavsc.Controllers
Code = activity.Code, Code = activity.Code,
Name = activity.Name, Name = activity.Name,
ParentCode = activity.ParentCode, ParentCode = activity.ParentCode,
Description = activity.Description, Description = activity.Description ?? string.Empty,
Photo = activity.Photo, Photo = activity.Photo,
Rate = activity.Rate, Rate = activity.Rate,
PerformerCount = performerCounts.TryGetValue(activity.Code, out var count) ? count : 0, PerformerCount = TryGetPerformerCount(performerCounts, activity.Code, out var count) ? count : 0,
Forms = (activity.Forms ?? Enumerable.Empty<CommandForm>()) Forms = (activity.Forms ?? Enumerable.Empty<CommandForm>())
.Select(f => new CommandFormSummary .Select(f => new CommandFormSummary
{ {
@ -283,17 +291,17 @@ namespace Yavsc.Controllers
.ToList(), .ToList(),
Children = (activity.Children ?? Enumerable.Empty<Activity>()) Children = (activity.Children ?? Enumerable.Empty<Activity>())
.Where(c => !c.Hidden) .Where(c => !c.Hidden)
.Where(c => performerCounts.TryGetValue(c.Code, out var childCount) && childCount > 0) .Where(c => TryGetPerformerCount(performerCounts, c.Code, out var childCount) && childCount > 0)
.OrderByDescending(c => c.Rate) .OrderByDescending(c => c.Rate)
.Select(c => new ActivityInfo .Select(c => new ActivityInfo
{ {
Code = c.Code, Code = c.Code,
Name = c.Name, Name = c.Name,
ParentCode = c.ParentCode, ParentCode = c.ParentCode,
Description = c.Description, Description = c.Description ?? string.Empty,
Photo = c.Photo, Photo = c.Photo,
Rate = c.Rate, Rate = c.Rate,
PerformerCount = performerCounts.TryGetValue(c.Code, out var childCount) ? childCount : 0, PerformerCount = TryGetPerformerCount(performerCounts, c.Code, out var childCount) ? childCount : 0,
Forms = (c.Forms ?? Enumerable.Empty<CommandForm>()) Forms = (c.Forms ?? Enumerable.Empty<CommandForm>())
.Select(f => new CommandFormSummary .Select(f => new CommandFormSummary
{ {
@ -306,5 +314,19 @@ namespace Yavsc.Controllers
.ToList(), .ToList(),
}; };
} }
private static bool TryGetPerformerCount(
IReadOnlyDictionary<string, int> performerCounts,
string code,
out int count)
{
if (string.IsNullOrWhiteSpace(code))
{
count = 0;
return false;
}
return performerCounts.TryGetValue(code, out count);
}
} }
} }

View file

@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Mvc;
using Yavsc.Helpers; using Yavsc.Helpers;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Services; using Yavsc.Services;
using Yavsc.Server.Helpers;
using Yavsc.ViewModels.FrontOffice; using Yavsc.ViewModels.FrontOffice;
namespace Yavsc.ApiControllers namespace Yavsc.ApiControllers
@ -15,10 +16,10 @@ namespace Yavsc.ApiControllers
private IBillingService billing; private IBillingService billing;
public FrontOfficeApiController(ApplicationDbContext context, IBillingService billing) public FrontOfficeApiController(ApplicationDbContext context, IBillingService billing = null)
{ {
dbContext = context; dbContext = context;
this.billing = billing; this.billing = billing ?? new BillingService(context);
} }
[HttpGet("profiles/{actCode}")] [HttpGet("profiles/{actCode}")]
@ -36,7 +37,7 @@ namespace Yavsc.ApiControllers
if (billing == null) return BadRequest(); if (billing == null) return BadRequest();
billing.Status = QueryStatus.Rejected; billing.Status = QueryStatus.Rejected;
dbContext.SaveChanges(); dbContext.SaveChanges(User.GetUserId());
return Ok(); return Ok();
} }
@ -48,7 +49,7 @@ namespace Yavsc.ApiControllers
var billing = BillingService.GetBillable(dbContext, billingCode, queryId); var billing = BillingService.GetBillable(dbContext, billingCode, queryId);
if (billing == null) return BadRequest(); if (billing == null) return BadRequest();
billing.Status = QueryStatus.Accepted; billing.Status = QueryStatus.Accepted;
dbContext.SaveChanges(); dbContext.SaveChanges(User.GetUserId());
return Ok(); return Ok();
} }
} }

View file

@ -82,19 +82,17 @@ public class HairCutQueryApiController : Controller
public async Task<IActionResult> PostQuery([FromBody] HairCutQuery query, CancellationToken cancellationToken) public async Task<IActionResult> PostQuery([FromBody] HairCutQuery query, CancellationToken cancellationToken)
{ {
var uid = User.GetUserId(); var uid = User.GetUserId();
if (string.IsNullOrWhiteSpace(query.ClientId)) query.ClientId = uid;
{
query.ClientId = uid;
}
ModelState.Remove("Client");
ModelState.Remove("ClientId"); ModelState.Remove("ClientId");
ModelState.Remove("UserCreated");
ModelState.Remove("UserModified");
ModelState.Remove("SelectedProfile");
ModelState.Remove("Prestation"); ModelState.Remove("Prestation");
ModelState.Remove("PerformerProfile");
if (query.ClientId != uid && !User.IsInRole(Constants.AdminGroupName)) ModelState.Remove("Context");
{ ModelState.Remove("Regularization");
ModelState.AddModelError("ClientId", "You can only create your own HairCutQuery");
return BadRequest(ModelState);
}
query.Prestation = await _context.HairPrestation query.Prestation = await _context.HairPrestation
.SingleOrDefaultAsync(p => p.Id == query.PrestationId, cancellationToken); .SingleOrDefaultAsync(p => p.Id == query.PrestationId, cancellationToken);

View file

@ -89,18 +89,16 @@ public class HairMultiCutQueryApiController : Controller
public async Task<IActionResult> PostQuery([FromBody] HairMultiCutQuery query, CancellationToken cancellationToken) public async Task<IActionResult> PostQuery([FromBody] HairMultiCutQuery query, CancellationToken cancellationToken)
{ {
var uid = User.GetUserId(); var uid = User.GetUserId();
if (string.IsNullOrWhiteSpace(query.ClientId)) query.ClientId = uid;
{
query.ClientId = uid;
}
ModelState.Remove("Client");
ModelState.Remove("ClientId"); ModelState.Remove("ClientId");
ModelState.Remove("UserCreated");
if (query.ClientId != uid && !User.IsInRole(Constants.AdminGroupName)) ModelState.Remove("UserModified");
{ ModelState.Remove("SelectedProfile");
ModelState.AddModelError("ClientId", "You can only create your own HairMultiCutQuery"); ModelState.Remove("PerformerProfile");
return BadRequest(ModelState); ModelState.Remove("Context");
} ModelState.Remove("Regularization");
if (query.Prestations is null || query.Prestations.Count == 0) if (query.Prestations is null || query.Prestations.Count == 0)
{ {

View file

@ -65,18 +65,18 @@ public class RdvQueryApiController : Controller
public async Task<IActionResult> PostQuery([FromBody] RdvQuery query, CancellationToken cancellationToken) public async Task<IActionResult> PostQuery([FromBody] RdvQuery query, CancellationToken cancellationToken)
{ {
var uid = User.GetUserId(); var uid = User.GetUserId();
if (string.IsNullOrWhiteSpace(query.ClientId)) // Security: the caller always posts for themselves.
{ query.ClientId = uid;
query.ClientId = uid; query.EventDate = EnsureUtc(query.EventDate);
}
ModelState.Remove("Client");
ModelState.Remove("ClientId"); ModelState.Remove("ClientId");
ModelState.Remove("UserCreated");
if (query.ClientId != uid && !User.IsInRole(Constants.AdminGroupName)) ModelState.Remove("UserModified");
{ ModelState.Remove("SelectedProfile");
ModelState.AddModelError("ClientId", "You can only create your own RdvQuery"); ModelState.Remove("PerformerProfile");
return BadRequest(ModelState); ModelState.Remove("Context");
} ModelState.Remove("Regularization");
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
@ -123,23 +123,44 @@ public class RdvQueryApiController : Controller
[HttpPut("{id}")] [HttpPut("{id}")]
public async Task<IActionResult> PutQuery([FromRoute] long id, [FromBody] RdvQuery query, CancellationToken cancellationToken) public async Task<IActionResult> PutQuery([FromRoute] long id, [FromBody] RdvQuery query, CancellationToken cancellationToken)
{ {
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != query.Id)
{
return BadRequest();
}
var uid = User.GetUserId(); var uid = User.GetUserId();
if (query.ClientId != uid && !User.IsInRole(Constants.AdminGroupName)) var existing = await _context.RdvQueries
.Include(q => q.Location)
.SingleOrDefaultAsync(q => q.Id == id, cancellationToken);
if (existing is null)
{
return NotFound();
}
if (existing.ClientId != uid && !User.IsInRole(Constants.AdminGroupName))
{ {
return Forbid(); return Forbid();
} }
_context.Entry(query).State = EntityState.Modified; existing.ActivityCode = query.ActivityCode;
existing.PerformerId = query.PerformerId;
existing.Consent = query.Consent;
existing.EventDate = EnsureUtc(query.EventDate);
existing.LocationType = query.LocationType;
existing.Reason = query.Reason;
existing.Status = query.Status;
existing.Provisional = query.Provisional;
if (query.Location is not null)
{
var resolvedLocation = await _context.Locations.FirstOrDefaultAsync(
x => x.Address == query.Location.Address
&& x.Longitude == query.Location.Longitude
&& x.Latitude == query.Location.Latitude,
cancellationToken);
existing.Location = resolvedLocation ?? query.Location;
if (resolvedLocation is null)
{
_context.Attach(query.Location);
}
}
try try
{ {
@ -186,4 +207,14 @@ public class RdvQueryApiController : Controller
{ {
return _context.RdvQueries.Any(e => e.Id == id); return _context.RdvQueries.Any(e => e.Id == id);
} }
private static DateTime EnsureUtc(DateTime value)
{
return value.Kind switch
{
DateTimeKind.Utc => value,
DateTimeKind.Local => value.ToUniversalTime(),
_ => DateTime.SpecifyKind(value, DateTimeKind.Utc)
};
}
} }

View file

@ -55,6 +55,14 @@ namespace Yavsc.Blogs.Controllers
[HttpPut("{id}")] [HttpPut("{id}")]
public async Task<IActionResult> PutBlog(long id, [FromBody] Models.Blog.BlogPost blog) public async Task<IActionResult> PutBlog(long id, [FromBody] Models.Blog.BlogPost blog)
{ {
// These properties are server-managed or optional graph members and
// should not block JSON payloads coming from API clients.
ModelState.Remove(nameof(Models.Blog.BlogPost.Author));
ModelState.Remove(nameof(Models.Blog.BlogPost.Tags));
ModelState.Remove(nameof(Models.Blog.BlogPost.Comments));
ModelState.Remove(nameof(Models.Blog.BlogPost.UserCreated));
ModelState.Remove(nameof(Models.Blog.BlogPost.UserModified));
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return BadRequest(ModelState); return BadRequest(ModelState);
@ -87,6 +95,14 @@ namespace Yavsc.Blogs.Controllers
[HttpPost] [HttpPost]
public IActionResult PostBlog([FromBody] Models.Blog.BlogPost blog) public IActionResult PostBlog([FromBody] Models.Blog.BlogPost blog)
{ {
// These properties are server-managed or optional graph members and
// should not block JSON payloads coming from API clients.
ModelState.Remove(nameof(Models.Blog.BlogPost.Author));
ModelState.Remove(nameof(Models.Blog.BlogPost.Tags));
ModelState.Remove(nameof(Models.Blog.BlogPost.Comments));
ModelState.Remove(nameof(Models.Blog.BlogPost.UserCreated));
ModelState.Remove(nameof(Models.Blog.BlogPost.UserModified));
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return BadRequest(ModelState); return BadRequest(ModelState);

View file

@ -467,8 +467,25 @@ IHtmlLocalizerFactory htmlLocalizerFactory,
if (ModelState.IsValid) if (ModelState.IsValid)
{ {
var existingUser = await _userManager.FindByEmailAsync(model.Email);
if (existingUser is not null)
{
ModelState.AddModelError(nameof(model.Email), _localizer["DuplicateEmail"]);
return View(model);
}
var user = new ApplicationUser { UserName = model.UserName, Email = model.Email }; var user = new ApplicationUser { UserName = model.UserName, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password); IdentityResult result;
try
{
result = await _userManager.CreateAsync(user, model.Password);
}
catch (DbUpdateException ex) when (IsDuplicateEmailViolation(ex))
{
_logger.LogWarning(ex, "Registration rejected: duplicate email '{Email}'.", model.Email);
ModelState.AddModelError(nameof(model.Email), _localizer["DuplicateEmail"]);
return View(model);
}
if (result.Succeeded) if (result.Succeeded)
{ {
_logger.LogInformation(3, "User created a new account with password."); _logger.LogInformation(3, "User created a new account with password.");
@ -517,6 +534,21 @@ IHtmlLocalizerFactory htmlLocalizerFactory,
return View(model); return View(model);
} }
private static bool IsDuplicateEmailViolation(Exception exception)
{
for (var current = exception; current is not null; current = current.InnerException)
{
if (current is PostgresException pg
&& pg.SqlState == PostgresErrorCodes.UniqueViolation
&& string.Equals(pg.ConstraintName, "AK_AspNetUsers_Email", StringComparison.Ordinal))
{
return true;
}
}
return false;
}
[Authorize, HttpPost, ValidateAntiForgeryToken] [Authorize, HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> SendConfirationEmail() public async Task<IActionResult> SendConfirationEmail()
{ {

View file

@ -121,6 +121,7 @@ namespace Yavsc.Controllers
public async Task<IActionResult> Create(Comment comment) public async Task<IActionResult> Create(Comment comment)
{ {
comment.UserCreated = User.GetUserId(); comment.UserCreated = User.GetUserId();
comment.UserModified = comment.UserCreated;
// AuthorId/UserCreated is set server-side after model binding; // AuthorId/UserCreated is set server-side after model binding;
// remove the stale binding error so a valid authenticated POST // remove the stale binding error so a valid authenticated POST
// does not fall into the invalid branch. // does not fall into the invalid branch.
@ -129,7 +130,7 @@ namespace Yavsc.Controllers
if (ModelState.IsValid) if (ModelState.IsValid)
{ {
_context.Comment.Add(comment); _context.Comment.Add(comment);
await _context.SaveChangesAsync(); await _context.SaveChangesAsync(comment.UserCreated);
return RedirectToAction("Index"); return RedirectToAction("Index");
} }
ViewBag.ReceiverId = new SelectList(_context.BlogSpot, "Id", "Title", comment.ReceiverId); ViewBag.ReceiverId = new SelectList(_context.BlogSpot, "Id", "Title", comment.ReceiverId);

View file

@ -1,3 +1,5 @@
#nullable enable annotations
 
using IdentityServer8; using IdentityServer8;
using IdentityServer8.Models; using IdentityServer8.Models;

View file

@ -1,3 +1,5 @@
#nullable enable annotations
namespace Yavsc.Server namespace Yavsc.Server
{ {

View file

@ -1,3 +1,5 @@
#nullable enable annotations
namespace Yavsc.Server.Exceptions; namespace Yavsc.Server.Exceptions;
[Serializable] [Serializable]

View file

@ -1,3 +1,5 @@
#nullable enable annotations
namespace Yavsc.Services namespace Yavsc.Services
{ {
[Serializable] [Serializable]

View file

@ -1,3 +1,5 @@
#nullable enable annotations
using System.Globalization; using System.Globalization;
using Yavsc.Billing; using Yavsc.Billing;
using Yavsc.Models.Billing; using Yavsc.Models.Billing;

View file

@ -1,3 +1,5 @@
#nullable enable annotations
using System.Security.Claims; using System.Security.Claims;
using System.Text; using System.Text;
using System.Text.Json; using System.Text.Json;

View file

@ -1,3 +1,5 @@
#nullable enable annotations
using System.Security.Claims; using System.Security.Claims;

View file

@ -1,3 +1,5 @@
#nullable enable annotations
using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Yavsc.Models.Drawing; using Yavsc.Models.Drawing;

View file

@ -1,3 +1,5 @@
#nullable enable annotations
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Yavsc.Models.Billing; using Yavsc.Models.Billing;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;

View file

@ -1,3 +1,5 @@
#nullable enable annotations
using System.Net; using System.Net;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using Yavsc.Server.Model; using Yavsc.Server.Model;

View file

@ -1,3 +1,5 @@
#nullable enable annotations
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;

View file

@ -1,3 +1,5 @@
#nullable enable annotations
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System.Security.Claims; using System.Security.Claims;
using Yavsc.Models; using Yavsc.Models;

View file

@ -1,3 +1,5 @@
#nullable enable annotations
// //
// ChatHub.cs // ChatHub.cs
// //

View file

@ -1,3 +1,5 @@
#nullable enable annotations
// //
// ChatHub.cs // ChatHub.cs
// //

View file

@ -1,3 +1,5 @@
#nullable enable annotations
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

View file

@ -108,6 +108,7 @@ namespace Yavsc.Models
; ;
builder.Entity<Activity>().Property(a => a.ParentCode).IsRequired(false); builder.Entity<Activity>().Property(a => a.ParentCode).IsRequired(false);
builder.Entity<Activity>().Property(a => a.Description).IsRequired(false);
builder.Entity<Country>().HasKey(c => c.Code); builder.Entity<Country>().HasKey(c => c.Code);
builder.Entity<PerformerCodeInputValidation>() builder.Entity<PerformerCodeInputValidation>()

Some files were not shown because too many files have changed in this diff Show more