From 4f26f14e56e50833c3bab4a9f5ac8d5e323b2f10 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sun, 6 Sep 2026 14:52:50 +0100 Subject: [PATCH 01/67] postit: unify action status bar with severity across settings/activities/circles/rdv --- src/PostIt/PostIt/Controls/StatusBar.axaml | 22 +++++++ src/PostIt/PostIt/Controls/StatusBar.axaml.cs | 11 ++++ .../ViewModels/ActivitiesPageViewModel.cs | 8 +++ .../PostIt/ViewModels/CirclesPageViewModel.cs | 8 +++ .../Commands/BillingCommandPageViewModel.cs | 8 +++ .../PostIt/ViewModels/Settings/Settings.cs | 18 ++++++ src/PostIt/PostIt/ViewModels/StatusNotice.cs | 58 +++++++++++++++++++ src/PostIt/PostIt/Views/ActivitiesPage.axaml | 13 +---- src/PostIt/PostIt/Views/CirclesPage.axaml | 5 +- .../PostIt/Views/Commands/RdvPage.axaml | 13 +---- src/PostIt/PostIt/Views/SettingsPage.axaml | 5 +- src/PostIt/PostIt/Views/SettingsPage.axaml.cs | 30 +++++----- 12 files changed, 159 insertions(+), 40 deletions(-) create mode 100644 src/PostIt/PostIt/Controls/StatusBar.axaml create mode 100644 src/PostIt/PostIt/Controls/StatusBar.axaml.cs create mode 100644 src/PostIt/PostIt/ViewModels/StatusNotice.cs diff --git a/src/PostIt/PostIt/Controls/StatusBar.axaml b/src/PostIt/PostIt/Controls/StatusBar.axaml new file mode 100644 index 000000000..eaa6f5a09 --- /dev/null +++ b/src/PostIt/PostIt/Controls/StatusBar.axaml @@ -0,0 +1,22 @@ + + + + + + + + diff --git a/src/PostIt/PostIt/Controls/StatusBar.axaml.cs b/src/PostIt/PostIt/Controls/StatusBar.axaml.cs new file mode 100644 index 000000000..975f9b2f9 --- /dev/null +++ b/src/PostIt/PostIt/Controls/StatusBar.axaml.cs @@ -0,0 +1,11 @@ +using Avalonia.Controls; + +namespace PostIt.Controls; + +public partial class StatusBar : UserControl +{ + public StatusBar() + { + InitializeComponent(); + } +} diff --git a/src/PostIt/PostIt/ViewModels/ActivitiesPageViewModel.cs b/src/PostIt/PostIt/ViewModels/ActivitiesPageViewModel.cs index 2dc8938f3..801cf21d4 100644 --- a/src/PostIt/PostIt/ViewModels/ActivitiesPageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/ActivitiesPageViewModel.cs @@ -43,6 +43,14 @@ public partial class ActivitiesPageViewModel : ViewModelBase [ObservableProperty] public partial string StatusMessage { get; set; } = "Choisissez une activité."; + [ObservableProperty] + public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Choisissez une activité."); + + partial void OnStatusMessageChanged(string value) + { + ActionStatus = StatusNotice.FromMessage(value); + } + public ActivityInfo? CurrentActivity => SelectedSpecialization ?? SelectedActivity; public string SelectedActivityLabel => SelectedActivity?.Name ?? "(aucune activité)"; public string CurrentActivityLabel => CurrentActivity?.Name ?? "(aucune)"; diff --git a/src/PostIt/PostIt/ViewModels/CirclesPageViewModel.cs b/src/PostIt/PostIt/ViewModels/CirclesPageViewModel.cs index 9cee3ea8c..6d70add1d 100644 --- a/src/PostIt/PostIt/ViewModels/CirclesPageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/CirclesPageViewModel.cs @@ -65,6 +65,14 @@ public partial class CirclesPageViewModel : ViewModelBase [ObservableProperty] public partial string StatusMessage { get; set; } = string.Empty; + [ObservableProperty] + public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Pret."); + + partial void OnStatusMessageChanged(string value) + { + ActionStatus = StatusNotice.FromMessage(value); + } + public CirclesPageViewModel(CircleApiClient client) { diff --git a/src/PostIt/PostIt/ViewModels/Commands/BillingCommandPageViewModel.cs b/src/PostIt/PostIt/ViewModels/Commands/BillingCommandPageViewModel.cs index 0ab76291d..5fd7d8461 100644 --- a/src/PostIt/PostIt/ViewModels/Commands/BillingCommandPageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/Commands/BillingCommandPageViewModel.cs @@ -23,6 +23,9 @@ public abstract partial class BillingCommandPageViewModel : RemoteViewModelBase [ObservableProperty] public partial string StatusMessage { get; set; } + [ObservableProperty] + public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Pret."); + [ObservableProperty] public partial string Reason { get; set; } = string.Empty; @@ -89,6 +92,11 @@ public abstract partial class BillingCommandPageViewModel : RemoteViewModelBase OnPropertyChanged(nameof(CanUseCurrentLocation)); } + partial void OnStatusMessageChanged(string value) + { + ActionStatus = StatusNotice.FromMessage(value); + } + public async Task InitializeAsync(BillingQueryDetailsDto? existingQuery = null) { await LoadAsync(); diff --git a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs index e63f0b321..b59ef9933 100644 --- a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs +++ b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs @@ -31,6 +31,19 @@ public partial class Settings : ViewModelBase [ObservableProperty] public partial string SearchText { get; set; } = string.Empty; + [ObservableProperty] + 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), + }; + } + /// /// Catch top-level mutations: the four ObservableProperty /// setters above all funnel through here, and we flip @@ -406,6 +419,8 @@ public partial class Settings : ViewModelBase [RelayCommand(CanExecute = nameof(CanSave))] public void Save() { + SetActionStatus("Enregistrement des parametres...", StatusSeverity.Info); + var configDir = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "PostIt"); @@ -425,10 +440,13 @@ public partial class Settings : ViewModelBase File.SetUnixFileMode(configPath, UnixFileMode.UserRead | UnixFileMode.UserWrite); IsDirty = false; + SetActionStatus("Parametres sauvegardes.", StatusSeverity.Info); + Console.WriteLine($"💾 Settings saved to {configPath}"); } catch (Exception ex) { + SetActionStatus($"Echec sauvegarde parametres: {ex.Message}", StatusSeverity.Error); Console.Error.WriteLine($"🩎 Error saving settings to {configPath}: {ex.Message}"); throw; } diff --git a/src/PostIt/PostIt/ViewModels/StatusNotice.cs b/src/PostIt/PostIt/ViewModels/StatusNotice.cs new file mode 100644 index 000000000..2d14b28b3 --- /dev/null +++ b/src/PostIt/PostIt/ViewModels/StatusNotice.cs @@ -0,0 +1,58 @@ +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); + + public static StatusNotice FromMessage(string? message) + { + if (string.IsNullOrWhiteSpace(message)) + { + return Info("Pret."); + } + + var text = message.Trim(); + var lower = text.ToLowerInvariant(); + + if (lower.StartsWith("erreur") || lower.StartsWith("echec") || lower.StartsWith("impossible")) + { + return Error(text); + } + + if (lower.Contains("refuse") || lower.Contains("annule") || lower.Contains("obligatoire") || lower.Contains("deja")) + { + return Warning(text); + } + + return Info(text); + } +} diff --git a/src/PostIt/PostIt/Views/ActivitiesPage.axaml b/src/PostIt/PostIt/Views/ActivitiesPage.axaml index 16d883443..a34d8edf2 100644 --- a/src/PostIt/PostIt/Views/ActivitiesPage.axaml +++ b/src/PostIt/PostIt/Views/ActivitiesPage.axaml @@ -1,6 +1,7 @@ - + diff --git a/src/PostIt/PostIt/Views/CirclesPage.axaml b/src/PostIt/PostIt/Views/CirclesPage.axaml index 6fc2172ba..8488201e2 100644 --- a/src/PostIt/PostIt/Views/CirclesPage.axaml +++ b/src/PostIt/PostIt/Views/CirclesPage.axaml @@ -1,6 +1,7 @@ - + diff --git a/src/PostIt/PostIt/Views/Commands/RdvPage.axaml b/src/PostIt/PostIt/Views/Commands/RdvPage.axaml index 46280602b..4c88b0108 100644 --- a/src/PostIt/PostIt/Views/Commands/RdvPage.axaml +++ b/src/PostIt/PostIt/Views/Commands/RdvPage.axaml @@ -1,6 +1,7 @@ @@ -71,16 +72,8 @@ Content="{Binding SubmitLabel}" Command="{Binding SubmitCommand}" IsEnabled="{Binding IsSupported}" /> - + - + public AddCircleMemberDialogViewModel? ViewModel => DataContext as AddCircleMemberDialogViewModel; - - private async Task OnCloseClicked(object? sender, RoutedEventArgs e) - { - App app = App.Current! as App; - await app!.GoBackAsync(); - } } From 37d6551a23ff4f265dec87a3a80789f25a399b9d Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sun, 6 Sep 2026 15:45:24 +0100 Subject: [PATCH 04/67] postit: replace inferred status severity with explicit setters --- .../ActionStatusViewModelExtensions.cs | 32 +++++++++++++ .../ViewModels/ActivitiesPageViewModel.cs | 29 +++++------- .../AddCircleMemberDialogViewModel.cs | 19 +++----- .../ViewModels/BillingQueriesPageViewModel.cs | 23 ++++------ .../PostIt/ViewModels/CirclesPageViewModel.cs | 46 ++++++++----------- .../ViewModels/CommandFormsPageViewModel.cs | 25 +++++----- .../Commands/BillingCommandPageViewModel.cs | 11 ++--- .../ViewModels/Commands/BrushViewModel.cs | 26 ++++++----- .../ViewModels/Commands/MBrushViewModel.cs | 14 +++--- .../ViewModels/Commands/RdvViewModel.cs | 28 +++++------ src/PostIt/PostIt/ViewModels/MainViewModel.cs | 35 ++++++-------- .../ViewModels/PostAclDialogViewModel.cs | 31 ++++++------- .../ViewModels/SignaturePageViewModel.cs | 21 ++++----- src/PostIt/PostIt/ViewModels/StatusNotice.cs | 23 ---------- 14 files changed, 165 insertions(+), 198 deletions(-) create mode 100644 src/PostIt/PostIt/ViewModels/ActionStatusViewModelExtensions.cs diff --git a/src/PostIt/PostIt/ViewModels/ActionStatusViewModelExtensions.cs b/src/PostIt/PostIt/ViewModels/ActionStatusViewModelExtensions.cs new file mode 100644 index 000000000..614d477c8 --- /dev/null +++ b/src/PostIt/PostIt/ViewModels/ActionStatusViewModelExtensions.cs @@ -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), + }; + } +} \ No newline at end of file diff --git a/src/PostIt/PostIt/ViewModels/ActivitiesPageViewModel.cs b/src/PostIt/PostIt/ViewModels/ActivitiesPageViewModel.cs index 801cf21d4..bd13faf9b 100644 --- a/src/PostIt/PostIt/ViewModels/ActivitiesPageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/ActivitiesPageViewModel.cs @@ -13,7 +13,7 @@ using Yavsc.Api.Client; namespace PostIt.ViewModels; -public partial class ActivitiesPageViewModel : ViewModelBase +public partial class ActivitiesPageViewModel : ViewModelBase, IActionStatusViewModel { private readonly ActivityApiClient _client; private readonly BillingApiClient _billingClient; @@ -46,11 +46,6 @@ public partial class ActivitiesPageViewModel : ViewModelBase [ObservableProperty] public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Choisissez une activité."); - partial void OnStatusMessageChanged(string value) - { - ActionStatus = StatusNotice.FromMessage(value); - } - public ActivityInfo? CurrentActivity => SelectedSpecialization ?? SelectedActivity; public string SelectedActivityLabel => SelectedActivity?.Name ?? "(aucune activité)"; public string CurrentActivityLabel => CurrentActivity?.Name ?? "(aucune)"; @@ -94,11 +89,11 @@ public partial class ActivitiesPageViewModel : ViewModelBase } 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) { - StatusMessage = $"Erreur: {ex.Message}"; + this.SetErrorStatus($"Erreur: {ex.Message}"); } } @@ -110,11 +105,11 @@ public partial class ActivitiesPageViewModel : ViewModelBase } 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) { - StatusMessage = $"Erreur: {ex.Message}"; + this.SetErrorStatus($"Erreur: {ex.Message}"); } } @@ -131,7 +126,7 @@ public partial class ActivitiesPageViewModel : ViewModelBase await ShowActivityAsync(first); 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) @@ -139,14 +134,14 @@ public partial class ActivitiesPageViewModel : ViewModelBase Activities = new ObservableCollection(); Specializations = new ObservableCollection(); Performers = new ObservableCollection(); - 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) { Activities = new ObservableCollection(); Specializations = new ObservableCollection(); Performers = new ObservableCollection(); - StatusMessage = $"Erreur: {ex.Message}"; + this.SetErrorStatus($"Erreur: {ex.Message}"); } finally { @@ -238,19 +233,19 @@ public partial class ActivitiesPageViewModel : ViewModelBase Performers = new ObservableCollection(items); 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) { Performers = new ObservableCollection(); 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) { Performers = new ObservableCollection(); SelectedPerformer = null; - StatusMessage = $"Erreur: {ex.Message}"; + this.SetErrorStatus($"Erreur: {ex.Message}"); } finally { @@ -267,7 +262,7 @@ public partial class ActivitiesPageViewModel : ViewModelBase { 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; } diff --git a/src/PostIt/PostIt/ViewModels/AddCircleMemberDialogViewModel.cs b/src/PostIt/PostIt/ViewModels/AddCircleMemberDialogViewModel.cs index d3f9deb68..635073d1a 100644 --- a/src/PostIt/PostIt/ViewModels/AddCircleMemberDialogViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/AddCircleMemberDialogViewModel.cs @@ -29,7 +29,7 @@ namespace PostIt.ViewModels; /// CirclesPage then calls /// . /// -public partial class AddCircleMemberDialogViewModel : ViewModelBase +public partial class AddCircleMemberDialogViewModel : ViewModelBase, IActionStatusViewModel { private readonly IUserDirectory _directory; @@ -46,15 +46,10 @@ public partial class AddCircleMemberDialogViewModel : ViewModelBase public partial bool IsBusy { get; set; } [ObservableProperty] - public partial string StatusMessage { get; set; } = string.Empty; + public partial string StatusMessage { get; set; } = "Pret."; [ObservableProperty] - public partial StatusNotice ActionStatus { get; set; } = StatusNotice.FromMessage(string.Empty); - - partial void OnStatusMessageChanged(string value) - { - ActionStatus = StatusNotice.FromMessage(value); - } + public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Pret."); /// /// Raised when the user confirms a selection. The hosting @@ -87,7 +82,7 @@ public partial class AddCircleMemberDialogViewModel : ViewModelBase if (string.IsNullOrWhiteSpace(SearchQuery)) { Results.Clear(); - StatusMessage = "Tapez un nom ou un email"; + this.SetWarningStatus("Tapez un nom ou un email"); return; } @@ -96,11 +91,11 @@ public partial class AddCircleMemberDialogViewModel : ViewModelBase { var hits = await _directory.SearchAsync(SearchQuery, CancellationToken.None).ConfigureAwait(true); Results = new ObservableCollection(hits ?? Array.Empty()); - StatusMessage = $"{Results.Count} résultat(s)"; + this.SetInfoStatus($"{Results.Count} résultat(s)"); } catch (Exception ex) { - StatusMessage = $"Erreur: {ex.Message}"; + this.SetErrorStatus($"Erreur: {ex.Message}"); } finally { @@ -118,7 +113,7 @@ public partial class AddCircleMemberDialogViewModel : ViewModelBase { if (Selected is null) { - StatusMessage = "Sélectionnez un utilisateur"; + this.SetWarningStatus("Sélectionnez un utilisateur"); return; } Confirmed?.Invoke(this, Selected); diff --git a/src/PostIt/PostIt/ViewModels/BillingQueriesPageViewModel.cs b/src/PostIt/PostIt/ViewModels/BillingQueriesPageViewModel.cs index 098cdc6f4..d3c097f43 100644 --- a/src/PostIt/PostIt/ViewModels/BillingQueriesPageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/BillingQueriesPageViewModel.cs @@ -14,7 +14,7 @@ using Yavsc.Abstract.Workflow; namespace PostIt.ViewModels; -public partial class BillingQueriesPageViewModel : ViewModelBase +public partial class BillingQueriesPageViewModel : ViewModelBase, IActionStatusViewModel { private readonly BillingApiClient _billingClient; @@ -37,12 +37,7 @@ public partial class BillingQueriesPageViewModel : ViewModelBase public partial string StatusMessage { get; set; } = "Chargement des commandes..."; [ObservableProperty] - public partial StatusNotice ActionStatus { get; set; } = StatusNotice.FromMessage("Chargement des commandes..."); - - partial void OnStatusMessageChanged(string value) - { - ActionStatus = StatusNotice.FromMessage(value); - } + public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Chargement des commandes..."); public string Title => IsReadOnly ? $"Demandes en cours ({Form.Title})" @@ -98,17 +93,17 @@ public partial class BillingQueriesPageViewModel : ViewModelBase .ToList(); Queries = new ObservableCollection(filtered); - StatusMessage = BuildLoadedStatusMessage(filtered.Count); + this.SetInfoStatus(BuildLoadedStatusMessage(filtered.Count)); } catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) { Queries = new ObservableCollection(); - 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) { Queries = new ObservableCollection(); - StatusMessage = $"Erreur: {ex.Message}"; + this.SetErrorStatus($"Erreur: {ex.Message}"); } finally { @@ -121,13 +116,13 @@ public partial class BillingQueriesPageViewModel : ViewModelBase { if (IsReadOnly) { - StatusMessage = "Mode lecture seule: l'ouverture en modification est désactivée."; + this.SetWarningStatus("Mode lecture seule: l'ouverture en modification est désactivée."); return; } if (SelectedQuery is null) { - StatusMessage = "Sélectionnez une commande."; + this.SetWarningStatus("Sélectionnez une commande."); return; } @@ -147,11 +142,11 @@ public partial class BillingQueriesPageViewModel : ViewModelBase } 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) { - StatusMessage = $"Erreur lors de l'ouverture: {ex.Message}"; + this.SetErrorStatus($"Erreur lors de l'ouverture: {ex.Message}"); } finally { diff --git a/src/PostIt/PostIt/ViewModels/CirclesPageViewModel.cs b/src/PostIt/PostIt/ViewModels/CirclesPageViewModel.cs index 73b87a181..cd068b4f4 100644 --- a/src/PostIt/PostIt/ViewModels/CirclesPageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/CirclesPageViewModel.cs @@ -34,7 +34,7 @@ namespace PostIt.ViewModels; /// . The "remove" /// command is per-row and runs inline. /// -public partial class CirclesPageViewModel : ViewModelBase +public partial class CirclesPageViewModel : ViewModelBase, IActionStatusViewModel { private readonly CircleApiClient _client; @@ -63,17 +63,11 @@ public partial class CirclesPageViewModel : ViewModelBase public partial bool IsBusy { get; set; } [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."); - partial void OnStatusMessageChanged(string value) - { - ActionStatus = StatusNotice.FromMessage(value); - } - - public CirclesPageViewModel(CircleApiClient client) { _client = client ?? throw new ArgumentNullException(nameof(client)); @@ -108,11 +102,11 @@ public partial class CirclesPageViewModel : ViewModelBase { var list = await _client.GetMyCirclesAsync(); Circles = new ObservableCollection(list ?? new()); - StatusMessage = $"{Circles.Count} cercle(s)"; + this.SetInfoStatus($"{Circles.Count} cercle(s)"); } catch (Exception ex) { - StatusMessage = $"Erreur: {ex.Message}"; + this.SetErrorStatus($"Erreur: {ex.Message}"); } finally { @@ -157,11 +151,11 @@ public partial class CirclesPageViewModel : ViewModelBase { var list = await _client.GetMembersAsync(circleId); Members = new ObservableCollection(list ?? new()); - StatusMessage = $"{Members.Count} membre(s)"; + this.SetInfoStatus($"{Members.Count} membre(s)"); } catch (Exception ex) { - StatusMessage = $"Erreur: {ex.Message}"; + this.SetErrorStatus($"Erreur: {ex.Message}"); Members = new ObservableCollection(); } finally @@ -176,7 +170,7 @@ public partial class CirclesPageViewModel : ViewModelBase SelectedCircle = null; DraftName = string.Empty; DraftPublic = false; - StatusMessage = "Nouveau cercle"; + this.SetInfoStatus("Nouveau cercle"); } [RelayCommand] @@ -186,7 +180,7 @@ public partial class CirclesPageViewModel : ViewModelBase SelectedCircle = circle; DraftName = circle.Name; DraftPublic = circle.Public; - StatusMessage = $"Édition de « {circle.Name} »"; + this.SetInfoStatus($"Édition de « {circle.Name} »"); } [RelayCommand] @@ -194,7 +188,7 @@ public partial class CirclesPageViewModel : ViewModelBase { if (string.IsNullOrWhiteSpace(DraftName)) { - StatusMessage = "Le nom est obligatoire"; + this.SetWarningStatus("Le nom est obligatoire"); return; } @@ -208,22 +202,22 @@ public partial class CirclesPageViewModel : ViewModelBase Name = DraftName.Trim(), Public = DraftPublic, }); - StatusMessage = created is null - ? "Création échouée" - : $"Cercle « {created.Name} » créé"; + this.SetStatus( + created is null ? "Création échouée" : $"Cercle « {created.Name} » créé", + created is null ? StatusSeverity.Warning : StatusSeverity.Info); } else { SelectedCircle.Name = DraftName.Trim(); SelectedCircle.Public = DraftPublic; await _client.UpdateCircleAsync(SelectedCircle.Id, SelectedCircle); - StatusMessage = $"Cercle « {SelectedCircle.Name} » mis à jour"; + this.SetInfoStatus($"Cercle « {SelectedCircle.Name} » mis à jour"); } await RefreshAsync(); } catch (Exception ex) { - StatusMessage = $"Erreur: {ex.Message}"; + this.SetErrorStatus($"Erreur: {ex.Message}"); } finally { @@ -239,7 +233,7 @@ public partial class CirclesPageViewModel : ViewModelBase try { await _client.DeleteCircleAsync(circle.Id); - StatusMessage = $"Cercle « {circle.Name} » supprimé"; + this.SetInfoStatus($"Cercle « {circle.Name} » supprimé"); // If the deleted circle was the selected one, // clear the selection so the Members view goes // empty too (the partial setter on @@ -250,7 +244,7 @@ public partial class CirclesPageViewModel : ViewModelBase } catch (Exception ex) { - StatusMessage = $"Erreur: {ex.Message}"; + this.SetErrorStatus($"Erreur: {ex.Message}"); } finally { @@ -271,7 +265,7 @@ public partial class CirclesPageViewModel : ViewModelBase try { await _client.AddMemberAsync(SelectedCircle.Id, picked.Id); - StatusMessage = $"« {picked.DisplayName} » ajouté au cercle"; + this.SetInfoStatus($"« {picked.DisplayName} » ajouté au cercle"); await LoadMembersAsync(SelectedCircle.Id); } catch (Exception ex) @@ -286,7 +280,7 @@ public partial class CirclesPageViewModel : ViewModelBase var msg = ex.Message.Contains("409") || ex.Message.Contains("Conflict") ? "Déjà membre du cercle" : $"Erreur: {ex.Message}"; - StatusMessage = msg; + this.SetStatus(msg, msg == "Déjà membre du cercle" ? StatusSeverity.Warning : StatusSeverity.Error); } finally { @@ -307,11 +301,11 @@ public partial class CirclesPageViewModel : ViewModelBase { await _client.RemoveMemberAsync(SelectedCircle.Id, member.Id); Members.Remove(member); - StatusMessage = $"« {member.UserName} » retiré du cercle"; + this.SetInfoStatus($"« {member.UserName} » retiré du cercle"); } catch (Exception ex) { - StatusMessage = $"Erreur: {ex.Message}"; + this.SetErrorStatus($"Erreur: {ex.Message}"); } finally { diff --git a/src/PostIt/PostIt/ViewModels/CommandFormsPageViewModel.cs b/src/PostIt/PostIt/ViewModels/CommandFormsPageViewModel.cs index fd4c9ec8d..533fbc380 100644 --- a/src/PostIt/PostIt/ViewModels/CommandFormsPageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/CommandFormsPageViewModel.cs @@ -11,7 +11,7 @@ using Yavsc.Api.Client; namespace PostIt.ViewModels; -public partial class CommandFormsPageViewModel : ViewModelBase +public partial class CommandFormsPageViewModel : ViewModelBase, IActionStatusViewModel { private readonly BillingApiClient _billingClient; @@ -25,15 +25,10 @@ public partial class CommandFormsPageViewModel : ViewModelBase public partial CommandFormSummary? SelectedForm { get; set; } [ObservableProperty] - public partial string StatusMessage { get; set; } + public partial string StatusMessage { get; set; } = "Pret."; [ObservableProperty] - public partial StatusNotice ActionStatus { get; set; } = StatusNotice.FromMessage(string.Empty); - - partial void OnStatusMessageChanged(string value) - { - ActionStatus = StatusNotice.FromMessage(value); - } + public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Pret."); public string Title => $"Formulaires pour {Performer.UserName}"; public string ContextLabel => $"{Activity.Name} · {Forms.Count} formulaire(s)"; @@ -63,9 +58,11 @@ public partial class CommandFormsPageViewModel : ViewModelBase .OrderBy(f => f.Title) .ThenBy(f => f.ActionName)); SelectedForm = Forms.FirstOrDefault(); - StatusMessage = Forms.Count == 0 - ? "Aucun formulaire n'est disponible pour cette activité." - : "Choisissez le formulaire à utiliser."; + this.SetStatus( + Forms.Count == 0 + ? "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; @@ -79,7 +76,7 @@ public partial class CommandFormsPageViewModel : ViewModelBase { if (SelectedForm is null) { - StatusMessage = "Sélectionnez un formulaire."; + this.SetWarningStatus("Sélectionnez un formulaire."); return; } @@ -100,7 +97,7 @@ public partial class CommandFormsPageViewModel : ViewModelBase { if (SelectedForm is null) { - StatusMessage = "Sélectionnez un formulaire."; + this.SetWarningStatus("Sélectionnez un formulaire."); return; } @@ -120,7 +117,7 @@ public partial class CommandFormsPageViewModel : ViewModelBase { if (SelectedForm is null) { - StatusMessage = "Sélectionnez un formulaire."; + this.SetWarningStatus("Sélectionnez un formulaire."); return; } diff --git a/src/PostIt/PostIt/ViewModels/Commands/BillingCommandPageViewModel.cs b/src/PostIt/PostIt/ViewModels/Commands/BillingCommandPageViewModel.cs index 5fd7d8461..5ad2b08f4 100644 --- a/src/PostIt/PostIt/ViewModels/Commands/BillingCommandPageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/Commands/BillingCommandPageViewModel.cs @@ -9,7 +9,7 @@ using Yavsc.Models.Billing; namespace PostIt.ViewModels; -public abstract partial class BillingCommandPageViewModel : RemoteViewModelBase +public abstract partial class BillingCommandPageViewModel : RemoteViewModelBase, IActionStatusViewModel { protected readonly BillingApiClient _billingClient; @@ -21,7 +21,7 @@ public abstract partial class BillingCommandPageViewModel : RemoteViewModelBase public partial bool IsBusy { get; set; } [ObservableProperty] - public partial string StatusMessage { get; set; } + public partial string StatusMessage { get; set; } = "Pret."; [ObservableProperty] public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Pret."); @@ -78,7 +78,7 @@ public abstract partial class BillingCommandPageViewModel : RemoteViewModelBase Form = form ?? throw new ArgumentNullException(nameof(form)); _billingClient = billingClient ?? throw new ArgumentNullException(nameof(billingClient)); - StatusMessage = SupportMessage; + this.SetInfoStatus(SupportMessage); } partial void OnExistingQueryIdChanged(long? value) @@ -92,11 +92,6 @@ public abstract partial class BillingCommandPageViewModel : RemoteViewModelBase OnPropertyChanged(nameof(CanUseCurrentLocation)); } - partial void OnStatusMessageChanged(string value) - { - ActionStatus = StatusNotice.FromMessage(value); - } - public async Task InitializeAsync(BillingQueryDetailsDto? existingQuery = null) { await LoadAsync(); diff --git a/src/PostIt/PostIt/ViewModels/Commands/BrushViewModel.cs b/src/PostIt/PostIt/ViewModels/Commands/BrushViewModel.cs index d49fde803..72d9ce8ea 100644 --- a/src/PostIt/PostIt/ViewModels/Commands/BrushViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/Commands/BrushViewModel.cs @@ -58,18 +58,20 @@ public partial class BrushViewModel : RdvViewModel SelectedPrestation = AvailablePrestations.FirstOrDefault(); } - StatusMessage = AvailablePrestations.Count == 0 - ? "Aucune prestation coiffure disponible." - : SupportMessage; + this.SetStatus( + AvailablePrestations.Count == 0 + ? "Aucune prestation coiffure disponible." + : SupportMessage, + AvailablePrestations.Count == 0 ? StatusSeverity.Warning : StatusSeverity.Info); } catch (HttpRequestException ex) 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) { - StatusMessage = $"Erreur lors du chargement des prestations: {ex.Message}"; + this.SetErrorStatus($"Erreur lors du chargement des prestations: {ex.Message}"); } finally { @@ -81,19 +83,19 @@ public partial class BrushViewModel : RdvViewModel { if (!Consent) { - StatusMessage = "Le consentement est requis pour poster la commande."; + this.SetWarningStatus("Le consentement est requis pour poster la commande."); return; } if (string.IsNullOrWhiteSpace(Address)) { - StatusMessage = "L'adresse du rendez-vous est requise."; + this.SetWarningStatus("L'adresse du rendez-vous est requise."); return; } if (SelectedPrestation is null) { - StatusMessage = "Sélectionnez une prestation coiffure."; + this.SetWarningStatus("Sélectionnez une prestation coiffure."); return; } @@ -143,18 +145,18 @@ public partial class BrushViewModel : RdvViewModel }).ConfigureAwait(true); } - StatusMessage = IsEditingExisting + this.SetInfoStatus(IsEditingExisting ? $"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) { - 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) { - StatusMessage = $"Erreur lors de l'envoi de la commande: {ex.Message}"; + this.SetErrorStatus($"Erreur lors de l'envoi de la commande: {ex.Message}"); } finally { diff --git a/src/PostIt/PostIt/ViewModels/Commands/MBrushViewModel.cs b/src/PostIt/PostIt/ViewModels/Commands/MBrushViewModel.cs index 793a77516..05481c2c3 100644 --- a/src/PostIt/PostIt/ViewModels/Commands/MBrushViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/Commands/MBrushViewModel.cs @@ -49,20 +49,20 @@ public partial class MBrushViewModel : BrushViewModel { if (!Consent) { - StatusMessage = "Le consentement est requis pour poster la commande."; + this.SetWarningStatus("Le consentement est requis pour poster la commande."); return; } if (string.IsNullOrWhiteSpace(Address)) { - StatusMessage = "L'adresse du rendez-vous est requise."; + this.SetWarningStatus("L'adresse du rendez-vous est requise."); return; } var selectedPrestations = MultiPrestations.Where(x => x.IsSelected).ToList(); if (selectedPrestations.Count == 0) { - StatusMessage = "Sélectionnez au moins une prestation coiffure."; + this.SetWarningStatus("Sélectionnez au moins une prestation coiffure."); return; } @@ -109,18 +109,18 @@ public partial class MBrushViewModel : BrushViewModel }).ConfigureAwait(true); } - StatusMessage = IsEditingExisting + this.SetInfoStatus(IsEditingExisting ? $"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) { - 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) { - StatusMessage = $"Erreur lors de l'envoi de la commande: {ex.Message}"; + this.SetErrorStatus($"Erreur lors de l'envoi de la commande: {ex.Message}"); } finally { diff --git a/src/PostIt/PostIt/ViewModels/Commands/RdvViewModel.cs b/src/PostIt/PostIt/ViewModels/Commands/RdvViewModel.cs index c2ff3294e..afd0c54bd 100644 --- a/src/PostIt/PostIt/ViewModels/Commands/RdvViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/Commands/RdvViewModel.cs @@ -54,7 +54,7 @@ public partial class RdvViewModel : BillingCommandPageViewModel Longitude = existingQuery.Location.Longitude; } - StatusMessage = $"Commande #{existingQuery.Id} chargée."; + this.SetInfoStatus($"Commande #{existingQuery.Id} chargée."); } [RelayCommand(CanExecute = nameof(CanUseCurrentLocation))] @@ -71,23 +71,23 @@ public partial class RdvViewModel : BillingCommandPageViewModel var result = await Platform.TryGetCurrentLocationAsync(default).ConfigureAwait(true); if (!result.IsSuccess || !result.Latitude.HasValue || !result.Longitude.HasValue) { - StatusMessage = result.Message; + this.SetWarningStatus(result.Message); return; } Latitude = result.Latitude.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." - : result.Message; + : result.Message); } 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) { - StatusMessage = $"Impossible de récupérer la position: {ex.Message}"; + this.SetErrorStatus($"Impossible de récupérer la position: {ex.Message}"); } finally { @@ -118,26 +118,26 @@ public partial class RdvViewModel : BillingCommandPageViewModel { if (!IsSupported) { - StatusMessage = SupportMessage; + this.SetWarningStatus(SupportMessage); return; } if (!Consent) { - StatusMessage = "Le consentement est requis pour poster la commande."; + this.SetWarningStatus("Le consentement est requis pour poster la commande."); return; } if (string.IsNullOrWhiteSpace(Address)) { - StatusMessage = "L'adresse du rendez-vous est requise."; + this.SetWarningStatus("L'adresse du rendez-vous est requise."); return; } if (string.IsNullOrWhiteSpace(Reason)) { - StatusMessage = "Le motif du rendez-vous est requis."; + this.SetWarningStatus("Le motif du rendez-vous est requis."); return; } @@ -186,17 +186,17 @@ public partial class RdvViewModel : BillingCommandPageViewModel }).ConfigureAwait(true); } - StatusMessage = IsEditingExisting + this.SetInfoStatus(IsEditingExisting ? $"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) { - 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) { - StatusMessage = $"Erreur lors de l'envoi: {ex.Message}"; + this.SetErrorStatus($"Erreur lors de l'envoi: {ex.Message}"); } finally { diff --git a/src/PostIt/PostIt/ViewModels/MainViewModel.cs b/src/PostIt/PostIt/ViewModels/MainViewModel.cs index 2ef6959bc..696470a3f 100644 --- a/src/PostIt/PostIt/ViewModels/MainViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/MainViewModel.cs @@ -12,7 +12,7 @@ using PostIt.Helpers; namespace PostIt.ViewModels; -public partial class MainViewModel : ViewModelBase +public partial class MainViewModel : ViewModelBase, IActionStatusViewModel { /// Window/tab title. Cosmetic — bound by /// MainPage.axaml if at all. Not the post title. @@ -55,16 +55,11 @@ public partial class MainViewModel : ViewModelBase public partial string StatusMessage { get; set; } [ObservableProperty] - public partial StatusNotice ActionStatus { get; set; } = StatusNotice.FromMessage(string.Empty); + public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Pret."); [ObservableProperty] public partial string SearchText { get; set; } - partial void OnStatusMessageChanged(string value) - { - ActionStatus = StatusNotice.FromMessage(value); - } - [ObservableProperty] public partial ObservableCollection Posts { get; set; } @@ -92,7 +87,7 @@ public partial class MainViewModel : ViewModelBase Posts.Add(post); } ApplyFilter(); - StatusMessage = $"Loaded {Posts.Count} posts."; + this.SetInfoStatus($"Loaded {Posts.Count} posts."); }); } @@ -112,7 +107,7 @@ public partial class MainViewModel : ViewModelBase // than to send a request the server will reject. if (string.IsNullOrWhiteSpace(DraftTitle)) { - StatusMessage = "Title is required."; + this.SetWarningStatus("Title is required."); return; } @@ -142,7 +137,7 @@ public partial class MainViewModel : ViewModelBase if (created is not null) { SelectedPost = created; - StatusMessage = $"Created post {created.Id}."; + this.SetInfoStatus($"Created post {created.Id}."); } } else @@ -158,7 +153,7 @@ public partial class MainViewModel : ViewModelBase DateModified = DateTime.UtcNow, }; await BlogClient!.UpdatePostAsync(SelectedPost.Id, update); - StatusMessage = $"Saved post {SelectedPost.Id}."; + this.SetInfoStatus($"Saved post {SelectedPost.Id}."); } await RefreshPostsAsync(); @@ -170,14 +165,14 @@ public partial class MainViewModel : ViewModelBase { if (SelectedPost is null || SelectedPost.Id == 0) { - StatusMessage = "Select an existing post before deleting."; + this.SetWarningStatus("Select an existing post before deleting."); return; } await ExecuteAsync(async () => { await BlogClient!.DeletePostAsync(SelectedPost.Id); - StatusMessage = $"Deleted post {SelectedPost.Id}."; + this.SetInfoStatus($"Deleted post {SelectedPost.Id}."); SelectedPost = null; await RefreshPostsAsync(); }); @@ -202,7 +197,7 @@ public partial class MainViewModel : ViewModelBase { 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; } @@ -219,9 +214,9 @@ public partial class MainViewModel : ViewModelBase // locally flipped state until the round-trip // re-hydrates it. SelectedPost.IsPublished = publish; - StatusMessage = publish + this.SetInfoStatus(publish ? $"Billet {SelectedPost.Id} publié." - : $"Billet {SelectedPost.Id} remis en brouillon."; + : $"Billet {SelectedPost.Id} remis en brouillon."); }); } @@ -255,7 +250,7 @@ public partial class MainViewModel : ViewModelBase { if (SelectedPost is null) { - StatusMessage = "Select an existing post before managing ACL."; + this.SetWarningStatus("Select an existing post before managing ACL."); return; } @@ -354,7 +349,7 @@ public partial class MainViewModel : ViewModelBase FilteredPosts = new ObservableCollection(); SelectedPost = null; IsBusy = false; - StatusMessage = "Ready"; + this.SetInfoStatus("Ready"); Settings = settings ?? new Settings(); SearchText = Settings.SearchText; WindowTitle = "PostIt"; @@ -484,12 +479,12 @@ public partial class MainViewModel : ViewModelBase try { IsBusy = true; - StatusMessage = "Working..."; + this.SetInfoStatus("Working..."); await action(); } catch (Exception ex) { - StatusMessage = $"Error: {ex.Message}"; + this.SetErrorStatus($"Error: {ex.Message}"); } finally { diff --git a/src/PostIt/PostIt/ViewModels/PostAclDialogViewModel.cs b/src/PostIt/PostIt/ViewModels/PostAclDialogViewModel.cs index 994a4bcbd..be1b220fa 100644 --- a/src/PostIt/PostIt/ViewModels/PostAclDialogViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/PostAclDialogViewModel.cs @@ -37,7 +37,7 @@ public sealed class PostAclEntry /// any 403 / 404 will surface as an exception caught by the /// command and routed to . /// -public partial class PostAclDialogViewModel : ViewModelBase +public partial class PostAclDialogViewModel : ViewModelBase, IActionStatusViewModel { private readonly BlogAclApiClient _aclClient; private readonly CircleApiClient _circleClient; @@ -61,15 +61,10 @@ public partial class PostAclDialogViewModel : ViewModelBase public partial bool IsBusy { get; set; } [ObservableProperty] - public partial string StatusMessage { get; set; } = string.Empty; + public partial string StatusMessage { get; set; } = "Pret."; [ObservableProperty] - public partial StatusNotice ActionStatus { get; set; } = StatusNotice.FromMessage(string.Empty); - - partial void OnStatusMessageChanged(string value) - { - ActionStatus = StatusNotice.FromMessage(value); - } + public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Pret."); /// /// Idempotency gate for : the dialog @@ -123,12 +118,12 @@ public partial class PostAclDialogViewModel : ViewModelBase AclEntries = new ObservableCollection(AclEntries.Select(a => ToAclEntry(a.CircleId))); - StatusMessage = $"{AclEntries.Count} autorisation(s)"; + this.SetInfoStatus($"{AclEntries.Count} autorisation(s)"); _loaded = true; } catch (Exception ex) { - StatusMessage = $"Erreur: {ex.Message}"; + this.SetErrorStatus($"Erreur: {ex.Message}"); } finally { @@ -141,7 +136,7 @@ public partial class PostAclDialogViewModel : ViewModelBase { if (SelectedCircleToAdd is null) { - StatusMessage = "Sélectionnez un cercle à ajouter"; + this.SetWarningStatus("Sélectionnez un cercle à ajouter"); return; } @@ -150,7 +145,7 @@ public partial class PostAclDialogViewModel : ViewModelBase { if (AclEntries.Any(a => a.CircleId == SelectedCircleToAdd.Id)) { - StatusMessage = $"Cercle « {SelectedCircleToAdd.Name} » déjà autorisé"; + this.SetWarningStatus($"Cercle « {SelectedCircleToAdd.Name} » déjà autorisé"); return; } @@ -162,11 +157,11 @@ public partial class PostAclDialogViewModel : ViewModelBase if (created is not null) { AclEntries.Add(ToAclEntry(created.CircleId)); - StatusMessage = $"Cercle « {SelectedCircleToAdd.Name} » autorisé"; + this.SetInfoStatus($"Cercle « {SelectedCircleToAdd.Name} » autorisé"); } else { - StatusMessage = "Autorisation refusée par le serveur"; + this.SetWarningStatus("Autorisation refusée par le serveur"); } } catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.Conflict) @@ -174,11 +169,11 @@ public partial class PostAclDialogViewModel : ViewModelBase // Conflict means the link already exists in backend. Resync // from the dedicated ACL API so the UI reflects server truth. await ReloadAclEntriesFromServerAsync(); - StatusMessage = $"Cercle « {SelectedCircleToAdd.Name} » déjà autorisé"; + this.SetWarningStatus($"Cercle « {SelectedCircleToAdd.Name} » déjà autorisé"); } catch (Exception ex) { - StatusMessage = $"Erreur: {ex.Message}"; + this.SetErrorStatus($"Erreur: {ex.Message}"); } finally { @@ -197,11 +192,11 @@ public partial class PostAclDialogViewModel : ViewModelBase var existing = AclEntries.FirstOrDefault(e => e.CircleId == acl.CircleId); if (existing is not null) AclEntries.Remove(existing); - StatusMessage = "Autorisation révoquée"; + this.SetInfoStatus("Autorisation révoquée"); } catch (Exception ex) { - StatusMessage = $"Erreur: {ex.Message}"; + this.SetErrorStatus($"Erreur: {ex.Message}"); } finally { diff --git a/src/PostIt/PostIt/ViewModels/SignaturePageViewModel.cs b/src/PostIt/PostIt/ViewModels/SignaturePageViewModel.cs index 47667bddf..23ba70cf9 100644 --- a/src/PostIt/PostIt/ViewModels/SignaturePageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/SignaturePageViewModel.cs @@ -30,7 +30,7 @@ namespace PostIt.ViewModels; /// until the Yavsc.Org endpoint exists; the contract there will /// be POST /api/signature/{devisId} with this same payload. /// -public partial class SignaturePageViewModel : ViewModelBase +public partial class SignaturePageViewModel : ViewModelBase, IActionStatusViewModel { /// /// Default capture surface, in DIPs. 3:1 ratio matches a @@ -43,12 +43,7 @@ public partial class SignaturePageViewModel : ViewModelBase public partial string StatusMessage { get; set; } = "Prêt."; [ObservableProperty] - public partial StatusNotice ActionStatus { get; set; } = StatusNotice.FromMessage("Prêt."); - - partial void OnStatusMessageChanged(string value) - { - ActionStatus = StatusNotice.FromMessage(value); - } + public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Prêt."); [ObservableProperty] public partial int StrokeCount { get; set; } @@ -115,7 +110,7 @@ public partial class SignaturePageViewModel : ViewModelBase private void OnStrokeCompleted(object? sender, SignaturePadData data) { - StatusMessage = $"Trait terminé. {data.StrokeCount} trait(s)."; + this.SetInfoStatus($"Trait terminé. {data.StrokeCount} trait(s)."); RefreshCounts(); } @@ -133,7 +128,7 @@ public partial class SignaturePageViewModel : ViewModelBase public void Clear() { _control?.Clear(); - StatusMessage = "Effacé."; + this.SetInfoStatus("Effacé."); RefreshCounts(); } @@ -142,14 +137,14 @@ public partial class SignaturePageViewModel : ViewModelBase { if (_control is null) { - StatusMessage = "Contrôle non attaché."; + this.SetWarningStatus("Contrôle non attaché."); return; } var data = _control.Snapshot(); if (data.IsEmpty) { - StatusMessage = "Rien à capturer."; + this.SetWarningStatus("Rien à capturer."); return; } @@ -157,11 +152,11 @@ public partial class SignaturePageViewModel : ViewModelBase { var path = WriteCapture(data); LastCapturedPath = path; - StatusMessage = $"Capture enregistrée: {path}"; + this.SetInfoStatus($"Capture enregistrée: {path}"); } catch (Exception ex) { - StatusMessage = $"Erreur: {ex.Message}"; + this.SetErrorStatus($"Erreur: {ex.Message}"); } await Task.CompletedTask; } diff --git a/src/PostIt/PostIt/ViewModels/StatusNotice.cs b/src/PostIt/PostIt/ViewModels/StatusNotice.cs index 2d14b28b3..972c64350 100644 --- a/src/PostIt/PostIt/ViewModels/StatusNotice.cs +++ b/src/PostIt/PostIt/ViewModels/StatusNotice.cs @@ -32,27 +32,4 @@ public sealed class StatusNotice 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); - - public static StatusNotice FromMessage(string? message) - { - if (string.IsNullOrWhiteSpace(message)) - { - return Info("Pret."); - } - - var text = message.Trim(); - var lower = text.ToLowerInvariant(); - - if (lower.StartsWith("erreur") || lower.StartsWith("echec") || lower.StartsWith("impossible")) - { - return Error(text); - } - - if (lower.Contains("refuse") || lower.Contains("annule") || lower.Contains("obligatoire") || lower.Contains("deja")) - { - return Warning(text); - } - - return Info(text); - } } From 5d94270fd8cb950be11fe1e7c291b4d5e0755d12 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sun, 6 Sep 2026 15:47:01 +0100 Subject: [PATCH 05/67] postit: harmonize main status messages in french --- src/PostIt/PostIt/ViewModels/MainViewModel.cs | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/PostIt/PostIt/ViewModels/MainViewModel.cs b/src/PostIt/PostIt/ViewModels/MainViewModel.cs index 696470a3f..d2667c012 100644 --- a/src/PostIt/PostIt/ViewModels/MainViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/MainViewModel.cs @@ -87,7 +87,7 @@ public partial class MainViewModel : ViewModelBase, IActionStatusViewModel Posts.Add(post); } ApplyFilter(); - this.SetInfoStatus($"Loaded {Posts.Count} posts."); + this.SetInfoStatus($"{Posts.Count} billet(s) chargé(s)."); }); } @@ -107,7 +107,7 @@ public partial class MainViewModel : ViewModelBase, IActionStatusViewModel // than to send a request the server will reject. if (string.IsNullOrWhiteSpace(DraftTitle)) { - this.SetWarningStatus("Title is required."); + this.SetWarningStatus("Le titre est obligatoire."); return; } @@ -137,7 +137,7 @@ public partial class MainViewModel : ViewModelBase, IActionStatusViewModel if (created is not null) { SelectedPost = created; - this.SetInfoStatus($"Created post {created.Id}."); + this.SetInfoStatus($"Billet {created.Id} créé."); } } else @@ -153,7 +153,7 @@ public partial class MainViewModel : ViewModelBase, IActionStatusViewModel DateModified = DateTime.UtcNow, }; await BlogClient!.UpdatePostAsync(SelectedPost.Id, update); - this.SetInfoStatus($"Saved post {SelectedPost.Id}."); + this.SetInfoStatus($"Billet {SelectedPost.Id} enregistré."); } await RefreshPostsAsync(); @@ -165,14 +165,14 @@ public partial class MainViewModel : ViewModelBase, IActionStatusViewModel { if (SelectedPost is null || SelectedPost.Id == 0) { - this.SetWarningStatus("Select an existing post before deleting."); + this.SetWarningStatus("Sélectionnez un billet existant avant suppression."); return; } await ExecuteAsync(async () => { await BlogClient!.DeletePostAsync(SelectedPost.Id); - this.SetInfoStatus($"Deleted post {SelectedPost.Id}."); + this.SetInfoStatus($"Billet {SelectedPost.Id} supprimé."); SelectedPost = null; await RefreshPostsAsync(); }); @@ -250,7 +250,7 @@ public partial class MainViewModel : ViewModelBase, IActionStatusViewModel { if (SelectedPost is null) { - this.SetWarningStatus("Select an existing post before managing ACL."); + this.SetWarningStatus("Sélectionnez un billet existant avant de gérer l'ACL."); return; } @@ -349,7 +349,7 @@ public partial class MainViewModel : ViewModelBase, IActionStatusViewModel FilteredPosts = new ObservableCollection(); SelectedPost = null; IsBusy = false; - this.SetInfoStatus("Ready"); + this.SetInfoStatus("Prêt."); Settings = settings ?? new Settings(); SearchText = Settings.SearchText; WindowTitle = "PostIt"; @@ -479,12 +479,12 @@ public partial class MainViewModel : ViewModelBase, IActionStatusViewModel try { IsBusy = true; - this.SetInfoStatus("Working..."); + this.SetInfoStatus("Traitement en cours..."); await action(); } catch (Exception ex) { - this.SetErrorStatus($"Error: {ex.Message}"); + this.SetErrorStatus($"Erreur: {ex.Message}"); } finally { From a987116eb5c11e90e7914908725a5635c10e9500 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sun, 6 Sep 2026 15:50:40 +0100 Subject: [PATCH 06/67] abstract: enable nullable annotations in legacy files --- src/Yavsc.Abstract/Billing/IBillable.cs | 2 ++ src/Yavsc.Abstract/Blogspot/BlogPostAuthorDto.cs | 2 ++ src/Yavsc.Abstract/Blogspot/BlogPostDto.cs | 2 ++ src/Yavsc.Abstract/Blogspot/IBlogPost.cs | 2 ++ src/Yavsc.Abstract/Chat/ChatHubConstants.cs | 2 ++ src/Yavsc.Abstract/Chat/IChatRoom.cs | 2 ++ src/Yavsc.Abstract/FileSystem/AbstractFileSystemHelpers.cs | 4 +++- src/Yavsc.Abstract/FileSystem/FsOperationInfo.cs | 2 ++ src/Yavsc.Abstract/FileSystem/UserDirectoryInfo.cs | 2 ++ src/Yavsc.Abstract/Google/GDate.cs | 2 ++ .../Google/Messaging/MessageWithPayloadResponse.cs | 2 ++ src/Yavsc.Abstract/IT/Fixing/Bug.cs | 2 ++ src/Yavsc.Abstract/Identity/IApplicationUser.cs | 4 +++- src/Yavsc.Abstract/Identity/UserDisplayHelpers.cs | 2 ++ src/Yavsc.Abstract/Interfaces/Workflow/IBookQueryData.cs | 4 +++- src/Yavsc.Abstract/Messaging/Comment.cs | 2 ++ src/Yavsc.Abstract/Messaging/Notification.cs | 2 ++ src/Yavsc.Abstract/Messaging/RdvQueryEvent.cs | 2 ++ src/Yavsc.Abstract/Messaging/RdvQueryProviderInfo.cs | 2 ++ src/Yavsc.Abstract/Workflow/IMobileDeviceDeclaration.cs | 4 +++- src/Yavsc.Abstract/Workflow/IPerformerProfile.cs | 2 ++ src/Yavsc.Abstract/Workflow/PerformerCodeInputValidation.cs | 2 ++ 22 files changed, 48 insertions(+), 4 deletions(-) diff --git a/src/Yavsc.Abstract/Billing/IBillable.cs b/src/Yavsc.Abstract/Billing/IBillable.cs index 416dc5bee..f936a57df 100644 --- a/src/Yavsc.Abstract/Billing/IBillable.cs +++ b/src/Yavsc.Abstract/Billing/IBillable.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using Yavsc.Services; namespace Yavsc.Billing diff --git a/src/Yavsc.Abstract/Blogspot/BlogPostAuthorDto.cs b/src/Yavsc.Abstract/Blogspot/BlogPostAuthorDto.cs index e332822e1..ab1b3fbe8 100644 --- a/src/Yavsc.Abstract/Blogspot/BlogPostAuthorDto.cs +++ b/src/Yavsc.Abstract/Blogspot/BlogPostAuthorDto.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + namespace Yavsc.Blogspot; /// diff --git a/src/Yavsc.Abstract/Blogspot/BlogPostDto.cs b/src/Yavsc.Abstract/Blogspot/BlogPostDto.cs index 9cb5b1430..bdb2ccdc8 100644 --- a/src/Yavsc.Abstract/Blogspot/BlogPostDto.cs +++ b/src/Yavsc.Abstract/Blogspot/BlogPostDto.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using Yavsc.Abstract.Identity.Security; using System.Text.Json.Serialization; diff --git a/src/Yavsc.Abstract/Blogspot/IBlogPost.cs b/src/Yavsc.Abstract/Blogspot/IBlogPost.cs index 1ef371803..38a50b78f 100644 --- a/src/Yavsc.Abstract/Blogspot/IBlogPost.cs +++ b/src/Yavsc.Abstract/Blogspot/IBlogPost.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + diff --git a/src/Yavsc.Abstract/Chat/ChatHubConstants.cs b/src/Yavsc.Abstract/Chat/ChatHubConstants.cs index b54c00c74..c673e6fae 100644 --- a/src/Yavsc.Abstract/Chat/ChatHubConstants.cs +++ b/src/Yavsc.Abstract/Chat/ChatHubConstants.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + namespace Yavsc.Abstract.Chat { public static class ChatHubConstants diff --git a/src/Yavsc.Abstract/Chat/IChatRoom.cs b/src/Yavsc.Abstract/Chat/IChatRoom.cs index 1d6f68dd5..133ca2837 100644 --- a/src/Yavsc.Abstract/Chat/IChatRoom.cs +++ b/src/Yavsc.Abstract/Chat/IChatRoom.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.ComponentModel.DataAnnotations; namespace Yavsc.Abstract.Chat diff --git a/src/Yavsc.Abstract/FileSystem/AbstractFileSystemHelpers.cs b/src/Yavsc.Abstract/FileSystem/AbstractFileSystemHelpers.cs index dd805864e..14bc86435 100644 --- a/src/Yavsc.Abstract/FileSystem/AbstractFileSystemHelpers.cs +++ b/src/Yavsc.Abstract/FileSystem/AbstractFileSystemHelpers.cs @@ -1,4 +1,6 @@ -using System.Text; +#nullable enable annotations + +using System.Text; using Yavsc.ViewModels.UserFiles; namespace Yavsc.Server.Helpers diff --git a/src/Yavsc.Abstract/FileSystem/FsOperationInfo.cs b/src/Yavsc.Abstract/FileSystem/FsOperationInfo.cs index 76a481492..0e3c0e0c7 100644 --- a/src/Yavsc.Abstract/FileSystem/FsOperationInfo.cs +++ b/src/Yavsc.Abstract/FileSystem/FsOperationInfo.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + namespace Yavsc.Abstract.Helpers { public enum ErrorCode { diff --git a/src/Yavsc.Abstract/FileSystem/UserDirectoryInfo.cs b/src/Yavsc.Abstract/FileSystem/UserDirectoryInfo.cs index fa727d0c0..2ec5dcfaf 100644 --- a/src/Yavsc.Abstract/FileSystem/UserDirectoryInfo.cs +++ b/src/Yavsc.Abstract/FileSystem/UserDirectoryInfo.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using Yavsc.Server.Helpers; namespace Yavsc.ViewModels.UserFiles diff --git a/src/Yavsc.Abstract/Google/GDate.cs b/src/Yavsc.Abstract/Google/GDate.cs index 3506ba416..10e4de92e 100644 --- a/src/Yavsc.Abstract/Google/GDate.cs +++ b/src/Yavsc.Abstract/Google/GDate.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + // // GDate.cs // diff --git a/src/Yavsc.Abstract/Google/Messaging/MessageWithPayloadResponse.cs b/src/Yavsc.Abstract/Google/Messaging/MessageWithPayloadResponse.cs index 59538ca62..980a4abcf 100644 --- a/src/Yavsc.Abstract/Google/Messaging/MessageWithPayloadResponse.cs +++ b/src/Yavsc.Abstract/Google/Messaging/MessageWithPayloadResponse.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + // // MessageWithPayloadResponse.cs // diff --git a/src/Yavsc.Abstract/IT/Fixing/Bug.cs b/src/Yavsc.Abstract/IT/Fixing/Bug.cs index f0b403bb7..60bd155f6 100644 --- a/src/Yavsc.Abstract/IT/Fixing/Bug.cs +++ b/src/Yavsc.Abstract/IT/Fixing/Bug.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Yavsc.Attributes.Validation; diff --git a/src/Yavsc.Abstract/Identity/IApplicationUser.cs b/src/Yavsc.Abstract/Identity/IApplicationUser.cs index 5d1d5b1ca..0b8e1047c 100644 --- a/src/Yavsc.Abstract/Identity/IApplicationUser.cs +++ b/src/Yavsc.Abstract/Identity/IApplicationUser.cs @@ -1,4 +1,6 @@ -namespace Yavsc.Abstract.Identity +#nullable enable annotations + +namespace Yavsc.Abstract.Identity { public interface IApplicationUser { diff --git a/src/Yavsc.Abstract/Identity/UserDisplayHelpers.cs b/src/Yavsc.Abstract/Identity/UserDisplayHelpers.cs index 242615527..4277d6e3b 100644 --- a/src/Yavsc.Abstract/Identity/UserDisplayHelpers.cs +++ b/src/Yavsc.Abstract/Identity/UserDisplayHelpers.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + namespace Yavsc.Abstract.Identity { /// diff --git a/src/Yavsc.Abstract/Interfaces/Workflow/IBookQueryData.cs b/src/Yavsc.Abstract/Interfaces/Workflow/IBookQueryData.cs index 2c844f925..eb3dee591 100644 --- a/src/Yavsc.Abstract/Interfaces/Workflow/IBookQueryData.cs +++ b/src/Yavsc.Abstract/Interfaces/Workflow/IBookQueryData.cs @@ -1,4 +1,6 @@ -using Yavsc.Abstract.Identity; +#nullable enable annotations + +using Yavsc.Abstract.Identity; namespace Yavsc.Interfaces { diff --git a/src/Yavsc.Abstract/Messaging/Comment.cs b/src/Yavsc.Abstract/Messaging/Comment.cs index 3b8702ae1..d8eef456c 100644 --- a/src/Yavsc.Abstract/Messaging/Comment.cs +++ b/src/Yavsc.Abstract/Messaging/Comment.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using Yavsc.Interfaces; diff --git a/src/Yavsc.Abstract/Messaging/Notification.cs b/src/Yavsc.Abstract/Messaging/Notification.cs index dbbf735d5..f7b35b48b 100644 --- a/src/Yavsc.Abstract/Messaging/Notification.cs +++ b/src/Yavsc.Abstract/Messaging/Notification.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; diff --git a/src/Yavsc.Abstract/Messaging/RdvQueryEvent.cs b/src/Yavsc.Abstract/Messaging/RdvQueryEvent.cs index b2168bd7c..9e2ecb754 100644 --- a/src/Yavsc.Abstract/Messaging/RdvQueryEvent.cs +++ b/src/Yavsc.Abstract/Messaging/RdvQueryEvent.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + // // BookQueryEvent.cs // diff --git a/src/Yavsc.Abstract/Messaging/RdvQueryProviderInfo.cs b/src/Yavsc.Abstract/Messaging/RdvQueryProviderInfo.cs index 87125c544..94eeb5ab9 100644 --- a/src/Yavsc.Abstract/Messaging/RdvQueryProviderInfo.cs +++ b/src/Yavsc.Abstract/Messaging/RdvQueryProviderInfo.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using Yavsc.Abstract.Identity; using Yavsc.Models.Relationship; diff --git a/src/Yavsc.Abstract/Workflow/IMobileDeviceDeclaration.cs b/src/Yavsc.Abstract/Workflow/IMobileDeviceDeclaration.cs index 6e55ebe51..7a1dbc261 100644 --- a/src/Yavsc.Abstract/Workflow/IMobileDeviceDeclaration.cs +++ b/src/Yavsc.Abstract/Workflow/IMobileDeviceDeclaration.cs @@ -1,4 +1,6 @@ -// Copyright (C) 2016 Paul Schneider +#nullable enable annotations + +// Copyright (C) 2016 Paul Schneider // // This file is part of yavsc. // diff --git a/src/Yavsc.Abstract/Workflow/IPerformerProfile.cs b/src/Yavsc.Abstract/Workflow/IPerformerProfile.cs index 4314dd371..606285a6c 100644 --- a/src/Yavsc.Abstract/Workflow/IPerformerProfile.cs +++ b/src/Yavsc.Abstract/Workflow/IPerformerProfile.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + namespace Yavsc.Workflow { public interface IPerformerProfile diff --git a/src/Yavsc.Abstract/Workflow/PerformerCodeInputValidation.cs b/src/Yavsc.Abstract/Workflow/PerformerCodeInputValidation.cs index 84e9c1cc7..4ed60e465 100644 --- a/src/Yavsc.Abstract/Workflow/PerformerCodeInputValidation.cs +++ b/src/Yavsc.Abstract/Workflow/PerformerCodeInputValidation.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; From 0ba44c21e7ea1f4bb2956fa5f56d1282f20cdb10 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sun, 6 Sep 2026 16:11:37 +0100 Subject: [PATCH 07/67] server: enable nullable annotations in legacy files --- src/Yavsc.Server/Config.cs | 2 ++ src/Yavsc.Server/Constants.cs | 2 ++ src/Yavsc.Server/Exceptions/AuthorizationFailureException.cs | 2 ++ src/Yavsc.Server/Exceptions/YavscInfrastructureException.cs | 2 ++ src/Yavsc.Server/Helpers/BillingHelpers.cs | 2 ++ src/Yavsc.Server/Helpers/EstimateSignatureFileHelper.cs | 2 ++ src/Yavsc.Server/Helpers/FileSystemHelpers.cs | 2 ++ src/Yavsc.Server/Helpers/HtmlHelpers.cs | 2 ++ src/Yavsc.Server/Helpers/PayPalHelpers.cs | 2 ++ src/Yavsc.Server/Helpers/RequestHelper.cs | 2 ++ src/Yavsc.Server/Helpers/ServiceExtensions.cs | 2 ++ src/Yavsc.Server/Helpers/UserHelpers.cs | 2 ++ src/Yavsc.Server/Hubs/ChatHub.cs | 2 ++ src/Yavsc.Server/Hubs/HubInputValidator.cs | 2 ++ src/Yavsc.Server/Models/Access/GrantViewModel.cs | 2 ++ src/Yavsc.Server/Models/ApplicationUser.cs | 2 ++ src/Yavsc.Server/Models/Auth/DeviceDeclaration.cs | 2 ++ src/Yavsc.Server/Models/Bank/BankIdentity.cs | 2 ++ src/Yavsc.Server/Models/Billing/Estimate.cs | 2 ++ src/Yavsc.Server/Models/Billing/NominativeServiceCommand.cs | 2 ++ src/Yavsc.Server/Models/Billing/histoestim.cs | 2 ++ src/Yavsc.Server/Models/Blog/BlogPost.cs | 2 ++ src/Yavsc.Server/Models/Blog/Comment.cs | 2 ++ src/Yavsc.Server/Models/Calendar/Period.cs | 2 ++ src/Yavsc.Server/Models/ErrorViewModel.cs | 2 ++ src/Yavsc.Server/Models/HairCut/BrusherProfile.cs | 2 ++ src/Yavsc.Server/Models/HairCut/HairCutPaymentEvent.cs | 2 ++ src/Yavsc.Server/Models/HairCut/HairCutQuery.cs | 2 ++ src/Yavsc.Server/Models/HairCut/HairCutQueryEvent.cs | 2 ++ src/Yavsc.Server/Models/HairCut/HairMultiCutQuery.cs | 2 ++ src/Yavsc.Server/Models/HairCut/HairPrestation.cs | 2 ++ src/Yavsc.Server/Models/HairCut/Views/HaircutQueryInfo.cs | 2 ++ src/Yavsc.Server/Models/IT/SourceCode/GitClone.cs | 2 ++ src/Yavsc.Server/Models/IT/SourceCode/ProjectBuild.cs | 2 ++ src/Yavsc.Server/Models/IT/SourceCode/SingleCmdProjectBatch.cs | 2 ++ src/Yavsc.Server/Models/IdentityUserLogin.cs | 2 ++ src/Yavsc.Server/Models/Kyc/TrustDeclaration.cs | 2 ++ src/Yavsc.Server/Models/Kyc/TrustToken.cs | 2 ++ src/Yavsc.Server/Models/Market/Product.cs | 2 ++ src/Yavsc.Server/Models/Relationship/StaticContact.cs | 2 ++ src/Yavsc.Server/Models/Workflow/Activity.cs | 2 ++ src/Yavsc.Server/Models/Workflow/PerformerProfile.cs | 2 ++ src/Yavsc.Server/Models/Workflow/RdvQuery.cs | 2 ++ src/Yavsc.Server/Models/societe.com/CompanyInfo.cs | 2 ++ src/Yavsc.Server/Services/BlogSpotService.cs | 2 ++ src/Yavsc.Server/Services/ClaudeModerationService.cs | 2 ++ src/Yavsc.Server/Services/LiveProcessor.cs | 2 ++ src/Yavsc.Server/Services/MailSender.cs | 2 ++ src/Yavsc.Server/Services/PermissionHandler.cs | 2 ++ src/Yavsc.Server/Services/ProfileService.cs | 2 ++ src/Yavsc.Server/Settings/SiteSettings.cs | 2 ++ src/Yavsc.Server/ViewModels/Account/ForgotPasswordViewModel.cs | 2 ++ src/Yavsc.Server/ViewModels/Account/SignInModel.cs | 2 ++ src/Yavsc.Server/ViewModels/Account/UnregisterViewModel.cs | 2 ++ src/Yavsc.Server/ViewModels/Account/VerifyCodeViewModel.cs | 2 ++ 55 files changed, 110 insertions(+) mode change 100755 => 100644 src/Yavsc.Server/ViewModels/Account/SignInModel.cs diff --git a/src/Yavsc.Server/Config.cs b/src/Yavsc.Server/Config.cs index 5d2bcdffb..e68546eff 100644 --- a/src/Yavsc.Server/Config.cs +++ b/src/Yavsc.Server/Config.cs @@ -1,3 +1,5 @@ +#nullable enable annotations +  using IdentityServer8; using IdentityServer8.Models; diff --git a/src/Yavsc.Server/Constants.cs b/src/Yavsc.Server/Constants.cs index 4ded48eae..8859e5e69 100644 --- a/src/Yavsc.Server/Constants.cs +++ b/src/Yavsc.Server/Constants.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + namespace Yavsc.Server { diff --git a/src/Yavsc.Server/Exceptions/AuthorizationFailureException.cs b/src/Yavsc.Server/Exceptions/AuthorizationFailureException.cs index a3c5105ec..4a588dfd9 100644 --- a/src/Yavsc.Server/Exceptions/AuthorizationFailureException.cs +++ b/src/Yavsc.Server/Exceptions/AuthorizationFailureException.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + namespace Yavsc.Server.Exceptions; [Serializable] diff --git a/src/Yavsc.Server/Exceptions/YavscInfrastructureException.cs b/src/Yavsc.Server/Exceptions/YavscInfrastructureException.cs index 7888970c5..583872414 100644 --- a/src/Yavsc.Server/Exceptions/YavscInfrastructureException.cs +++ b/src/Yavsc.Server/Exceptions/YavscInfrastructureException.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + namespace Yavsc.Services { [Serializable] diff --git a/src/Yavsc.Server/Helpers/BillingHelpers.cs b/src/Yavsc.Server/Helpers/BillingHelpers.cs index c10a76155..789b85a96 100644 --- a/src/Yavsc.Server/Helpers/BillingHelpers.cs +++ b/src/Yavsc.Server/Helpers/BillingHelpers.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.Globalization; using Yavsc.Billing; using Yavsc.Models.Billing; diff --git a/src/Yavsc.Server/Helpers/EstimateSignatureFileHelper.cs b/src/Yavsc.Server/Helpers/EstimateSignatureFileHelper.cs index e2d40266d..8545c3a0a 100644 --- a/src/Yavsc.Server/Helpers/EstimateSignatureFileHelper.cs +++ b/src/Yavsc.Server/Helpers/EstimateSignatureFileHelper.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.Security.Claims; using System.Text; using System.Text.Json; diff --git a/src/Yavsc.Server/Helpers/FileSystemHelpers.cs b/src/Yavsc.Server/Helpers/FileSystemHelpers.cs index 7d9d86ed0..29ada6b77 100644 --- a/src/Yavsc.Server/Helpers/FileSystemHelpers.cs +++ b/src/Yavsc.Server/Helpers/FileSystemHelpers.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.Security.Claims; diff --git a/src/Yavsc.Server/Helpers/HtmlHelpers.cs b/src/Yavsc.Server/Helpers/HtmlHelpers.cs index 213ea369a..c23f05cd2 100644 --- a/src/Yavsc.Server/Helpers/HtmlHelpers.cs +++ b/src/Yavsc.Server/Helpers/HtmlHelpers.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Http; using Yavsc.Models.Drawing; diff --git a/src/Yavsc.Server/Helpers/PayPalHelpers.cs b/src/Yavsc.Server/Helpers/PayPalHelpers.cs index 9d4074d46..51902c784 100644 --- a/src/Yavsc.Server/Helpers/PayPalHelpers.cs +++ b/src/Yavsc.Server/Helpers/PayPalHelpers.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using Microsoft.Extensions.Logging; using Yavsc.Models.Billing; using Microsoft.AspNetCore.Http; diff --git a/src/Yavsc.Server/Helpers/RequestHelper.cs b/src/Yavsc.Server/Helpers/RequestHelper.cs index 99fe15248..6b85a5c31 100644 --- a/src/Yavsc.Server/Helpers/RequestHelper.cs +++ b/src/Yavsc.Server/Helpers/RequestHelper.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.Net; using System.Net.Http.Headers; using Yavsc.Server.Model; diff --git a/src/Yavsc.Server/Helpers/ServiceExtensions.cs b/src/Yavsc.Server/Helpers/ServiceExtensions.cs index 06e877be8..1a69ca42f 100644 --- a/src/Yavsc.Server/Helpers/ServiceExtensions.cs +++ b/src/Yavsc.Server/Helpers/ServiceExtensions.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.Extensions.Configuration; diff --git a/src/Yavsc.Server/Helpers/UserHelpers.cs b/src/Yavsc.Server/Helpers/UserHelpers.cs index c3ee708d6..f0a30995f 100644 --- a/src/Yavsc.Server/Helpers/UserHelpers.cs +++ b/src/Yavsc.Server/Helpers/UserHelpers.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using Microsoft.EntityFrameworkCore; using System.Security.Claims; using Yavsc.Models; diff --git a/src/Yavsc.Server/Hubs/ChatHub.cs b/src/Yavsc.Server/Hubs/ChatHub.cs index 4a99b507c..799f7441c 100644 --- a/src/Yavsc.Server/Hubs/ChatHub.cs +++ b/src/Yavsc.Server/Hubs/ChatHub.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + // // ChatHub.cs // diff --git a/src/Yavsc.Server/Hubs/HubInputValidator.cs b/src/Yavsc.Server/Hubs/HubInputValidator.cs index a6acac5ac..a2382c11e 100644 --- a/src/Yavsc.Server/Hubs/HubInputValidator.cs +++ b/src/Yavsc.Server/Hubs/HubInputValidator.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + // // ChatHub.cs // diff --git a/src/Yavsc.Server/Models/Access/GrantViewModel.cs b/src/Yavsc.Server/Models/Access/GrantViewModel.cs index d9d0e1562..d0d379caa 100644 --- a/src/Yavsc.Server/Models/Access/GrantViewModel.cs +++ b/src/Yavsc.Server/Models/Access/GrantViewModel.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + // 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. diff --git a/src/Yavsc.Server/Models/ApplicationUser.cs b/src/Yavsc.Server/Models/ApplicationUser.cs index 355e0ad15..69fbf1e52 100644 --- a/src/Yavsc.Server/Models/ApplicationUser.cs +++ b/src/Yavsc.Server/Models/ApplicationUser.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Newtonsoft.Json; diff --git a/src/Yavsc.Server/Models/Auth/DeviceDeclaration.cs b/src/Yavsc.Server/Models/Auth/DeviceDeclaration.cs index 1db1d89e0..7ed5e9b0d 100644 --- a/src/Yavsc.Server/Models/Auth/DeviceDeclaration.cs +++ b/src/Yavsc.Server/Models/Auth/DeviceDeclaration.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Newtonsoft.Json; diff --git a/src/Yavsc.Server/Models/Bank/BankIdentity.cs b/src/Yavsc.Server/Models/Bank/BankIdentity.cs index eea65d691..092059acc 100644 --- a/src/Yavsc.Server/Models/Bank/BankIdentity.cs +++ b/src/Yavsc.Server/Models/Bank/BankIdentity.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; diff --git a/src/Yavsc.Server/Models/Billing/Estimate.cs b/src/Yavsc.Server/Models/Billing/Estimate.cs index e6495a140..24cd021a8 100644 --- a/src/Yavsc.Server/Models/Billing/Estimate.cs +++ b/src/Yavsc.Server/Models/Billing/Estimate.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; diff --git a/src/Yavsc.Server/Models/Billing/NominativeServiceCommand.cs b/src/Yavsc.Server/Models/Billing/NominativeServiceCommand.cs index ad651d368..aa9e06abf 100644 --- a/src/Yavsc.Server/Models/Billing/NominativeServiceCommand.cs +++ b/src/Yavsc.Server/Models/Billing/NominativeServiceCommand.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; diff --git a/src/Yavsc.Server/Models/Billing/histoestim.cs b/src/Yavsc.Server/Models/Billing/histoestim.cs index 1f9b99f1f..df2860f5d 100644 --- a/src/Yavsc.Server/Models/Billing/histoestim.cs +++ b/src/Yavsc.Server/Models/Billing/histoestim.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + namespace Yavsc.Models.Billing { public partial class histoestim diff --git a/src/Yavsc.Server/Models/Blog/BlogPost.cs b/src/Yavsc.Server/Models/Blog/BlogPost.cs index 4c2f2ae5c..6dc8ff750 100644 --- a/src/Yavsc.Server/Models/Blog/BlogPost.cs +++ b/src/Yavsc.Server/Models/Blog/BlogPost.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Newtonsoft.Json; diff --git a/src/Yavsc.Server/Models/Blog/Comment.cs b/src/Yavsc.Server/Models/Blog/Comment.cs index 4d39d0c2e..5d7cc2912 100644 --- a/src/Yavsc.Server/Models/Blog/Comment.cs +++ b/src/Yavsc.Server/Models/Blog/Comment.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Newtonsoft.Json; diff --git a/src/Yavsc.Server/Models/Calendar/Period.cs b/src/Yavsc.Server/Models/Calendar/Period.cs index dfc285cf3..f333235b1 100644 --- a/src/Yavsc.Server/Models/Calendar/Period.cs +++ b/src/Yavsc.Server/Models/Calendar/Period.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + // // Period.cs // diff --git a/src/Yavsc.Server/Models/ErrorViewModel.cs b/src/Yavsc.Server/Models/ErrorViewModel.cs index 178194769..087aa505b 100644 --- a/src/Yavsc.Server/Models/ErrorViewModel.cs +++ b/src/Yavsc.Server/Models/ErrorViewModel.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + namespace Yavsc.Models; public class ErrorViewModel diff --git a/src/Yavsc.Server/Models/HairCut/BrusherProfile.cs b/src/Yavsc.Server/Models/HairCut/BrusherProfile.cs index ba47bfdce..d89a56fa8 100644 --- a/src/Yavsc.Server/Models/HairCut/BrusherProfile.cs +++ b/src/Yavsc.Server/Models/HairCut/BrusherProfile.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + // // BrusherProfile.cs diff --git a/src/Yavsc.Server/Models/HairCut/HairCutPaymentEvent.cs b/src/Yavsc.Server/Models/HairCut/HairCutPaymentEvent.cs index 353249288..2c96a7d80 100644 --- a/src/Yavsc.Server/Models/HairCut/HairCutPaymentEvent.cs +++ b/src/Yavsc.Server/Models/HairCut/HairCutPaymentEvent.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using Microsoft.Extensions.Localization; using Yavsc.Interfaces.Workflow; diff --git a/src/Yavsc.Server/Models/HairCut/HairCutQuery.cs b/src/Yavsc.Server/Models/HairCut/HairCutQuery.cs index 0960db6d6..680cf6956 100644 --- a/src/Yavsc.Server/Models/HairCut/HairCutQuery.cs +++ b/src/Yavsc.Server/Models/HairCut/HairCutQuery.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Yavsc.Models.Billing; diff --git a/src/Yavsc.Server/Models/HairCut/HairCutQueryEvent.cs b/src/Yavsc.Server/Models/HairCut/HairCutQueryEvent.cs index bd30fb784..fadc353a8 100644 --- a/src/Yavsc.Server/Models/HairCut/HairCutQueryEvent.cs +++ b/src/Yavsc.Server/Models/HairCut/HairCutQueryEvent.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using Yavsc.Interfaces.Workflow; namespace Yavsc.Models.Haircut diff --git a/src/Yavsc.Server/Models/HairCut/HairMultiCutQuery.cs b/src/Yavsc.Server/Models/HairCut/HairMultiCutQuery.cs index 21ae437ce..beb7da9ac 100644 --- a/src/Yavsc.Server/Models/HairCut/HairMultiCutQuery.cs +++ b/src/Yavsc.Server/Models/HairCut/HairMultiCutQuery.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Yavsc.Models.Billing; diff --git a/src/Yavsc.Server/Models/HairCut/HairPrestation.cs b/src/Yavsc.Server/Models/HairCut/HairPrestation.cs index 6153f6483..2e2cf8ca6 100644 --- a/src/Yavsc.Server/Models/HairCut/HairPrestation.cs +++ b/src/Yavsc.Server/Models/HairCut/HairPrestation.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Reflection; diff --git a/src/Yavsc.Server/Models/HairCut/Views/HaircutQueryInfo.cs b/src/Yavsc.Server/Models/HairCut/Views/HaircutQueryInfo.cs index c9213862e..4099dbcaa 100644 --- a/src/Yavsc.Server/Models/HairCut/Views/HaircutQueryInfo.cs +++ b/src/Yavsc.Server/Models/HairCut/Views/HaircutQueryInfo.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + // // HaircutQueryInfo.cs diff --git a/src/Yavsc.Server/Models/IT/SourceCode/GitClone.cs b/src/Yavsc.Server/Models/IT/SourceCode/GitClone.cs index 826e5de38..d58551a65 100644 --- a/src/Yavsc.Server/Models/IT/SourceCode/GitClone.cs +++ b/src/Yavsc.Server/Models/IT/SourceCode/GitClone.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + // // GitClone.cs // /* // paul 21/06/2018 11:27 20182018 6 21 diff --git a/src/Yavsc.Server/Models/IT/SourceCode/ProjectBuild.cs b/src/Yavsc.Server/Models/IT/SourceCode/ProjectBuild.cs index f65b17b51..eb1afe214 100644 --- a/src/Yavsc.Server/Models/IT/SourceCode/ProjectBuild.cs +++ b/src/Yavsc.Server/Models/IT/SourceCode/ProjectBuild.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.Diagnostics; namespace Yavsc.Server.Models.IT.SourceCode diff --git a/src/Yavsc.Server/Models/IT/SourceCode/SingleCmdProjectBatch.cs b/src/Yavsc.Server/Models/IT/SourceCode/SingleCmdProjectBatch.cs index 2ce162564..0fb2116f5 100644 --- a/src/Yavsc.Server/Models/IT/SourceCode/SingleCmdProjectBatch.cs +++ b/src/Yavsc.Server/Models/IT/SourceCode/SingleCmdProjectBatch.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.Diagnostics; namespace Yavsc.Server.Models.IT.SourceCode diff --git a/src/Yavsc.Server/Models/IdentityUserLogin.cs b/src/Yavsc.Server/Models/IdentityUserLogin.cs index bfbd4e899..78567f68f 100644 --- a/src/Yavsc.Server/Models/IdentityUserLogin.cs +++ b/src/Yavsc.Server/Models/IdentityUserLogin.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + namespace Yavsc.Models.Auth { using System.ComponentModel.DataAnnotations.Schema; diff --git a/src/Yavsc.Server/Models/Kyc/TrustDeclaration.cs b/src/Yavsc.Server/Models/Kyc/TrustDeclaration.cs index 0a97eb6a9..fe9fc2ec4 100644 --- a/src/Yavsc.Server/Models/Kyc/TrustDeclaration.cs +++ b/src/Yavsc.Server/Models/Kyc/TrustDeclaration.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + // Yavsc.Models.Kyc/TrustDeclaration.cs namespace Yavsc.Models.Kyc { diff --git a/src/Yavsc.Server/Models/Kyc/TrustToken.cs b/src/Yavsc.Server/Models/Kyc/TrustToken.cs index 2e240bae1..8c09d39cd 100644 --- a/src/Yavsc.Server/Models/Kyc/TrustToken.cs +++ b/src/Yavsc.Server/Models/Kyc/TrustToken.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + // Yavsc.Models.Kyc/TrustToken.cs namespace Yavsc.Models.Kyc { diff --git a/src/Yavsc.Server/Models/Market/Product.cs b/src/Yavsc.Server/Models/Market/Product.cs index ae8f29199..84f5709ca 100644 --- a/src/Yavsc.Server/Models/Market/Product.cs +++ b/src/Yavsc.Server/Models/Market/Product.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.ComponentModel.DataAnnotations; diff --git a/src/Yavsc.Server/Models/Relationship/StaticContact.cs b/src/Yavsc.Server/Models/Relationship/StaticContact.cs index 7ae6ab6ae..05ebf04da 100644 --- a/src/Yavsc.Server/Models/Relationship/StaticContact.cs +++ b/src/Yavsc.Server/Models/Relationship/StaticContact.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + namespace Yavsc.Models.Relationship { diff --git a/src/Yavsc.Server/Models/Workflow/Activity.cs b/src/Yavsc.Server/Models/Workflow/Activity.cs index 0f813a273..e3303f5ac 100644 --- a/src/Yavsc.Server/Models/Workflow/Activity.cs +++ b/src/Yavsc.Server/Models/Workflow/Activity.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Newtonsoft.Json; diff --git a/src/Yavsc.Server/Models/Workflow/PerformerProfile.cs b/src/Yavsc.Server/Models/Workflow/PerformerProfile.cs index 23bd688b4..c2f312b84 100644 --- a/src/Yavsc.Server/Models/Workflow/PerformerProfile.cs +++ b/src/Yavsc.Server/Models/Workflow/PerformerProfile.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; diff --git a/src/Yavsc.Server/Models/Workflow/RdvQuery.cs b/src/Yavsc.Server/Models/Workflow/RdvQuery.cs index f821fc75d..cd56f3676 100644 --- a/src/Yavsc.Server/Models/Workflow/RdvQuery.cs +++ b/src/Yavsc.Server/Models/Workflow/RdvQuery.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; diff --git a/src/Yavsc.Server/Models/societe.com/CompanyInfo.cs b/src/Yavsc.Server/Models/societe.com/CompanyInfo.cs index 114c4d8e3..354bc4861 100644 --- a/src/Yavsc.Server/Models/societe.com/CompanyInfo.cs +++ b/src/Yavsc.Server/Models/societe.com/CompanyInfo.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.ComponentModel.DataAnnotations; diff --git a/src/Yavsc.Server/Services/BlogSpotService.cs b/src/Yavsc.Server/Services/BlogSpotService.cs index a08326303..20f7245e5 100644 --- a/src/Yavsc.Server/Services/BlogSpotService.cs +++ b/src/Yavsc.Server/Services/BlogSpotService.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.Diagnostics; using System.Security.Claims; using Microsoft.AspNetCore.Authorization; diff --git a/src/Yavsc.Server/Services/ClaudeModerationService.cs b/src/Yavsc.Server/Services/ClaudeModerationService.cs index a510e55cb..a47952318 100644 --- a/src/Yavsc.Server/Services/ClaudeModerationService.cs +++ b/src/Yavsc.Server/Services/ClaudeModerationService.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using Yavsc.Moderation; using Yavsc.Abstract.Interfaces; using Anthropic.SDK; diff --git a/src/Yavsc.Server/Services/LiveProcessor.cs b/src/Yavsc.Server/Services/LiveProcessor.cs index f10a8201a..560ee6d0a 100644 --- a/src/Yavsc.Server/Services/LiveProcessor.cs +++ b/src/Yavsc.Server/Services/LiveProcessor.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.Collections.Concurrent; using System.Net.WebSockets; using Yavsc.Models; diff --git a/src/Yavsc.Server/Services/MailSender.cs b/src/Yavsc.Server/Services/MailSender.cs index 592a43ba6..81518eddb 100644 --- a/src/Yavsc.Server/Services/MailSender.cs +++ b/src/Yavsc.Server/Services/MailSender.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using MailKit.Net.Smtp; using MailKit.Security; using Microsoft.Extensions.Logging; diff --git a/src/Yavsc.Server/Services/PermissionHandler.cs b/src/Yavsc.Server/Services/PermissionHandler.cs index 6848070ac..77ee9fd57 100644 --- a/src/Yavsc.Server/Services/PermissionHandler.cs +++ b/src/Yavsc.Server/Services/PermissionHandler.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.Security.Claims; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; diff --git a/src/Yavsc.Server/Services/ProfileService.cs b/src/Yavsc.Server/Services/ProfileService.cs index b6da3a568..3b7b5121a 100644 --- a/src/Yavsc.Server/Services/ProfileService.cs +++ b/src/Yavsc.Server/Services/ProfileService.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.Security.Claims; using IdentityModel; using IdentityServer8.Models; diff --git a/src/Yavsc.Server/Settings/SiteSettings.cs b/src/Yavsc.Server/Settings/SiteSettings.cs index ef74781de..3d604f79f 100644 --- a/src/Yavsc.Server/Settings/SiteSettings.cs +++ b/src/Yavsc.Server/Settings/SiteSettings.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using Yavsc.Models.Relationship; namespace Yavsc diff --git a/src/Yavsc.Server/ViewModels/Account/ForgotPasswordViewModel.cs b/src/Yavsc.Server/ViewModels/Account/ForgotPasswordViewModel.cs index 6af77fe4d..903d4c8b3 100644 --- a/src/Yavsc.Server/ViewModels/Account/ForgotPasswordViewModel.cs +++ b/src/Yavsc.Server/ViewModels/Account/ForgotPasswordViewModel.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.ComponentModel.DataAnnotations; diff --git a/src/Yavsc.Server/ViewModels/Account/SignInModel.cs b/src/Yavsc.Server/ViewModels/Account/SignInModel.cs old mode 100755 new mode 100644 index d2aa69ad2..6375c40fe --- a/src/Yavsc.Server/ViewModels/Account/SignInModel.cs +++ b/src/Yavsc.Server/ViewModels/Account/SignInModel.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.ComponentModel.DataAnnotations; namespace Yavsc.ViewModels.Account diff --git a/src/Yavsc.Server/ViewModels/Account/UnregisterViewModel.cs b/src/Yavsc.Server/ViewModels/Account/UnregisterViewModel.cs index e28fcfed8..e08330440 100644 --- a/src/Yavsc.Server/ViewModels/Account/UnregisterViewModel.cs +++ b/src/Yavsc.Server/ViewModels/Account/UnregisterViewModel.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.ComponentModel.DataAnnotations; namespace Yavsc.ViewModels.Account diff --git a/src/Yavsc.Server/ViewModels/Account/VerifyCodeViewModel.cs b/src/Yavsc.Server/ViewModels/Account/VerifyCodeViewModel.cs index a768e249f..5252ff4f6 100644 --- a/src/Yavsc.Server/ViewModels/Account/VerifyCodeViewModel.cs +++ b/src/Yavsc.Server/ViewModels/Account/VerifyCodeViewModel.cs @@ -1,3 +1,5 @@ +#nullable enable annotations + using System.ComponentModel.DataAnnotations; namespace Yavsc.ViewModels.Account From 148a3aa271535f664d6263a87f9433a71d1b0daa Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sun, 6 Sep 2026 16:20:17 +0100 Subject: [PATCH 08/67] postit: harden oidc settings defaults on startup --- .../PostIt/ViewModels/Settings/Settings.cs | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs index b59ef9933..9547fb4f3 100644 --- a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs +++ b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs @@ -123,6 +123,8 @@ public partial class Settings : ViewModelBase // build options from a torn read. lock (_mutationGate) { + EnsureAuthenticationDefaultsLocked(); + var options = new OidcClientOptions { Authority = Authentication.Authority, @@ -151,6 +153,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(); + } + /// /// Scopes the PostIt client always requires from the OIDC provider, /// regardless of what the user has in their settings file. @@ -334,11 +355,13 @@ public partial class Settings : ViewModelBase AuthenticationSettings.DesktopRedirectUri : settings.Authentication.RedirectUri; if (settings.Authentication.Scopes is null || settings.Authentication.Scopes.Length == 0) { - settings.Authentication.Scopes = AuthenticationSettings.DefaultScopes; + this.Authentication.Scopes = AuthenticationSettings.DefaultScopes; } else this.Authentication.Scopes = settings.Authentication.Scopes; } + + EnsureAuthenticationDefaultsLocked(); } // A disk load (or an embedded-resource fallback) is the // baseline, not a user edit. Clear the dirty flag last From 66614ef2e1e8f503eb1a1963a018f14a3822105e Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sun, 6 Sep 2026 16:24:46 +0100 Subject: [PATCH 09/67] postit: ignore runtime status in settings json --- src/PostIt/PostIt/ViewModels/Settings/Settings.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs index 9547fb4f3..0864c1416 100644 --- a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs +++ b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs @@ -7,6 +7,7 @@ using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Text.Json; +using System.Text.Json.Serialization; [assembly: InternalsVisibleTo("PostIt.Tests")] @@ -32,6 +33,7 @@ public partial class Settings : ViewModelBase 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) From 3488abc7fdf1a182309cc6af6ff832f1c2a03576 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sun, 6 Sep 2026 16:32:59 +0100 Subject: [PATCH 10/67] postit-tests: lock first-load settings regression --- src/PostIt/PostIt.Tests/SettingsLoadTests.cs | 47 ++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/src/PostIt/PostIt.Tests/SettingsLoadTests.cs b/src/PostIt/PostIt.Tests/SettingsLoadTests.cs index 3f8dc02b9..069b6ac96 100644 --- a/src/PostIt/PostIt.Tests/SettingsLoadTests.cs +++ b/src/PostIt/PostIt.Tests/SettingsLoadTests.cs @@ -173,4 +173,51 @@ public class SettingsLoadTests Assert.NotNull(roundTrip); Assert.Equal("bonjour", roundTrip.SearchText); } + + /// + /// First-start regression guard: older settings payloads can + /// still contain ActionStatus from a previous write. This + /// runtime-only UI state must not be persisted anymore and must + /// not break deserialization when present. + /// + [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(legacyPayload); + + Assert.NotNull(roundTrip); + Assert.Equal("hello", roundTrip.SearchText); + } } From 2ede36cb8fd87f4c710f362998c9009ea910e8ba Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sun, 6 Sep 2026 16:58:39 +0100 Subject: [PATCH 11/67] postit: add mapsui location picker to rdv form --- src/PostIt/Directory.Packages.props | 2 + .../BillingCommandPageViewModelTests.cs | 20 ++++++ src/PostIt/PostIt/PostIt.csproj | 2 + .../ViewModels/Commands/RdvViewModel.cs | 14 ++++ .../PostIt/Views/Commands/RdvPage.axaml | 12 +++- .../PostIt/Views/Commands/RdvPage.axaml.cs | 65 +++++++++++++++++++ 6 files changed, 114 insertions(+), 1 deletion(-) diff --git a/src/PostIt/Directory.Packages.props b/src/PostIt/Directory.Packages.props index 4dd4b2889..2f27340e9 100644 --- a/src/PostIt/Directory.Packages.props +++ b/src/PostIt/Directory.Packages.props @@ -16,6 +16,8 @@ + + diff --git a/src/PostIt/PostIt.Tests/BillingCommandPageViewModelTests.cs b/src/PostIt/PostIt.Tests/BillingCommandPageViewModelTests.cs index c7b5b926b..da366d284 100644 --- a/src/PostIt/PostIt.Tests/BillingCommandPageViewModelTests.cs +++ b/src/PostIt/PostIt.Tests/BillingCommandPageViewModelTests.cs @@ -115,6 +115,26 @@ 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 async Task InitializeAsync_loads_prestations_for_brush_and_submit_posts_selected_prestation() { diff --git a/src/PostIt/PostIt/PostIt.csproj b/src/PostIt/PostIt/PostIt.csproj index 177e346d3..09632bdf8 100644 --- a/src/PostIt/PostIt/PostIt.csproj +++ b/src/PostIt/PostIt/PostIt.csproj @@ -29,6 +29,8 @@ None All + + diff --git a/src/PostIt/PostIt/ViewModels/Commands/RdvViewModel.cs b/src/PostIt/PostIt/ViewModels/Commands/RdvViewModel.cs index afd0c54bd..44293f03e 100644 --- a/src/PostIt/PostIt/ViewModels/Commands/RdvViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/Commands/RdvViewModel.cs @@ -113,6 +113,20 @@ 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."); + } + protected override async Task SubmitAsync() { diff --git a/src/PostIt/PostIt/Views/Commands/RdvPage.axaml b/src/PostIt/PostIt/Views/Commands/RdvPage.axaml index 4c88b0108..cee3c5c79 100644 --- a/src/PostIt/PostIt/Views/Commands/RdvPage.axaml +++ b/src/PostIt/PostIt/Views/Commands/RdvPage.axaml @@ -1,12 +1,13 @@ - + + + ("LocationMap"); + if (_locationMap is null) + return; + + var map = new Map(); + map.Layers.Add(OpenStreetMap.CreateTileLayer()); + _locationMap.Map = map; + _locationMap.MapTapped += OnMapTapped; + + DataContextChanged += OnDataContextChanged; + CenterFromViewModel(); + } + + private void OnDataContextChanged(object? sender, System.EventArgs e) + { + CenterFromViewModel(); + } + + private 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); + CenterMap(latitude, longitude, zoomLevel: 13); + } + + private void CenterFromViewModel() + { + if (DataContext is not RdvViewModel vm) + { + CenterMap(48.8566, 2.3522, zoomLevel: 4); + return; + } + + if (vm.Latitude.HasValue && vm.Longitude.HasValue) + { + CenterMap(vm.Latitude.Value, vm.Longitude.Value, zoomLevel: 13); + return; + } + + CenterMap(48.8566, 2.3522, zoomLevel: 4); + } + + 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); + } } From 389cd050daec1e1b0c609c4bc624d121ade9285d Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sun, 6 Sep 2026 17:05:18 +0100 Subject: [PATCH 12/67] postit: add rdv map marker and recenter action --- .../PostIt/Views/Commands/RdvPage.axaml | 20 ++-- .../PostIt/Views/Commands/RdvPage.axaml.cs | 92 ++++++++++++++++++- 2 files changed, 101 insertions(+), 11 deletions(-) diff --git a/src/PostIt/PostIt/Views/Commands/RdvPage.axaml b/src/PostIt/PostIt/Views/Commands/RdvPage.axaml index cee3c5c79..a3cb477b1 100644 --- a/src/PostIt/PostIt/Views/Commands/RdvPage.axaml +++ b/src/PostIt/PostIt/Views/Commands/RdvPage.axaml @@ -40,12 +40,20 @@ - - public MainViewModel(BlogApiClient blogClient, Settings? settings = null, IServiceProvider? services = null) + public BlogsViewModel(BlogApiClient blogClient, Settings? settings = null, IServiceProvider? services = null) { SettingsModel = new Settings(); BlogClient = blogClient ?? throw new ArgumentNullException(nameof(blogClient)); ; diff --git a/src/PostIt/PostIt/Views/Blogs/MainPage.axaml b/src/PostIt/PostIt/Views/Blogs/MainPage.axaml index 871a2f541..c93aef2c2 100644 --- a/src/PostIt/PostIt/Views/Blogs/MainPage.axaml +++ b/src/PostIt/PostIt/Views/Blogs/MainPage.axaml @@ -5,15 +5,15 @@ xmlns:vm="using:PostIt.ViewModels" xmlns:postitControls="using:PostIt.Controls" xmlns:models="using:Yavsc.Blogspot" - xmlns:views="using:PostIt.Views" + xmlns:views="using:PostIt.Views.Blogs" xmlns:AvaloniaEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" mc:Ignorable="d" - x:Class="PostIt.Views.MainPage" - x:DataType="vm:MainViewModel" + x:Class="PostIt.Views.Blogs.BlogsPage" + x:DataType="vm:BlogsViewModel" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> - + + x:DataType="vm:HomePageViewModel"> - + diff --git a/src/PostIt/PostIt/Views/Layout/MainView.axaml.cs b/src/PostIt/PostIt/Views/Layout/MainView.axaml.cs index 654b90e2d..22bf537c6 100644 --- a/src/PostIt/PostIt/Views/Layout/MainView.axaml.cs +++ b/src/PostIt/PostIt/Views/Layout/MainView.axaml.cs @@ -13,7 +13,7 @@ public partial class MainView : UserControl protected override void OnDataContextChanged(EventArgs e) { base.OnDataContextChanged(e); - if (DataContext is ViewModels.MainViewModel vm) + if (DataContext is ViewModels.BlogsViewModel vm) { if (!vm.IsLoaded) { diff --git a/src/Yavsc.Org.Tests/Directory.Packages.props b/src/Yavsc.Org.Tests/Directory.Packages.props index 5927d2b5b..af2ef948c 100644 --- a/src/Yavsc.Org.Tests/Directory.Packages.props +++ b/src/Yavsc.Org.Tests/Directory.Packages.props @@ -4,8 +4,8 @@ - - - + + + diff --git a/src/Yavsc.Org.Tests/Services/FileSystemAuthManagerTests.cs b/src/Yavsc.Org.Tests/Services/FileSystemAuthManagerTests.cs new file mode 100644 index 000000000..8a796e4b5 --- /dev/null +++ b/src/Yavsc.Org.Tests/Services/FileSystemAuthManagerTests.cs @@ -0,0 +1,129 @@ +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; +using Yavsc.Models; +using Yavsc.Models.Access; +using Yavsc.Models.Relationship; +using Yavsc.Services; + +namespace Yavsc.Org.Tests.Services; + +public class FileSystemAuthManagerTests +{ + [Fact] + public void SetAccess_creates_acl_row_with_owner_path_and_flags() + { + using var scope = CreateScope(); + scope.Service.SetAccess(scope.Circle.Id, "alice/documents/report.txt", FileAccessRight.Read | FileAccessRight.Write); + + var row = scope.Db.CircleAuthorizationToFile.Single(); + + Assert.Equal(scope.Circle.Id, row.CircleId); + Assert.Equal("alice/documents/report.txt", row.Path); + Assert.Equal("alice", row.OwnerId); + Assert.Equal(FileAccessRight.Read | FileAccessRight.Write, row.Access); + } + + [Fact] + public void SetAccess_updates_existing_acl_row_without_duplicates() + { + using var scope = CreateScope(); + + scope.Service.SetAccess(scope.Circle.Id, "alice/documents/report.txt", FileAccessRight.Read); + scope.Service.SetAccess(scope.Circle.Id, "alice/documents/report.txt", FileAccessRight.Write); + + var rows = scope.Db.CircleAuthorizationToFile.ToList(); + + Assert.Single(rows); + Assert.Equal(FileAccessRight.Write, rows[0].Access); + } + + [Fact] + public void SetAccess_none_removes_existing_acl_row() + { + using var scope = CreateScope(); + + scope.Service.SetAccess(scope.Circle.Id, "alice/documents/report.txt", FileAccessRight.Read); + scope.Service.SetAccess(scope.Circle.Id, "alice/documents/report.txt", FileAccessRight.None); + + Assert.Empty(scope.Db.CircleAuthorizationToFile); + } + + [Fact] + public void SetAccess_ignores_unknown_owner_prefix() + { + using var scope = CreateScope(); + + scope.Service.SetAccess(scope.Circle.Id, "unknown/documents/report.txt", FileAccessRight.Read); + + Assert.Empty(scope.Db.CircleAuthorizationToFile); + } + + [Fact] + public void Deleting_circle_cascades_file_acl_rows() + { + using var scope = CreateScope(); + + scope.Service.SetAccess(scope.Circle.Id, "alice/documents/report.txt", FileAccessRight.Read); + scope.Db.Circle.Remove(scope.Circle); + scope.Db.SaveChanges(); + + Assert.Empty(scope.Db.CircleAuthorizationToFile); + } + + private static TestScope CreateScope() + { + var connection = new SqliteConnection("Data Source=:memory:"); + connection.Open(); + + var options = new DbContextOptionsBuilder() + .UseSqlite(connection) + .Options; + + var db = new ApplicationDbContext(options); + db.Database.EnsureCreated(); + + db.Users.Add(new ApplicationUser + { + Id = "alice", + UserName = "alice", + Email = "alice@example.test" + }); + db.SaveChanges(); + + var circle = new Circle + { + OwnerId = "alice", + Name = "shared", + Public = false + }; + + db.Circle.Add(circle); + db.SaveChanges(); + + var service = new FileSystemAuthManager(db, Options.Create(new SiteSettings())); + return new TestScope(connection, db, service, circle); + } + + private sealed class TestScope : IDisposable + { + public TestScope(SqliteConnection connection, ApplicationDbContext db, FileSystemAuthManager service, Circle circle) + { + Connection = connection; + Db = db; + Service = service; + Circle = circle; + } + + public SqliteConnection Connection { get; } + public ApplicationDbContext Db { get; } + public FileSystemAuthManager Service { get; } + public Circle Circle { get; } + + public void Dispose() + { + Db.Dispose(); + Connection.Dispose(); + } + } +} diff --git a/src/Yavsc.Org.Tests/Yavsc.Org.Tests.csproj b/src/Yavsc.Org.Tests/Yavsc.Org.Tests.csproj index 106079202..0d18d1e0f 100644 --- a/src/Yavsc.Org.Tests/Yavsc.Org.Tests.csproj +++ b/src/Yavsc.Org.Tests/Yavsc.Org.Tests.csproj @@ -53,6 +53,7 @@ + - - - /// [ForeignKey("CommandId"),JsonIgnore] - public RdvQuery Query { get; set; } + public NominativeServiceCommand? Query { get; set; } public string Description { get; set; } public string Title { get; set; } From 2397f4d3a8f9214269c3939da58b3a18df584178 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sat, 12 Sep 2026 13:29:49 +0100 Subject: [PATCH 51/67] Add provider ongoing requests flow and sort persistence --- ...oviderOngoingRequestsPageViewModelTests.cs | 208 ++++++++++ .../Helpers/ServiceCollectionHelpers.cs | 1 + src/PostIt/PostIt/ViewLocator.cs | 1 + .../ProviderOngoingRequestsPageViewModel.cs | 356 ++++++++++++++++++ .../ViewModels/Layout/HomePageViewModel.cs | 20 +- .../PostIt/ViewModels/Settings/Settings.cs | 8 +- .../ProviderOngoingRequestsPage.axaml | 98 +++++ .../ProviderOngoingRequestsPage.axaml.cs | 17 + src/Yavsc.Api.Client/BillingApiClient.cs | 8 + .../Controllers/Business/BillingController.cs | 69 ++++ 10 files changed, 784 insertions(+), 2 deletions(-) create mode 100644 src/PostIt/PostIt.Tests/ProviderOngoingRequestsPageViewModelTests.cs create mode 100644 src/PostIt/PostIt/ViewModels/Activity/ProviderOngoingRequestsPageViewModel.cs create mode 100644 src/PostIt/PostIt/Views/Activity/ProviderOngoingRequestsPage.axaml create mode 100644 src/PostIt/PostIt/Views/Activity/ProviderOngoingRequestsPage.axaml.cs diff --git a/src/PostIt/PostIt.Tests/ProviderOngoingRequestsPageViewModelTests.cs b/src/PostIt/PostIt.Tests/ProviderOngoingRequestsPageViewModelTests.cs new file mode 100644 index 000000000..945072870 --- /dev/null +++ b/src/PostIt/PostIt.Tests/ProviderOngoingRequestsPageViewModelTests.cs @@ -0,0 +1,208 @@ +using System.Net.Http; +using PostIt.ViewModels; +using Yavsc; +using Yavsc.Api.Client; + +namespace PostIt.Tests; + +public class ProviderOngoingRequestsPageViewModelTests +{ + [Fact] + public async Task RefreshAsync_calls_provider_endpoint_and_filters_out_unknown_billing_codes() + { + var api = new StubProviderApi(); + var client = new BillingApiClient(api, "https://business.example/api/v1/"); + var vm = new ProviderOngoingRequestsPageViewModel(client); + + await vm.InitializeAsync(); + + Assert.Contains("https://business.example/api/v1/bill/provider/ongoing", api.Paths); + Assert.Equal(3, vm.Queries.Count); + Assert.Equal(12, vm.Queries[0].Id); + Assert.Equal(11, vm.Queries[1].Id); + Assert.Equal(10, vm.Queries[2].Id); + } + + [Fact] + public async Task FilterText_filters_by_activity_code_and_status() + { + var api = new StubProviderApi(); + var client = new BillingApiClient(api, "https://business.example/api/v1/"); + var vm = new ProviderOngoingRequestsPageViewModel(client); + + await vm.InitializeAsync(); + + vm.FilterText = "mbrush"; + Assert.Single(vm.Queries); + Assert.Equal("MBrush", vm.Queries[0].BillingCode); + + vm.FilterText = "accepted"; + Assert.Single(vm.Queries); + Assert.Equal(QueryStatus.Accepted, vm.Queries[0].Status); + } + + [Fact] + public async Task OpenSelectedEditorCommand_can_execute_only_when_selection_exists() + { + var api = new StubProviderApi(); + var client = new BillingApiClient(api, "https://business.example/api/v1/"); + var vm = new ProviderOngoingRequestsPageViewModel(client); + + await vm.InitializeAsync(); + + Assert.False(vm.OpenSelectedEditorCommand.CanExecute(null)); + + vm.SelectedQuery = vm.Queries[0]; + + Assert.True(vm.OpenSelectedEditorCommand.CanExecute(null)); + } + + [Fact] + public async Task SelectedSortOption_date_keeps_most_recent_first() + { + var api = new StubProviderApi(); + var client = new BillingApiClient(api, "https://business.example/api/v1/"); + var vm = new ProviderOngoingRequestsPageViewModel(client); + + await vm.InitializeAsync(); + vm.SelectedSortOption = ProviderOngoingRequestsPageViewModel.SortByDate; + + Assert.Equal(new long[] { 12, 11, 10 }, vm.Queries.Select(q => q.Id).ToArray()); + } + + [Fact] + public async Task SelectedSortOption_date_ascending_keeps_oldest_first() + { + var api = new StubProviderApi(); + var client = new BillingApiClient(api, "https://business.example/api/v1/"); + var vm = new ProviderOngoingRequestsPageViewModel(client); + + await vm.InitializeAsync(); + vm.SelectedSortOption = ProviderOngoingRequestsPageViewModel.SortByDateAsc; + + Assert.Equal(new long[] { 10, 11, 12 }, vm.Queries.Select(q => q.Id).ToArray()); + } + + [Fact] + public async Task SelectedSortOption_status_prioritizes_inprogress_then_accepted_then_inserted() + { + var api = new StubProviderApi(); + var client = new BillingApiClient(api, "https://business.example/api/v1/"); + var vm = new ProviderOngoingRequestsPageViewModel(client); + + await vm.InitializeAsync(); + vm.SelectedSortOption = ProviderOngoingRequestsPageViewModel.SortByStatus; + + Assert.Equal(new long[] { 11, 12, 10 }, vm.Queries.Select(q => q.Id).ToArray()); + } + + [Fact] + public void Constructor_reads_saved_sort_option_from_settings() + { + var api = new StubProviderApi(); + var client = new BillingApiClient(api, "https://business.example/api/v1/"); + var settings = new Settings + { + ProviderOngoingRequestsSortOption = ProviderOngoingRequestsPageViewModel.SortByStatus, + }; + + var vm = new ProviderOngoingRequestsPageViewModel(client, settings); + + Assert.Equal(ProviderOngoingRequestsPageViewModel.SortByStatus, vm.SelectedSortOption); + } + + [Fact] + public void Constructor_falls_back_to_default_when_saved_sort_is_invalid() + { + var api = new StubProviderApi(); + var client = new BillingApiClient(api, "https://business.example/api/v1/"); + var settings = new Settings + { + ProviderOngoingRequestsSortOption = "invalide", + }; + + var vm = new ProviderOngoingRequestsPageViewModel(client, settings); + + Assert.Equal(ProviderOngoingRequestsPageViewModel.SortByDate, vm.SelectedSortOption); + } + + private sealed class StubProviderApi : IYavscApiClient + { + public HttpClient Http { get; } = new(); + public List Paths { get; } = new(); + + public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) + { + Paths.Add(path); + + if (typeof(T) == typeof(List)) + { + var data = new List + { + new() + { + Id = 10, + BillingCode = "Rdv", + ActivityCode = "dev", + PerformerId = "perf-1", + ClientId = "cli-1", + Status = QueryStatus.Inserted, + Description = "Rendez-vous", + EventDate = new DateTime(2026, 9, 10, 10, 0, 0, DateTimeKind.Utc), + }, + new() + { + Id = 11, + BillingCode = "MBrush", + ActivityCode = "hair", + PerformerId = "perf-1", + ClientId = "cli-2", + Status = QueryStatus.InProgress, + Description = "Coupe multiple", + EventDate = new DateTime(2026, 9, 11, 10, 0, 0, DateTimeKind.Utc), + }, + new() + { + Id = 12, + BillingCode = "Brush", + ActivityCode = "hair", + PerformerId = "perf-1", + ClientId = "cli-3", + Status = QueryStatus.Accepted, + Description = "Coupe simple", + EventDate = new DateTime(2026, 9, 12, 10, 0, 0, DateTimeKind.Utc), + }, + new() + { + Id = 13, + BillingCode = "", + ActivityCode = "unknown", + PerformerId = "perf-1", + ClientId = "cli-4", + Status = QueryStatus.Accepted, + Description = "Doit être filtrée", + EventDate = new DateTime(2026, 9, 13, 10, 0, 0, DateTimeKind.Utc), + } + }; + + return Task.FromResult((T)(object)data); + } + + return Task.FromResult(default(T)!); + } + + public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) + { + Paths.Add(path); + return Task.CompletedTask; + } + + public Task CallAsync(HttpMethod method, string path, Func contentFactory, CancellationToken ct = default) + => CallAsync(method, path, (object?)null, ct); + + public Task CallAsync(HttpMethod method, string path, Func contentFactory, CancellationToken ct = default) + => CallAsync(method, path, (object?)null, ct); + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } +} diff --git a/src/PostIt/PostIt/Helpers/ServiceCollectionHelpers.cs b/src/PostIt/PostIt/Helpers/ServiceCollectionHelpers.cs index c87eb9286..0ebd2af19 100644 --- a/src/PostIt/PostIt/Helpers/ServiceCollectionHelpers.cs +++ b/src/PostIt/PostIt/Helpers/ServiceCollectionHelpers.cs @@ -59,6 +59,7 @@ public static class ServiceCollectionHelpers services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); // ViewModels services.AddSingleton(settings); services.AddSingleton(api); diff --git a/src/PostIt/PostIt/ViewLocator.cs b/src/PostIt/PostIt/ViewLocator.cs index 97538abbb..72bd2559e 100644 --- a/src/PostIt/PostIt/ViewLocator.cs +++ b/src/PostIt/PostIt/ViewLocator.cs @@ -52,6 +52,7 @@ public class ViewLocator : IDataTemplate PostAclDialogViewModel => services.GetRequiredService(), BillingQueriesPageViewModel => services.GetRequiredService(), BillingQueryDetailsPageViewModel => services.GetRequiredService(), + ProviderOngoingRequestsPageViewModel => services.GetRequiredService(), null => new TextBlock { Text = "No view for " }, _ => new TextBlock { Text = $"No view for {data.GetType().Name}" } }; diff --git a/src/PostIt/PostIt/ViewModels/Activity/ProviderOngoingRequestsPageViewModel.cs b/src/PostIt/PostIt/ViewModels/Activity/ProviderOngoingRequestsPageViewModel.cs new file mode 100644 index 000000000..562f24988 --- /dev/null +++ b/src/PostIt/PostIt/ViewModels/Activity/ProviderOngoingRequestsPageViewModel.cs @@ -0,0 +1,356 @@ +using System; +using System.Collections.ObjectModel; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; +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 ProviderOngoingRequestsPageViewModel : ViewModelBase, IActionStatusViewModel +{ + public const string SortByDate = "Date (plus récent d'abord)"; + public const string SortByDateAsc = "Date (plus ancien d'abord)"; + public const string SortByStatus = "Statut (en cours d'abord)"; + + private readonly BillingApiClient _billingClient; + private readonly Settings? _settings; + private List _allQueries = new(); + + [ObservableProperty] + public partial ObservableCollection Queries { get; set; } = new(); + + [ObservableProperty] + public partial string FilterText { get; set; } = string.Empty; + + public IReadOnlyList SortOptions { get; } = new[] + { + SortByDate, + SortByDateAsc, + SortByStatus, + }; + + [ObservableProperty] + public partial string SelectedSortOption { get; set; } = SortByDate; + + [ObservableProperty, NotifyCanExecuteChangedFor(nameof(OpenSelectedQueryCommand))] + public partial BillingQuerySummaryDto? SelectedQuery { get; set; } + + [ObservableProperty] + public partial bool IsBusy { get; set; } + + [ObservableProperty] + public partial string StatusMessage { get; set; } = "Chargement des demandes fournisseur..."; + + [ObservableProperty] + public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Chargement des demandes fournisseur..."); + + public string Title => "Mes demandes en cours"; + + public override bool CanNavigateNext + { + get => false; + protected set { _ = value; } + } + + public override bool CanNavigatePrevious + { + get => true; + protected set { _ = value; } + } + + public ProviderOngoingRequestsPageViewModel(BillingApiClient billingClient, Settings? settings = null) + { + _billingClient = billingClient ?? throw new ArgumentNullException(nameof(billingClient)); + _settings = settings; + + if (_settings is not null) + { + var preferredSort = NormalizeSortOption(_settings.ProviderOngoingRequestsSortOption); + if (!string.Equals(preferredSort, SelectedSortOption, StringComparison.Ordinal)) + { + SelectedSortOption = preferredSort; + } + } + } + + public Task InitializeAsync() => RefreshAsync(); + + [RelayCommand] + public async Task RefreshAsync() + { + IsBusy = true; + try + { + var items = await _billingClient.GetProviderOngoingQueriesAsync().ConfigureAwait(true) ?? new(); + _allQueries = items + .Where(x => !string.IsNullOrWhiteSpace(x.BillingCode)) + .OrderByDescending(x => x.EventDate ?? DateTime.MinValue) + .ThenByDescending(x => x.Id) + .ToList(); + + ApplyFilter(); + this.SetInfoStatus(_allQueries.Count == 0 + ? "Aucune demande en cours pour votre profil fournisseur." + : $"{_allQueries.Count} demande(s) en cours chargée(s)."); + } + catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) + { + _allQueries = new List(); + Queries = new ObservableCollection(); + this.SetWarningStatus("Accès refusé au billing (scope 'api'). Déconnectez puis reconnectez-vous."); + } + catch (Exception ex) + { + _allQueries = new List(); + Queries = new ObservableCollection(); + this.SetErrorStatus($"Erreur: {ex.Message}"); + } + finally + { + IsBusy = false; + } + } + + private bool CanOpenSelectedQuery() => SelectedQuery is not null; + + private bool CanOpenSelectedEditor() => SelectedQuery is not null; + + [RelayCommand(CanExecute = nameof(CanOpenSelectedQuery))] + public async Task OpenSelectedQueryAsync() + { + if (SelectedQuery is null) + { + this.SetWarningStatus("Sélectionnez une demande."); + return; + } + + var app = (App?)Application.Current; + if (app is null) + { + throw new InvalidOperationException("Application PostIt indisponible."); + } + + IsBusy = true; + try + { + var details = await _billingClient + .GetQueryAsync(SelectedQuery.BillingCode, SelectedQuery.Id) + .ConfigureAwait(true); + var (activity, performer, form) = BuildNavigationContext(SelectedQuery); + + var vm = new BillingQueryDetailsPageViewModel( + activity, + performer, + form, + _billingClient, + details, + isReadOnly: false); + + await app.PushPageAsync(vm).ConfigureAwait(true); + } + catch (Exception ex) + { + this.SetErrorStatus($"Erreur lors de l'ouverture: {ex.Message}"); + } + finally + { + IsBusy = false; + } + } + + [RelayCommand(CanExecute = nameof(CanOpenSelectedEditor))] + public async Task OpenSelectedEditorAsync() + { + if (SelectedQuery is null) + { + this.SetWarningStatus("Sélectionnez une demande."); + return; + } + + var app = (App?)Application.Current; + if (app is null) + { + throw new InvalidOperationException("Application PostIt indisponible."); + } + + IsBusy = true; + try + { + var details = await _billingClient + .GetQueryAsync(SelectedQuery.BillingCode, SelectedQuery.Id) + .ConfigureAwait(true); + + var (activity, performer, form) = BuildNavigationContext(SelectedQuery); + var vm = form.CreateCommandPageViewModel(activity, performer, _billingClient); + if (vm is null) + { + this.SetWarningStatus($"Le formulaire '{form.ActionName}' n'est pas pris en charge en édition."); + return; + } + + await vm.InitializeAsync(details).ConfigureAwait(true); + await app.PushPageAsync(vm).ConfigureAwait(true); + } + catch (Exception ex) + { + this.SetErrorStatus($"Erreur lors de l'ouverture en édition: {ex.Message}"); + } + finally + { + IsBusy = false; + } + } + + partial void OnFilterTextChanged(string value) + { + ApplyFilter(); + } + + partial void OnSelectedSortOptionChanged(string value) + { + var normalized = NormalizeSortOption(value); + if (!string.Equals(normalized, value, StringComparison.Ordinal)) + { + SelectedSortOption = normalized; + return; + } + + PersistSortPreference(value); + ApplyFilter(); + } + + private void ApplyFilter() + { + var query = FilterText?.Trim(); + var filtered = string.IsNullOrWhiteSpace(query) + ? _allQueries + : _allQueries.Where(x => + ContainsInsensitive(x.Description, query) + || ContainsInsensitive(x.ActivityCode, query) + || ContainsInsensitive(x.BillingCode, query) + || ContainsInsensitive(x.ClientId, query) + || ContainsInsensitive(x.Status.ToString(), query)) + .ToList(); + + var sorted = ApplySort(filtered); + Queries = new ObservableCollection(sorted); + } + + private List ApplySort(IEnumerable source) + { + if (string.Equals(SelectedSortOption, SortByStatus, StringComparison.Ordinal)) + { + return source + .OrderBy(x => GetStatusRank(x.Status)) + .ThenByDescending(x => x.EventDate ?? DateTime.MinValue) + .ThenByDescending(x => x.Id) + .ToList(); + } + + if (string.Equals(SelectedSortOption, SortByDateAsc, StringComparison.Ordinal)) + { + return source + .OrderBy(x => x.EventDate ?? DateTime.MinValue) + .ThenBy(x => x.Id) + .ToList(); + } + + return source + .OrderByDescending(x => x.EventDate ?? DateTime.MinValue) + .ThenByDescending(x => x.Id) + .ToList(); + } + + private void PersistSortPreference(string selectedSort) + { + if (_settings is null) + { + return; + } + + if (string.Equals(_settings.ProviderOngoingRequestsSortOption, selectedSort, StringComparison.Ordinal)) + { + return; + } + + _settings.ProviderOngoingRequestsSortOption = selectedSort; + + try + { + _settings.Save(); + } + catch + { + this.SetWarningStatus("Le tri a été appliqué, mais sa sauvegarde a échoué."); + } + } + + private static string NormalizeSortOption(string? sortOption) + { + if (string.Equals(sortOption, SortByDate, StringComparison.Ordinal) + || string.Equals(sortOption, SortByDateAsc, StringComparison.Ordinal) + || string.Equals(sortOption, SortByStatus, StringComparison.Ordinal)) + { + return sortOption!; + } + + return SortByDate; + } + + private static int GetStatusRank(QueryStatus status) + => status switch + { + QueryStatus.InProgress => 0, + QueryStatus.Accepted => 1, + QueryStatus.Inserted => 2, + QueryStatus.Success => 3, + QueryStatus.Rejected => 4, + QueryStatus.Failed => 5, + _ => 99, + }; + + private static bool ContainsInsensitive(string? source, string query) + => !string.IsNullOrWhiteSpace(source) + && source.Contains(query, StringComparison.OrdinalIgnoreCase); + + private static (ActivityInfo activity, ActivityUserDisplayItem performer, CommandFormSummary form) + BuildNavigationContext(BillingQuerySummaryDto query) + { + var activity = new ActivityInfo + { + Code = query.ActivityCode, + Name = string.IsNullOrWhiteSpace(query.ActivityCode) + ? "Activité" + : query.ActivityCode, + }; + + var performer = new ActivityUserDisplayItem + { + PerformerId = query.PerformerId, + UserName = "Mon profil fournisseur", + AvatarFallbackLabel = "M", + IsPerformerActive = true, + PerformerStatusBadgeLabel = "Actif", + PerformerStatusBadgeBackground = "#E6F7EC", + PerformerStatusBadgeBorder = "#2E7D32", + PerformerStatusBadgeForeground = "#1B5E20", + }; + + var form = new CommandFormSummary + { + ActionName = query.BillingCode, + Title = query.BillingCode, + }; + + return (activity, performer, form); + } +} diff --git a/src/PostIt/PostIt/ViewModels/Layout/HomePageViewModel.cs b/src/PostIt/PostIt/ViewModels/Layout/HomePageViewModel.cs index a35c8016d..673177863 100644 --- a/src/PostIt/PostIt/ViewModels/Layout/HomePageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/Layout/HomePageViewModel.cs @@ -5,6 +5,7 @@ using CommunityToolkit.Mvvm.Input; using Microsoft.Extensions.DependencyInjection; using PostIt.Helpers; using PostIt.Services; +using Yavsc.Api.Client; namespace PostIt.ViewModels; public class HomePageViewModel : ViewModelBase @@ -50,7 +51,24 @@ public class HomePageViewModel : ViewModelBase await app.PushPageAsync(vm); } - private Task OpenProviderRequestsAsync() => OpenActivitiesAsync(); + private async Task OpenProviderRequestsAsync() + { + var app = (App?)Application.Current; + if (app is null) + { + throw new InvalidOperationException("Application PostIt indisponible."); + } + + var billingClient = app.ServiceProvider?.GetRequiredService(); + if (billingClient is null) + { + throw new InvalidOperationException("Client billing indisponible."); + } + + var vm = new ProviderOngoingRequestsPageViewModel(billingClient, Settings); + await vm.InitializeAsync(); + await app.PushPageAsync(vm); + } /// /// Avalonia designer constructor. Builds a self-contained VM diff --git a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs index 0864c1416..23e9955f4 100644 --- a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs +++ b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs @@ -32,6 +32,9 @@ public partial class Settings : ViewModelBase [ObservableProperty] public partial string SearchText { get; set; } = string.Empty; + [ObservableProperty] + public partial string ProviderOngoingRequestsSortOption { get; set; } = string.Empty; + [ObservableProperty] [JsonIgnore] public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Pret."); @@ -62,6 +65,7 @@ public partial class Settings : ViewModelBase partial void OnBlogsApiUrlChanged(string value) => MarkDirty(); partial void OnApiUrlChanged(string value) => MarkDirty(); partial void OnSearchTextChanged(string value) => MarkDirty(); + partial void OnProviderOngoingRequestsSortOptionChanged(string value) => MarkDirty(); /// /// Authentication can be reassigned wholesale by @@ -346,6 +350,7 @@ public partial class Settings : ViewModelBase ? settings.ApiUrl : this.ApiUrl; this.SearchText = settings.SearchText ?? string.Empty; + this.ProviderOngoingRequestsSortOption = settings.ProviderOngoingRequestsSortOption ?? string.Empty; if (!(settings.Authentication is null)) { this.Authentication = new AuthenticationSettings(); @@ -424,6 +429,7 @@ public partial class Settings : ViewModelBase this.BlogsApiUrl = "https://blogs.pschneider.fr/api/v1/"; this.ApiUrl = "https://api.pschneider.fr/api/v1/"; this.SearchText = string.Empty; + this.ProviderOngoingRequestsSortOption = string.Empty; } /// @@ -466,7 +472,7 @@ public partial class Settings : ViewModelBase UnixFileMode.UserRead | UnixFileMode.UserWrite); IsDirty = false; SetActionStatus("Parametres sauvegardes.", StatusSeverity.Info); - + Console.WriteLine($"💾 Settings saved to {configPath}"); } catch (Exception ex) diff --git a/src/PostIt/PostIt/Views/Activity/ProviderOngoingRequestsPage.axaml b/src/PostIt/PostIt/Views/Activity/ProviderOngoingRequestsPage.axaml new file mode 100644 index 000000000..010bab7b5 --- /dev/null +++ b/src/PostIt/PostIt/Views/Activity/ProviderOngoingRequestsPage.axaml @@ -0,0 +1,98 @@ + + + + + + + + + -public class AccountSmokeTests : SmokeTestBase, IClassFixture +public class AccountSmokeTests : IClassFixture { private readonly TestWebApplicationFactory _factory; @@ -27,24 +27,7 @@ public class AccountSmokeTests : SmokeTestBase, IClassFixture -/// Base for the smoke tests covering the production hosts -/// (Yavsc.Org / Yavsc.Api / Yavsc.Blogs). One smoke test per -/// bounded context (BC): each test hits one GET endpoint and -/// asserts a 2xx or 3xx status, with no follow-up redirect. -/// Together they satisfy the 'Tests d'intégration smoke par BC' -/// item of Jalon 0 in ROADMAP.md. -/// -/// Status code policy: -/// - 200 OK : endpoint serves a page. -/// - 302 / 301 : endpoint requires auth and redirects to login -/// (acceptable smoke signal: routing + middleware are wired). -/// - 401 / 403 : endpoint exists but rejects anonymous (acceptable -/// for API smoke tests where the smoke is "the host boots"). -/// Anything else (404, 500, connection refused) is a failure. -/// -public abstract class SmokeTestBase -{ - /// - /// Issue a GET against on the - /// in-memory test server. Returns the raw HttpResponseMessage - /// without following redirects — the test asserts on the first - /// hop, not the eventual page. - /// - protected static async Task GetRaw( - HttpClient client, string relativePath) - { - Assert.NotNull(client); - var request = new HttpRequestMessage(HttpMethod.Get, relativePath); - return await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); - } - - /// - /// Smoke assertion: a GET on - /// returns 2xx (page served) or 3xx (redirect to login) or - /// 401/403 (anonymous rejected by [Authorize]). Anything else - /// — 404 (route missing), 5xx (server crash), connection - /// refused (host not started) — fails the test. - /// - protected static async Task AssertResponds( - HttpClient client, string relativePath) - { - var response = await GetRaw(client, relativePath); - var status = (int)response.StatusCode; - Assert.True( - status >= 200 && status < 400 || status == 401 || status == 403, - $"GET {relativePath} returned {status} {response.StatusCode}, " + - "expected 2xx/3xx (page or redirect) or 401/403 (auth required)."); - } -} diff --git a/src/Yavsc.Org.Tests/WebServerFixture.cs b/src/Yavsc.Org.Tests/WebServerFixture.cs index f82771ec6..9115af234 100644 --- a/src/Yavsc.Org.Tests/WebServerFixture.cs +++ b/src/Yavsc.Org.Tests/WebServerFixture.cs @@ -78,6 +78,7 @@ public sealed class WebServerFixture : WebHostFixture public RecordingSmtpClientFactory? SmtpClientFactory { get; private set; } public ILogger? Logger { get; internal set; } + public string? HttpsAuthority => Addresses.FirstOrDefault(u => u.StartsWith("https:")); protected override WebApplication BuildApp(WebApplicationBuilder builder) { var authority = $"https://localhost:{_httpsPort}"; From d92456e141fc5cb5a3ea78796bce18467387d967 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sat, 12 Sep 2026 16:49:36 +0100 Subject: [PATCH 54/67] fixe tests --- src/Yavsc.Org.Tests/Mandatory/BatchTests.cs | 6 +-- src/Yavsc.Org.Tests/Mandatory/Remoting.cs | 6 ++- src/Yavsc.Org.Tests/NonRegression/Database.cs | 17 +------ src/Yavsc.Org.Tests/Smoke/BlogSmokeTests.cs | 6 ++- src/Yavsc.Org.Tests/WebServerFixture.cs | 49 +++++++++++++++++-- src/Yavsc.Tests.Shared/WebHostFixture.cs | 49 +++++++++++++++---- 6 files changed, 96 insertions(+), 37 deletions(-) diff --git a/src/Yavsc.Org.Tests/Mandatory/BatchTests.cs b/src/Yavsc.Org.Tests/Mandatory/BatchTests.cs index daa2bf1fe..30f0535a9 100644 --- a/src/Yavsc.Org.Tests/Mandatory/BatchTests.cs +++ b/src/Yavsc.Org.Tests/Mandatory/BatchTests.cs @@ -10,10 +10,10 @@ namespace Yavsc.Org.Tests { [Collection("Yavsc Server")] [Trait("regression", "oui")] - public class BaseTestContext : IClassFixture, IDisposable + public abstract class BaseTestContext : IClassFixture, IDisposable { - public readonly WebServerFixture _serverFixture; - private readonly ITestOutputHelper _output; + protected readonly WebServerFixture _serverFixture; + protected readonly ITestOutputHelper _output; public BaseTestContext(ITestOutputHelper output, WebServerFixture fixture) { diff --git a/src/Yavsc.Org.Tests/Mandatory/Remoting.cs b/src/Yavsc.Org.Tests/Mandatory/Remoting.cs index 125d6f75e..bb9353cb4 100644 --- a/src/Yavsc.Org.Tests/Mandatory/Remoting.cs +++ b/src/Yavsc.Org.Tests/Mandatory/Remoting.cs @@ -84,9 +84,11 @@ namespace Yavsc.Org.Tests [Fact] public async Task GetOpenIdConfiguration_returns_ok() { - using var client = _serverFixture.CreateHttpClient(); + using var client = CreateHttpClient(); var response = await GetRaw(client, "/.well-known/openid-configuration"); - var payload = await response.Content.ReadAsStringAsync(); + var payload = await response.Content.ReadAsStringAsync( + TestContext.Current.CancellationToken + ); Assert.True( response.IsSuccessStatusCode, diff --git a/src/Yavsc.Org.Tests/NonRegression/Database.cs b/src/Yavsc.Org.Tests/NonRegression/Database.cs index 4633ce177..1baf7e3bc 100644 --- a/src/Yavsc.Org.Tests/NonRegression/Database.cs +++ b/src/Yavsc.Org.Tests/NonRegression/Database.cs @@ -1,14 +1,8 @@ - -using Microsoft.Data.Sqlite; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Diagnostics; -using Yavsc.Models; - namespace Yavsc.Org.Tests.Mandatory {[Collection("Database")] [Trait("regression", "II")] [Trait("dev", "wip")] - public class Database: IClassFixture, IDisposable + public class Database : IClassFixture { readonly ITestOutputHelper output; readonly WebServerFixture _serverFixture; @@ -24,15 +18,6 @@ namespace Yavsc.Org.Tests.Mandatory /// Install all our migrations in a fresh new database. /// - public void Dispose() - { - if (_serverFixture!=null) - { - _serverFixture.Dispose(); - } - - } - [Fact] public void TestDatabaseMigration() { diff --git a/src/Yavsc.Org.Tests/Smoke/BlogSmokeTests.cs b/src/Yavsc.Org.Tests/Smoke/BlogSmokeTests.cs index 96650ba80..3c383ad80 100644 --- a/src/Yavsc.Org.Tests/Smoke/BlogSmokeTests.cs +++ b/src/Yavsc.Org.Tests/Smoke/BlogSmokeTests.cs @@ -14,11 +14,13 @@ namespace Yavsc.Org.Tests.Smoke; /// doc/architecture/decoupage-organisation.md. The smoke /// here asserts the front-end side of the BC. /// -public class BlogSmokeTests : SmokeTestBase, IClassFixture +public class BlogSmokeTests : BaseTestContext, IClassFixture { private readonly TestWebApplicationFactory _factory; - public BlogSmokeTests(TestWebApplicationFactory factory) + public BlogSmokeTests(TestWebApplicationFactory factory, ITestOutputHelper output, + WebServerFixture webServerFixture) + : base(output, webServerFixture) { _factory = factory; } diff --git a/src/Yavsc.Org.Tests/WebServerFixture.cs b/src/Yavsc.Org.Tests/WebServerFixture.cs index 9115af234..f438fd88c 100644 --- a/src/Yavsc.Org.Tests/WebServerFixture.cs +++ b/src/Yavsc.Org.Tests/WebServerFixture.cs @@ -63,6 +63,7 @@ public sealed class WebServerFixture : WebHostFixture private static string? _sharedTestingUserName; private static string? _sharedTestingUserPassword; private static string? _sharedTestingUserEmail; + private static string? _sharedHttpsAuthority; private static RecordingSmtpClientFactory? _sharedSmtpClientFactory; public IConfiguration? Configuration { get; private set; } @@ -78,10 +79,19 @@ public sealed class WebServerFixture : WebHostFixture public RecordingSmtpClientFactory? SmtpClientFactory { get; private set; } public ILogger? Logger { get; internal set; } - public string? HttpsAuthority => Addresses.FirstOrDefault(u => u.StartsWith("https:")); + public string? HttpsAuthority { get; private set; } + + protected override WebApplicationOptions CreateBuilderOptions() + { + return new WebApplicationOptions + { + ApplicationName = typeof(Yavsc.Program).Assembly.GetName().Name + }; + } + protected override WebApplication BuildApp(WebApplicationBuilder builder) { - var authority = $"https://localhost:{_httpsPort}"; + HttpsAuthority = $"https://localhost:{HttpsPort}"; // WebApplication.CreateBuilder defaults WebRootPath to // {ContentRoot}/wwwroot. The test assembly runs from @@ -100,7 +110,7 @@ public sealed class WebServerFixture : WebHostFixture ["Smtp:Port"] = "465", ["Smtp:UserName"] = "test-user", ["Smtp:Password"] = "test-pass", - ["Site:Authority"] = authority + ["Site:Authority"] = HttpsAuthority }); Configuration = builder.Configuration; @@ -183,6 +193,7 @@ public sealed class WebServerFixture : WebHostFixture _sharedTestingUserName = TestingUserName; _sharedTestingUserPassword = TestingUserPassword; _sharedTestingUserEmail = TestingUserEmail; + _sharedHttpsAuthority = HttpsAuthority; _sharedLogger = app.Services.GetRequiredService().CreateLogger(); Logger = _sharedLogger; SmtpClientFactory = smtpFactory; @@ -195,13 +206,42 @@ public sealed class WebServerFixture : WebHostFixture using var scope = Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); db.Database.EnsureDeleted(); + db.Database.EnsureCreated(); if (db.Database.IsRelational()) { db.Database.Migrate(); + ReseedAuthTestData(scope); return; } + ReseedAuthTestData(scope); + } - db.Database.EnsureCreated(); + private void ReseedAuthTestData(IServiceScope scope) + { + TestingUserName ??= "Tester"; + TestingUserPassword ??= "Test123!"; + TestingUserEmail ??= "test@no-reply.com"; + TestClientId ??= "testClientId"; + TestClientSecret ??= Guid.CreateVersion7().ToString(); + + TestingUser = null; + EnsureUser(TestingUserName, TestingUserPassword, TestingUserEmail, scope); + + var db = scope.ServiceProvider.GetRequiredService(); + TestingUser = db.Users.FirstOrDefault(u => u.UserName == TestingUserName); + + var configDb = scope.ServiceProvider.GetRequiredService(); + var hasClient = configDb.Set().Any(c => c.ClientId == TestClientId); + if (!hasClient) + { + AddAuthorizedClient(scope, TestClientId, TestClientSecret); + } + + _sharedTestClientId = TestClientId; + _sharedTestClientSecret = TestClientSecret; + _sharedTestingUserName = TestingUserName; + _sharedTestingUserPassword = TestingUserPassword; + _sharedTestingUserEmail = TestingUserEmail; } protected override async Task ConfigurePipelineAsync(WebApplication app) @@ -226,6 +266,7 @@ public sealed class WebServerFixture : WebHostFixture TestingUserName = _sharedTestingUserName; TestingUserPassword = _sharedTestingUserPassword; TestingUserEmail = _sharedTestingUserEmail; + HttpsAuthority = _sharedHttpsAuthority; SmtpClientFactory = _sharedSmtpClientFactory; Configuration = _sharedConfiguration; SiteSettings = _sharedSiteSettings; diff --git a/src/Yavsc.Tests.Shared/WebHostFixture.cs b/src/Yavsc.Tests.Shared/WebHostFixture.cs index b92adc094..ac3356cce 100644 --- a/src/Yavsc.Tests.Shared/WebHostFixture.cs +++ b/src/Yavsc.Tests.Shared/WebHostFixture.cs @@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Hosting.Server.Features; using Microsoft.Extensions.DependencyInjection; using System.Net; +using System.Runtime.Loader; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; @@ -37,6 +38,7 @@ public abstract class WebHostFixture : IBackendFixture private static readonly object _sync = new object(); private static WebApplication? _app; private static bool _isInitialized; + private static bool _shutdownHooksRegistered; private static int _instanceCount; private static readonly List _sharedAddresses = new(); private static IServiceProvider? _sharedServices; @@ -63,6 +65,8 @@ public abstract class WebHostFixture : IBackendFixture { lock (_sync) { + RegisterShutdownHooks(); + if (!_isInitialized) { InitializeAsync().GetAwaiter().GetResult(); @@ -114,11 +118,19 @@ public abstract class WebHostFixture : IBackendFixture /// listen port. protected virtual int HttpsPort => 5101; + /// Options used to create the WebApplicationBuilder. + /// Derived fixtures can override (for example, to set + /// ApplicationName for MVC controller discovery). + protected virtual WebApplicationOptions CreateBuilderOptions() + { + return new WebApplicationOptions(); + } + public WebApplication App { get; private set; } private async Task InitializeAsync() { - var builder = WebApplication.CreateBuilder(); + var builder = WebApplication.CreateBuilder(CreateBuilderOptions()); builder.WebHost.ConfigureKestrel(options => { @@ -158,23 +170,40 @@ public abstract class WebHostFixture : IBackendFixture _instanceCount--; } - IsInitialized = false; + IsInitialized = _isInitialized; - if (_instanceCount > 0) + // Keep the shared host alive for the whole test process. + // Disposing per class/collection can race with other test + // classes and intermittently drop the listener mid-run. + } + } + + private static void RegisterShutdownHooks() + { + if (_shutdownHooksRegistered) + { + return; + } + + AppDomain.CurrentDomain.ProcessExit += (_, __) => ShutdownSharedHost(); + AssemblyLoadContext.Default.Unloading += _ => ShutdownSharedHost(); + _shutdownHooksRegistered = true; + } + + private static void ShutdownSharedHost() + { + lock (_sync) + { + if (!_isInitialized || _app is null) { return; } - if (!_isInitialized) - { - return; - } - - _app?.StopAsync().GetAwaiter().GetResult(); + _app.StopAsync().GetAwaiter().GetResult(); _app = null; _isInitialized = false; - _sharedAddresses.Clear(); _sharedServices = null; + _sharedAddresses.Clear(); } } From 67715f9d67464eae572fa71748655db99dc7a9a6 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sat, 12 Sep 2026 17:31:18 +0100 Subject: [PATCH 55/67] tests en vert --- .../Fixtures/ApiWebServerFixture.cs | 20 ++------ src/Yavsc.Blogs.Tests/BlogAclApiTests.cs | 51 +++++++++++-------- .../Fixtures/BlogsWebServerFixture.cs | 34 +++---------- 3 files changed, 40 insertions(+), 65 deletions(-) diff --git a/src/Yavsc.Api.Test/Fixtures/ApiWebServerFixture.cs b/src/Yavsc.Api.Test/Fixtures/ApiWebServerFixture.cs index d8663ed8f..96c220bff 100644 --- a/src/Yavsc.Api.Test/Fixtures/ApiWebServerFixture.cs +++ b/src/Yavsc.Api.Test/Fixtures/ApiWebServerFixture.cs @@ -357,21 +357,9 @@ public sealed class ApiWebServerFixture : WebHostFixture public override void Dispose() { - try - { - base.Dispose(); - } - finally - { - lock (_sqliteLock) - { - if (_sharedSqliteConnection is not null) - { - _sharedSqliteConnection.Close(); - _sharedSqliteConnection.Dispose(); - _sharedSqliteConnection = null; - } - } - } + // Keep the shared in-memory SQLite connection alive for the + // whole test process. Closing it from one fixture instance can + // drop the schema while other tests are still running. + base.Dispose(); } } diff --git a/src/Yavsc.Blogs.Tests/BlogAclApiTests.cs b/src/Yavsc.Blogs.Tests/BlogAclApiTests.cs index ab5ebcc66..174838173 100644 --- a/src/Yavsc.Blogs.Tests/BlogAclApiTests.cs +++ b/src/Yavsc.Blogs.Tests/BlogAclApiTests.cs @@ -51,7 +51,7 @@ public sealed class BlogAclApiTests : IClassFixture private string BlogAclUrl() => $"{_fixture.Addresses.First(a => a.StartsWith("https://"))}/{APIPrefix}/{BlogAclPath}"; - /// Delete any ACL rows tied to the fixture's seeded + /// Delete any ACL rows tied to the specified /// (CircleId, BlogPostId) pair. The shared SQLite store /// persists across tests, so tests that POST a successful ACL /// row would otherwise conflict with whichever other test runs @@ -59,13 +59,13 @@ public sealed class BlogAclApiTests : IClassFixture /// execution order. Calling this at the start of each /// insert-bearing test guarantees a clean slate regardless of /// the previous test's outcome. - private void CleanupAcl() + private void CleanupAcl(long circleId, long blogPostId) { using var scope = _fixture.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); db.CircleAuthorizationToBlogPost - .Where(a => a.CircleId == _fixture.CircleId - && a.BlogPostId == _fixture.PostId) + .Where(a => a.CircleId == circleId + && a.BlogPostId == blogPostId) .ExecuteDelete(); } @@ -122,13 +122,16 @@ public sealed class BlogAclApiTests : IClassFixture // The prod circle already exists with Name="test", Public=true, // owned by the caller. We seed the same shape pre-POST so the // test reproduces the prod scenario end-to-end. - CleanupAcl(); + _fixture.SeedUser(_fixture.DefaultUserLogin); + var seededCircleId = _fixture.SeedCircle(_fixture.DefaultUserLogin, "test"); + var seededBlogPostId = _fixture.SeedBlogPost(_fixture.DefaultUserLogin, "acl-target"); + CleanupAcl(seededCircleId, seededBlogPostId); using var http = NewClient(_fixture.DefaultUserLogin); var payload = new PostAccessControlRulePayload { - CircleId = _fixture.CircleId, - BlogPostId = _fixture.PostId + CircleId = seededCircleId, + BlogPostId = seededBlogPostId }; var response = await http.PostAsJsonAsync( @@ -194,13 +197,16 @@ public sealed class BlogAclApiTests : IClassFixture [Fact] async Task PostCircleAuthorization_dosent_return_500 () { - CleanupAcl(); + _fixture.SeedUser(_fixture.DefaultUserLogin); + var seededCircleId = _fixture.SeedCircle(_fixture.DefaultUserLogin, "test-" + Guid.NewGuid().ToString("N")); + var seededBlogPostId = _fixture.SeedBlogPost(_fixture.DefaultUserLogin, "acl-never-500"); + CleanupAcl(seededCircleId, seededBlogPostId); await PostCircleAuthorization_never_returns_500( new PostAccessControlRulePayload { BlogPostId = -1, - CircleId = _fixture.CircleId + CircleId = seededCircleId } ); @@ -209,13 +215,16 @@ public sealed class BlogAclApiTests : IClassFixture [Fact] async Task PostCircleAuthorization_dosent_return_500_on_success () { - CleanupAcl(); + _fixture.SeedUser(_fixture.DefaultUserLogin); + var seededCircleId = _fixture.SeedCircle(_fixture.DefaultUserLogin, "test-" + Guid.NewGuid().ToString("N")); + var seededBlogPostId = _fixture.SeedBlogPost(_fixture.DefaultUserLogin, "acl-never-500-success"); + CleanupAcl(seededCircleId, seededBlogPostId); await PostCircleAuthorization_never_returns_500( new PostAccessControlRulePayload { - BlogPostId = _fixture.PostId, - CircleId = _fixture.CircleId + BlogPostId = seededBlogPostId, + CircleId = seededCircleId } ); @@ -224,16 +233,17 @@ public sealed class BlogAclApiTests : IClassFixture [Fact] public async Task PostBlog_with_ACL_creates_a_post_and_Get_returns_it_in_the_list() { - CleanupAcl(); _fixture.SeedUser(_fixture.DefaultUserLogin); _fixture.SeedUser("tester"); - _fixture.SeedCircle(_fixture.DefaultUserLogin, "test", + var seededCircleId = _fixture.SeedCircle(_fixture.DefaultUserLogin, "test-" + Guid.NewGuid().ToString("N"), false, new String[] { _fixture.DefaultUserLogin, "tester" }); + var seededBlogPostId = _fixture.SeedBlogPost(_fixture.DefaultUserLogin, "acl-seeded-target"); + CleanupAcl(seededCircleId, seededBlogPostId); using var http = NewClient(_fixture.DefaultUserLogin ); // Create a minimal BlogPost. The server assigns Id, so we @@ -252,8 +262,8 @@ public sealed class BlogAclApiTests : IClassFixture { new CircleAuthorizationToBlogPost { - CircleId = _fixture.CircleId, - BlogPostId = _fixture.PostId + CircleId = seededCircleId, + BlogPostId = seededBlogPostId } } ) @@ -303,17 +313,16 @@ public sealed class BlogAclApiTests : IClassFixture var aclEntry = acl[0]; Assert.Equal(JsonValueKind.Object, aclEntry.ValueKind); - Assert.True(aclEntry.TryGetProperty("circleId", out var circleId)); - Assert.Equal(_fixture.CircleId, circleId.GetInt64()); + Assert.True(aclEntry.TryGetProperty("circleId", out var returnedCircleId)); + Assert.Equal(seededCircleId, returnedCircleId.GetInt64()); } [Fact] public async Task Non_owner_can_read_restricted_post_but_receives_empty_acl_in_list_and_detail() { - CleanupAcl(); _fixture.SeedUser(_fixture.DefaultUserLogin); _fixture.SeedUser("tester"); - _fixture.SeedCircle(_fixture.DefaultUserLogin, "test", false, + var seededCircleId = _fixture.SeedCircle(_fixture.DefaultUserLogin, "test-" + Guid.NewGuid().ToString("N"), false, new[] { _fixture.DefaultUserLogin, "tester" }); using var ownerHttp = NewClient(_fixture.DefaultUserLogin); @@ -343,7 +352,7 @@ public sealed class BlogAclApiTests : IClassFixture BlogAclUrl(), new PostAccessControlRulePayload { - CircleId = _fixture.CircleId, + CircleId = seededCircleId, BlogPostId = created.Id }, TestContext.Current.CancellationToken); diff --git a/src/Yavsc.Blogs.Tests/Fixtures/BlogsWebServerFixture.cs b/src/Yavsc.Blogs.Tests/Fixtures/BlogsWebServerFixture.cs index ea6837b1c..e0606f5d7 100644 --- a/src/Yavsc.Blogs.Tests/Fixtures/BlogsWebServerFixture.cs +++ b/src/Yavsc.Blogs.Tests/Fixtures/BlogsWebServerFixture.cs @@ -289,33 +289,11 @@ public sealed class BlogsWebServerFixture : WebHostFixture public override void Dispose() { - try - { - base.Dispose(); - } - finally - { - // Close the shared SQLite connection only when the - // last fixture instance goes away, matching the - // lifetime contract of WebHostFixture.Dispose. We - // rely on base.Dispose's _instanceCount decrement - // having run, so we close only if the host is gone - // (base already nulled _app when count==0). - lock (_sqliteLock) - { - if (_sharedSqliteConnection is not null) - { - // Synchronous close: SQLite's Close() is - // documented as safe to call from a sync - // context and avoids the GetAwaiter().GetResult() - // pattern that's historically caused teardown - // hangs in this repo's async pipeline. - _sharedSqliteConnection.Close(); - _sharedSqliteConnection.Dispose(); - _sharedSqliteConnection = null; - } - } - } + // Keep the shared in-memory SQLite connection alive for the + // whole test process. Closing it from one fixture instance can + // destroy the database while other collections are still using + // it, which surfaces as intermittent "no such table" failures. + base.Dispose(); } /// Seed an in the shared @@ -374,7 +352,7 @@ public sealed class BlogsWebServerFixture : WebHostFixture /// directly in the SQLite store and return its server-assigned /// id. public long SeedCircle(string ownerId, string name, bool isPublic = false, - ICollection members = null + ICollection? members = null ) { using var scope = Services.CreateScope(); From cbb59f019dd94253a5784d7073d04c3cf8724452 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sun, 13 Sep 2026 03:09:12 +0100 Subject: [PATCH 56/67] got saved a RdvQuery --- .forgejo/workflows/buildAndTest.yml | 4 +- .vscode/tasks.json | 22 ++ .../ViewModels/Commands/RdvViewModel.cs | 52 ++++- .../PostIt/ViewModels/Layout/StatusNotice.cs | 4 +- src/Yavsc.Api.Client/BillingApiClient.cs | 9 + src/Yavsc.Api.Client/BlogApiClient.cs | 5 - .../Dtos/BillingQueryDetailsDto.cs | 8 + src/Yavsc.Api.Test/BillingControllerTests.cs | 53 +++++ .../Fixtures/ApiWebServerFixture.cs | 163 ++++++++++++++- .../RdvQueryApiControllerTests.cs | 83 ++++++++ .../Controllers/Business/BillingController.cs | 30 ++- .../Business/BookQueryApiController.cs | 193 ------------------ .../Business/RdvQueryApiController.cs | 130 +++++++++--- src/Yavsc.Api/Program.cs | 3 + ...egacyNominativeServiceCommandLocationId.cs | 63 ++++++ .../Interfaces/IConnexionManager.cs | 2 +- .../Services/HubConnectionManager.cs} | 84 ++++---- 17 files changed, 618 insertions(+), 290 deletions(-) delete mode 100644 src/Yavsc.Api/Controllers/Business/BookQueryApiController.cs create mode 100644 src/Yavsc.Org/Migrations/20260913022000_cleanupLegacyNominativeServiceCommandLocationId.cs rename src/{Yavsc.Org/Services/ChatHubConnexionManager.cs => Yavsc.Server/Services/HubConnectionManager.cs} (81%) diff --git a/.forgejo/workflows/buildAndTest.yml b/.forgejo/workflows/buildAndTest.yml index 5246e6c81..4e7bea2e4 100644 --- a/.forgejo/workflows/buildAndTest.yml +++ b/.forgejo/workflows/buildAndTest.yml @@ -48,8 +48,8 @@ jobs: - name: Test run: | echo "🚀 Lancement des tests..." + export YAVSC_API_TEST_DB_PROVIDER=npgsql cd /src/_src && dotnet test \ --verbosity normal \ --filter="Category!=Platform-Android" \ - --logger "xunit;LogFileName=test-results.xml" \ - && echo "✅ Success !" || { echo "❌ Fail ($?)!"; exit 1; } + --logger "xunit;LogFileName=test-results.xml" diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 82721d8a2..f5bcc21a2 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -66,6 +66,28 @@ "isDefault": false } }, + { + "label": "test api backend (npgsql)", + "type": "process", + "problemMatcher": ["$msCompile"], + "command": "dotnet", + "args": [ + "test", + "Yavsc.Api.Test.csproj", + "-v", + "minimal" + ], + "options": { + "cwd": "src/Yavsc.Api.Test", + "env": { + "YAVSC_API_TEST_DB_PROVIDER": "npgsql", + } + }, + "group": { + "kind": "test", + "isDefault": false + } + }, { "label": "build-webapi", "type": "process", diff --git a/src/PostIt/PostIt/ViewModels/Commands/RdvViewModel.cs b/src/PostIt/PostIt/ViewModels/Commands/RdvViewModel.cs index 7a7d17df6..4f9d457a5 100644 --- a/src/PostIt/PostIt/ViewModels/Commands/RdvViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/Commands/RdvViewModel.cs @@ -12,6 +12,9 @@ namespace PostIt.ViewModels.Commands; public partial class RdvViewModel : BillingCommandPageViewModel { + private long? _existingLocationId; + private bool _hydratingExistingQuery; + public override string SupportMessage => "Complétez les informations du rendez-vous puis postez la commande."; [ObservableProperty] @@ -56,6 +59,7 @@ public partial class RdvViewModel : BillingCommandPageViewModel protected override void ApplyExistingQuery(BillingQueryDetailsDto existingQuery) { + _hydratingExistingQuery = true; ExistingQueryId = existingQuery.Id; CommandStatus = existingQuery.Status; Consent = existingQuery.Consent; @@ -70,11 +74,18 @@ public partial class RdvViewModel : BillingCommandPageViewModel if (existingQuery.Location is not null) { + _existingLocationId = existingQuery.Location.Id; Address = existingQuery.Location.Address ?? string.Empty; SuggestedAddress = string.Empty; Latitude = existingQuery.Location.Latitude; Longitude = existingQuery.Location.Longitude; } + else + { + _existingLocationId = null; + } + + _hydratingExistingQuery = false; this.SetInfoStatus($"Commande #{existingQuery.Id} chargée."); } @@ -117,20 +128,22 @@ public partial class RdvViewModel : BillingCommandPageViewModel } } - protected static object BuildLocationPayload(string address, double? latitude, double? longitude) + protected static BillingLocationDto BuildLocationPayload(string address, double? latitude, double? longitude, long? locationId = null) { if (latitude.HasValue && longitude.HasValue) { - return new + return new BillingLocationDto { + Id = locationId, Address = address, Latitude = latitude.Value, Longitude = longitude.Value, }; } - return new + return new BillingLocationDto { + Id = locationId, Address = address, }; } @@ -223,6 +236,30 @@ public partial class RdvViewModel : BillingCommandPageViewModel OnPropertyChanged(nameof(EventDateSelection)); } + partial void OnAddressChanged(string value) + { + if (_hydratingExistingQuery) + return; + + _existingLocationId = null; + } + + partial void OnLatitudeChanged(double? value) + { + if (_hydratingExistingQuery) + return; + + _existingLocationId = null; + } + + partial void OnLongitudeChanged(double? value) + { + if (_hydratingExistingQuery) + return; + + _existingLocationId = null; + } + protected override async Task SubmitAsync() { @@ -257,7 +294,7 @@ public partial class RdvViewModel : BillingCommandPageViewModel try { var address = Address.Trim(); - var locationPayload = BuildLocationPayload(address, Latitude, Longitude); + var locationPayload = BuildLocationPayload(address, Latitude, Longitude, IsEditingExisting ? _existingLocationId : null); var payload = new BillingQueryDetailsDto { @@ -270,12 +307,7 @@ public partial class RdvViewModel : BillingCommandPageViewModel Status = CommandStatus, Reason = Reason.Trim(), AdditionalInfo = string.IsNullOrWhiteSpace(AdditionalInfo) ? string.Empty : AdditionalInfo.Trim(), - Location = new BillingLocationDto - { - Address = address, - Latitude = Latitude, - Longitude = Longitude, - } + Location = locationPayload }; if (IsEditingExisting) diff --git a/src/PostIt/PostIt/ViewModels/Layout/StatusNotice.cs b/src/PostIt/PostIt/ViewModels/Layout/StatusNotice.cs index 972c64350..c87af390c 100644 --- a/src/PostIt/PostIt/ViewModels/Layout/StatusNotice.cs +++ b/src/PostIt/PostIt/ViewModels/Layout/StatusNotice.cs @@ -23,8 +23,8 @@ public sealed class StatusNotice (Glyph, Background, BorderBrush, Foreground) = severity switch { - StatusSeverity.Error => ("!", "#FDECEA", "#C62828", "#7F1D1D"), - StatusSeverity.Warning => ("~", "#FFF8E1", "#E6A700", "#7C4A03"), + StatusSeverity.Error => ("!", "#7F1D1D", "#C62828", "#e1f0f6"), + StatusSeverity.Warning => ("~", "#7C4A03", "#E6A700", "#eaeaea"), _ => ("i", "#E8F0FE", "#5B8DEF", "#1E3A8A"), }; } diff --git a/src/Yavsc.Api.Client/BillingApiClient.cs b/src/Yavsc.Api.Client/BillingApiClient.cs index 3907dda25..a9e9deda6 100644 --- a/src/Yavsc.Api.Client/BillingApiClient.cs +++ b/src/Yavsc.Api.Client/BillingApiClient.cs @@ -164,6 +164,7 @@ public sealed class BillingApiClient ? null : new BillingLocationDto { + Id = dto.Location.Id > 0 ? dto.Location.Id : null, Address = dto.Location.Address ?? string.Empty, Latitude = dto.Location.Latitude, Longitude = dto.Location.Longitude, @@ -191,6 +192,7 @@ public sealed class BillingApiClient ? null : new BillingLocationDto { + Id = dto.Location.Id > 0 ? dto.Location.Id : null, Address = dto.Location.Address ?? string.Empty, Latitude = dto.Location.Latitude, Longitude = dto.Location.Longitude, @@ -220,6 +222,7 @@ public sealed class BillingApiClient ? null : new BillingLocationDto { + Id = dto.Location.Id > 0 ? dto.Location.Id : null, Address = dto.Location.Address ?? string.Empty, Latitude = dto.Location.Latitude, Longitude = dto.Location.Longitude, @@ -313,6 +316,11 @@ public sealed class BillingApiClient ["Address"] = location.Address, }; + if (location.Id.HasValue && location.Id.Value > 0) + { + payload["Id"] = location.Id.Value; + } + if (location.Latitude.HasValue) { payload["Latitude"] = location.Latitude.Value; @@ -328,6 +336,7 @@ public sealed class BillingApiClient private sealed class BillingLocationResponse { + public long Id { get; set; } public string? Address { get; set; } public double Latitude { get; set; } public double Longitude { get; set; } diff --git a/src/Yavsc.Api.Client/BlogApiClient.cs b/src/Yavsc.Api.Client/BlogApiClient.cs index 6c0f538ea..3de5b37ec 100644 --- a/src/Yavsc.Api.Client/BlogApiClient.cs +++ b/src/Yavsc.Api.Client/BlogApiClient.cs @@ -1,10 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Net.Http; using System.Net.Http.Headers; using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; using Yavsc.Blogspot; namespace Yavsc.Api.Client; diff --git a/src/Yavsc.Api.Client/Dtos/BillingQueryDetailsDto.cs b/src/Yavsc.Api.Client/Dtos/BillingQueryDetailsDto.cs index 6d658ce49..eb33ba816 100644 --- a/src/Yavsc.Api.Client/Dtos/BillingQueryDetailsDto.cs +++ b/src/Yavsc.Api.Client/Dtos/BillingQueryDetailsDto.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Text.Json.Serialization; using Yavsc; namespace Yavsc.Api.Client; @@ -29,7 +30,14 @@ public sealed class BillingQueryDetailsDto public sealed class BillingLocationDto { + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public long? Id { get; set; } + public string Address { get; set; } = string.Empty; + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public double? Latitude { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public double? Longitude { get; set; } } diff --git a/src/Yavsc.Api.Test/BillingControllerTests.cs b/src/Yavsc.Api.Test/BillingControllerTests.cs index a6445c776..d06ae7dba 100644 --- a/src/Yavsc.Api.Test/BillingControllerTests.cs +++ b/src/Yavsc.Api.Test/BillingControllerTests.cs @@ -1,6 +1,7 @@ using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; +using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Yavsc.Api.Test.Fixtures; using Yavsc.Helpers; @@ -101,6 +102,58 @@ public sealed class BillingControllerTests : IClassFixture Assert.Contains(payload!, item => item.BillingCode == BillingCodes.Rdv); } + [Fact] + public async Task GetProviderOngoingCommands_ignores_rows_with_invalid_discriminator() + { + WorkflowHelpers.ConfigureBillingService(); + _fixture.ResetAndSeedActivityGraph(); + + using (var scope = _fixture.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + + db.Database.ExecuteSqlInterpolated($@" +INSERT INTO ""NominativeServiceCommand"" +(""ActivityCode"", ""ClientId"", ""Consent"", ""DateCreated"", ""DateModified"", ""Description"", ""Discriminator"", ""PerformerId"", ""Status"", ""UserCreated"", ""UserModified"") +VALUES +({"dev"}, {"bob"}, {true}, {DateTime.UtcNow.AddMinutes(-5)}, {DateTime.UtcNow.AddMinutes(-4)}, {"Legacy malformed row"}, {""}, {"alice"}, {(int)QueryStatus.Accepted}, {"alice"}, {"alice"}); +"); + + var location = db.Locations.Single(); + db.RdvQueries.Add(new RdvQuery + { + ActivityCode = "dev", + ClientId = "bob", + PerformerId = "alice", + Consent = true, + UserCreated = "alice", + UserModified = "alice", + DateCreated = DateTime.UtcNow.AddMinutes(-3), + DateModified = DateTime.UtcNow.AddMinutes(-2), + EventDate = DateTime.UtcNow.AddDays(1), + Location = location, + Reason = "Commande valide", + Status = QueryStatus.InProgress, + Description = "Commande fournisseur valide", + }); + + db.SaveChanges(); + } + + using var http = NewClient(); + + var response = await http.GetAsync("/api/v1/bill/provider/ongoing", 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}"); + + var payload = await response.Content.ReadFromJsonAsync>(TestContext.Current.CancellationToken); + Assert.NotNull(payload); + Assert.NotEmpty(payload!); + Assert.Contains(payload!, item => item.BillingCode == BillingCodes.Rdv && item.PerformerId == "alice"); + Assert.DoesNotContain(payload!, item => string.IsNullOrWhiteSpace(item.BillingCode)); + } + private sealed class ProviderOngoingCommandDto { public long Id { get; set; } diff --git a/src/Yavsc.Api.Test/Fixtures/ApiWebServerFixture.cs b/src/Yavsc.Api.Test/Fixtures/ApiWebServerFixture.cs index 96c220bff..3079e48c5 100644 --- a/src/Yavsc.Api.Test/Fixtures/ApiWebServerFixture.cs +++ b/src/Yavsc.Api.Test/Fixtures/ApiWebServerFixture.cs @@ -3,6 +3,8 @@ using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Tokens; +using Npgsql; +using System.Runtime.Loader; using Yavsc.Controllers; using Yavsc.Interfaces.Workflow; using Yavsc.Models; @@ -18,27 +20,45 @@ namespace Yavsc.Api.Test.Fixtures; public sealed class ApiWebServerFixture : WebHostFixture { + private const string DbProviderEnvVar = "YAVSC_API_TEST_DB_PROVIDER"; + private const string NpgsqlAdminConnectionEnvVar = "YAVSC_API_TEST_NPGSQL_ADMIN_CONNECTION"; + private const string DefaultDevelopmentConnectionString = "Server=localhost;Port=5432;Database=yavscdev;Username=yavscdev;Password=8*5idas;Include Error Detail=true"; + protected override int HttpsPort => 5104; private static SqliteConnection? _sharedSqliteConnection; private static readonly object _sqliteLock = new(); + private static readonly object _npgsqlLock = new(); + private static string? _sharedNpgsqlConnectionString; + private static string? _sharedNpgsqlAdminConnectionString; + private static string? _sharedNpgsqlDatabaseName; + private static bool _npgsqlCleanupRegistered; protected override WebApplication BuildApp(WebApplicationBuilder builder) { - SqliteConnection sharedConnection; - lock (_sqliteLock) + if (UseNpgsqlProvider()) { - if (_sharedSqliteConnection is null) - { - _sharedSqliteConnection = new SqliteConnection( - "Data Source=YavscApiTests;Mode=Memory;Cache=Shared"); - _sharedSqliteConnection.Open(); - } - sharedConnection = _sharedSqliteConnection; + var npgsqlConnectionString = EnsureNpgsqlDatabaseCreated(); + builder.Services.AddDbContext(opt => + opt.UseNpgsql(npgsqlConnectionString)); } + else + { + SqliteConnection sharedConnection; + lock (_sqliteLock) + { + if (_sharedSqliteConnection is null) + { + _sharedSqliteConnection = new SqliteConnection( + "Data Source=YavscApiTests;Mode=Memory;Cache=Shared"); + _sharedSqliteConnection.Open(); + } + sharedConnection = _sharedSqliteConnection; + } - builder.Services.AddDbContext(opt => - opt.UseSqlite(sharedConnection)); + builder.Services.AddDbContext(opt => + opt.UseSqlite(sharedConnection)); + } builder.Services.AddControllers() .AddApplicationPart(typeof(ActivityApiController).Assembly); @@ -90,6 +110,127 @@ public sealed class ApiWebServerFixture : WebHostFixture public string BaseAddress => Addresses.First(a => a.StartsWith("https://", StringComparison.Ordinal)); + public static bool UseNpgsqlProvider() + => string.Equals( + Environment.GetEnvironmentVariable(DbProviderEnvVar), + "npgsql", + StringComparison.OrdinalIgnoreCase); + + private static string EnsureNpgsqlDatabaseCreated() + { + lock (_npgsqlLock) + { + if (!string.IsNullOrWhiteSpace(_sharedNpgsqlConnectionString)) + { + return _sharedNpgsqlConnectionString; + } + + var adminConnectionString = BuildAdminConnectionString(); + var databaseName = $"yavsc_api_test_{Guid.NewGuid():N}"; + + using (var adminConnection = new NpgsqlConnection(adminConnectionString)) + { + adminConnection.Open(); + using var createCommand = adminConnection.CreateCommand(); + createCommand.CommandText = $"CREATE DATABASE \"{databaseName}\""; + createCommand.ExecuteNonQuery(); + } + + var testConnectionBuilder = new NpgsqlConnectionStringBuilder(adminConnectionString) + { + Database = databaseName, + Pooling = false, + IncludeErrorDetail = true + }; + + _sharedNpgsqlAdminConnectionString = adminConnectionString; + _sharedNpgsqlDatabaseName = databaseName; + _sharedNpgsqlConnectionString = testConnectionBuilder.ToString(); + RegisterNpgsqlCleanup(); + return _sharedNpgsqlConnectionString; + } + } + + private static string BuildAdminConnectionString() + { + var configured = Environment.GetEnvironmentVariable(NpgsqlAdminConnectionEnvVar); + var source = string.IsNullOrWhiteSpace(configured) + ? DefaultDevelopmentConnectionString + : configured; + + var builder = new NpgsqlConnectionStringBuilder(source) + { + Pooling = false, + IncludeErrorDetail = true + }; + + if (string.IsNullOrWhiteSpace(configured)) + { + builder.Database = "postgres"; + } + else if (string.IsNullOrWhiteSpace(builder.Database)) + { + builder.Database = "postgres"; + } + + return builder.ToString(); + } + + private static void RegisterNpgsqlCleanup() + { + if (_npgsqlCleanupRegistered) + { + return; + } + + AppDomain.CurrentDomain.ProcessExit += (_, __) => DropTemporaryNpgsqlDatabase(); + AssemblyLoadContext.Default.Unloading += _ => DropTemporaryNpgsqlDatabase(); + _npgsqlCleanupRegistered = true; + } + + private static void DropTemporaryNpgsqlDatabase() + { + lock (_npgsqlLock) + { + if (string.IsNullOrWhiteSpace(_sharedNpgsqlDatabaseName) + || string.IsNullOrWhiteSpace(_sharedNpgsqlAdminConnectionString)) + { + return; + } + + try + { + using var adminConnection = new NpgsqlConnection(_sharedNpgsqlAdminConnectionString); + adminConnection.Open(); + + using (var terminateCommand = adminConnection.CreateCommand()) + { + terminateCommand.CommandText = @" +SELECT pg_terminate_backend(pid) +FROM pg_stat_activity +WHERE datname = @databaseName + AND pid <> pg_backend_pid();"; + terminateCommand.Parameters.AddWithValue("databaseName", _sharedNpgsqlDatabaseName); + terminateCommand.ExecuteNonQuery(); + } + + using var dropCommand = adminConnection.CreateCommand(); + dropCommand.CommandText = $"DROP DATABASE IF EXISTS \"{_sharedNpgsqlDatabaseName}\""; + dropCommand.ExecuteNonQuery(); + } + catch + { + // Best-effort cleanup only. + } + finally + { + _sharedNpgsqlConnectionString = null; + _sharedNpgsqlAdminConnectionString = null; + _sharedNpgsqlDatabaseName = null; + } + } + } + private sealed class NoopMessageSender : IYavscMessageSender { public Task NotifyBookQueryAsync(IEnumerable connectionIds, RdvQueryEvent ev) diff --git a/src/Yavsc.Api.Test/RdvQueryApiControllerTests.cs b/src/Yavsc.Api.Test/RdvQueryApiControllerTests.cs index 668814239..c3e4aad2b 100644 --- a/src/Yavsc.Api.Test/RdvQueryApiControllerTests.cs +++ b/src/Yavsc.Api.Test/RdvQueryApiControllerTests.cs @@ -143,4 +143,87 @@ public sealed class RdvQueryApiControllerTests : IClassFixture(TestContext.Current.CancellationToken); + Assert.NotNull(created); + Assert.NotNull(created!.Location); + Assert.True(created.Location.Id > 0); + Assert.NotEqual(999999L, created.Location.Id); + Assert.Equal("alice", created.ClientId); + } + + [Fact] + public async Task PostQuery_without_location_returns_bad_request() + { + _fixture.ResetAndSeedRdvQueryGraph(); + using var http = NewClient(subject: "alice"); + + var createPayload = new + { + ActivityCode = "dev", + PerformerId = "alice", + Consent = true, + EventDate = DateTime.UtcNow.AddDays(1), + Reason = "Rendez-vous sans location", + Status = QueryStatus.Inserted, + }; + + var createResponse = await http.PostAsJsonAsync("/api/v1/billing/Rdv", createPayload, TestContext.Current.CancellationToken); + Assert.Equal(HttpStatusCode.BadRequest, createResponse.StatusCode); + } + + [Fact] + public async Task PostQuery_with_unknown_location_id_and_missing_address_returns_bad_request() + { + _fixture.ResetAndSeedRdvQueryGraph(); + using var http = NewClient(subject: "alice"); + + var createPayload = new + { + ActivityCode = "dev", + PerformerId = "alice", + Consent = true, + EventDate = DateTime.UtcNow.AddDays(1), + Location = new + { + Id = 777777L, + Address = "", + Latitude = 0.0, + Longitude = 0.0, + }, + Reason = "Rendez-vous location invalide", + Status = QueryStatus.Inserted, + }; + + var createResponse = await http.PostAsJsonAsync("/api/v1/billing/Rdv", createPayload, TestContext.Current.CancellationToken); + Assert.Equal(HttpStatusCode.BadRequest, createResponse.StatusCode); + } } diff --git a/src/Yavsc.Api/Controllers/Business/BillingController.cs b/src/Yavsc.Api/Controllers/Business/BillingController.cs index 5f9349559..219431b7e 100644 --- a/src/Yavsc.Api/Controllers/Business/BillingController.cs +++ b/src/Yavsc.Api/Controllers/Business/BillingController.cs @@ -7,6 +7,8 @@ using Yavsc.Billing; using Yavsc.Helpers; using Yavsc.ViewModels; using Yavsc.Models.Billing; +using Yavsc.Models.Haircut; +using Yavsc.Models.Workflow; using Yavsc.Server.Models.FileSystem; namespace Yavsc.ApiControllers @@ -121,12 +123,38 @@ namespace Yavsc.ApiControllers WorkflowHelpers.ConfigureBillingService(); } - var commands = dbContext.Set() + // Query known derived types explicitly so legacy rows with + // invalid/empty discriminator values are naturally ignored. + var rdvCommands = dbContext.Set() .AsNoTracking() .Where(q => q.PerformerId == uid) .Where(q => q.Status == QueryStatus.Inserted || q.Status == QueryStatus.Accepted || q.Status == QueryStatus.InProgress) + .Cast() + .ToList(); + + var hairCommands = dbContext.Set() + .AsNoTracking() + .Where(q => q.PerformerId == uid) + .Where(q => q.Status == QueryStatus.Inserted + || q.Status == QueryStatus.Accepted + || q.Status == QueryStatus.InProgress) + .Cast() + .ToList(); + + var hairMultiCommands = dbContext.Set() + .AsNoTracking() + .Where(q => q.PerformerId == uid) + .Where(q => q.Status == QueryStatus.Inserted + || q.Status == QueryStatus.Accepted + || q.Status == QueryStatus.InProgress) + .Cast() + .ToList(); + + var commands = rdvCommands + .Concat(hairCommands) + .Concat(hairMultiCommands) .OrderByDescending(q => q.DateModified) .ThenByDescending(q => q.Id) .ToList(); diff --git a/src/Yavsc.Api/Controllers/Business/BookQueryApiController.cs b/src/Yavsc.Api/Controllers/Business/BookQueryApiController.cs deleted file mode 100644 index 293cca9ae..000000000 --- a/src/Yavsc.Api/Controllers/Business/BookQueryApiController.cs +++ /dev/null @@ -1,193 +0,0 @@ -using System.Security.Claims; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace Yavsc.Controllers -{ - using System; - using Yavsc.Models; - using Yavsc.Models.Workflow; - using Yavsc.Models.Billing; - using Yavsc.Abstract.Identity; - using Microsoft.EntityFrameworkCore; - using Yavsc.Server.Helpers; - - [Authorize] - [Produces("application/json")] - [Route(Constants.APIPrefix + "/bookquery"), Authorize("Performer")] - public class BookQueryApiController : Controller - { - private ApplicationDbContext _context; - private ILogger _logger; - - public BookQueryApiController(ApplicationDbContext context, ILoggerFactory loggerFactory) - { - _context = context; - _logger = loggerFactory.CreateLogger(); - } - - // GET: api/BookQueryApi - /// - /// Book queries, by creation order - /// - /// returned Ids must be lower than this value - /// book queries - [HttpGet] - public IEnumerable GetCommands(long maxId=long.MaxValue) - { - var uid = User.FindFirstValue(ClaimTypes.NameIdentifier); - var now = DateTime.UtcNow; - - var result = _context.RdvQueries.Include(c => c.Location). - Include(c => c.Client).Where(c => c.PerformerId == uid && c.Id < maxId && c.EventDate > now - && c.ValidationDate == null). - Select(c => new RdvQueryProviderInfo - { - Client = new ClientProviderInfo { - UserName = c.Client.UserName, - UserId = c.ClientId, - Avatar = c.Client.Avatar }, - Location = c.Location, - EventDate = c.EventDate, - Id = c.Id, - Previsional = c.Provisional, - Reason = c.Reason, - ActivityCode = c.ActivityCode, - BillingCode = BillingCodes.Rdv - }). - OrderBy(c=>c.Id). - Take(25); - return result; - } - - // GET: api/BookQueryApi/5 - [HttpGet("{id}", Name = "GetBookQuery")] - public IActionResult GetBookQuery([FromRoute] long id) - { - - if (!ModelState.IsValid) - { - return BadRequest(ModelState); - } - var uid = User.FindFirstValue(ClaimTypes.NameIdentifier); - - RdvQuery bookQuery = _context.RdvQueries.Where(c => c.ClientId == uid || c.PerformerId == uid).Single(m => m.Id == id); - - if (bookQuery == null) - { - return NotFound(); - } - - return Ok(bookQuery); - } - - // PUT: api/BookQueryApi/5 - [HttpPut("{id}")] - public IActionResult PutBookQuery(long id, [FromBody] RdvQuery bookQuery) - { - if (!ModelState.IsValid) - { - return BadRequest(ModelState); - } - - if (id != bookQuery.Id) - { - return BadRequest(); - } - var uid = User.FindFirstValue(ClaimTypes.NameIdentifier); - if (bookQuery.ClientId != uid) - return NotFound(); - - _context.Entry(bookQuery).State = EntityState.Modified; - - try - { - _context.SaveChanges(User.GetUserId()); - } - catch (DbUpdateConcurrencyException) - { - if (!BookQueryExists(id)) - { - return NotFound(); - } - else - { - throw; - } - } - - return new StatusCodeResult(StatusCodes.Status204NoContent); - } - - // POST: api/BookQueryApi - [HttpPost] - public IActionResult PostBookQuery([FromBody] RdvQuery bookQuery) - { - if (!ModelState.IsValid) - { - return BadRequest(ModelState); - } - var uid = User.FindFirstValue(ClaimTypes.NameIdentifier); - if (bookQuery.ClientId != uid) - { - ModelState.AddModelError("ClientId", "You must be the client at creating a book query"); - return new BadRequestObjectResult(ModelState); - } - _context.RdvQueries.Add(bookQuery); - try - { - _context.SaveChanges(User.GetUserId()); - } - catch (DbUpdateException) - { - if (BookQueryExists(bookQuery.Id)) - { - return new StatusCodeResult(StatusCodes.Status409Conflict); - } - else - { - throw; - } - } - - return CreatedAtRoute("GetBookQuery", new { id = bookQuery.Id }, bookQuery); - } - - // DELETE: api/BookQueryApi/5 - [HttpDelete("{id}")] - public IActionResult DeleteBookQuery(long id) - { - if (!ModelState.IsValid) - { - return BadRequest(ModelState); - } - var uid = User.FindFirstValue(ClaimTypes.NameIdentifier); - RdvQuery bookQuery = _context.RdvQueries.Single(m => m.Id == id); - - if (bookQuery == null) - { - return NotFound(); - } - if (bookQuery.ClientId != uid) return NotFound(); - - _context.RdvQueries.Remove(bookQuery); - _context.SaveChanges(User.GetUserId()); - - return Ok(bookQuery); - } - - protected override void Dispose(bool disposing) - { - if (disposing) - { - _context.Dispose(); - } - base.Dispose(disposing); - } - - private bool BookQueryExists(long id) - { - return _context.RdvQueries.Count(e => e.Id == id) > 0; - } - } -} diff --git a/src/Yavsc.Api/Controllers/Business/RdvQueryApiController.cs b/src/Yavsc.Api/Controllers/Business/RdvQueryApiController.cs index 48e3be2e1..06256a987 100644 --- a/src/Yavsc.Api/Controllers/Business/RdvQueryApiController.cs +++ b/src/Yavsc.Api/Controllers/Business/RdvQueryApiController.cs @@ -1,8 +1,13 @@ +#nullable enable annotations + using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; +using Npgsql; using Yavsc.Models; using Yavsc.Models.Billing; +using Yavsc.Models.Relationship; using Yavsc.Models.Workflow; using Yavsc.Server.Helpers; @@ -83,30 +88,32 @@ public class RdvQueryApiController : Controller return BadRequest(ModelState); } - if (query.Location is not null) + if (query.Location is null) { - var existingLocation = await _context.Locations.FirstOrDefaultAsync( - x => x.Address == query.Location.Address - && x.Longitude == query.Location.Longitude - && x.Latitude == query.Location.Latitude, - cancellationToken); - - if (existingLocation is not null) - { - query.Location = existingLocation; - } - else - { - _context.Attach(query.Location); - } + return BadRequest(new { Error = "location is required" }); } - _context.RdvQueries.Add(query); + var resolvedLocation = await ResolveLocationAsync(query.Location, cancellationToken); + if (resolvedLocation is null) + { + return BadRequest(new { Error = "location payload is invalid" }); + } + + await PersistLocationIfNeededAsync(resolvedLocation, uid, cancellationToken); + + query.Location = resolvedLocation; + + var addedEntry = _context.RdvQueries.Add(query); + EnsureLocationForeignKey(addedEntry, resolvedLocation.Id); try { await _context.SaveChangesAsync(User.GetUserId(), cancellationToken); } + catch (DbUpdateException ex) when (IsLocationForeignKeyViolation(ex)) + { + return BadRequest(new { Error = "location reference is invalid" }); + } catch (DbUpdateException) { if (QueryExists(query.Id)) @@ -149,17 +156,16 @@ public class RdvQueryApiController : Controller 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; + var resolvedLocation = await ResolveLocationAsync(query.Location, cancellationToken); if (resolvedLocation is null) { - _context.Attach(query.Location); + return BadRequest(new { Error = "location payload is invalid" }); } + + await PersistLocationIfNeededAsync(resolvedLocation, uid, cancellationToken); + + existing.Location = resolvedLocation; + EnsureLocationForeignKey(_context.Entry(existing), resolvedLocation.Id); } try @@ -175,6 +181,10 @@ public class RdvQueryApiController : Controller throw; } + catch (DbUpdateException ex) when (IsLocationForeignKeyViolation(ex)) + { + return BadRequest(new { Error = "location reference is invalid" }); + } return NoContent(); } @@ -208,6 +218,78 @@ public class RdvQueryApiController : Controller return _context.RdvQueries.Any(e => e.Id == id); } + private async Task ResolveLocationAsync(Location postedLocation, CancellationToken cancellationToken) + { + if (postedLocation.Id > 0) + { + var byId = await _context.Locations + .FirstOrDefaultAsync(x => x.Id == postedLocation.Id, cancellationToken); + if (byId is not null) + { + return byId; + } + } + + if (string.IsNullOrWhiteSpace(postedLocation.Address)) + { + return null; + } + + var existingByCoordinates = await _context.Locations.FirstOrDefaultAsync( + x => x.Address == postedLocation.Address + && x.Longitude == postedLocation.Longitude + && x.Latitude == postedLocation.Latitude, + cancellationToken); + + if (existingByCoordinates is not null) + { + return existingByCoordinates; + } + + // Treat unknown location ids as client-side placeholders and insert a new row. + postedLocation.Id = 0; + _context.Locations.Add(postedLocation); + return postedLocation; + } + + private async Task PersistLocationIfNeededAsync(Location location, string userId, CancellationToken cancellationToken) + { + if (_context.Entry(location).State != EntityState.Added) + { + return; + } + + await _context.SaveChangesAsync(userId, cancellationToken); + } + + private static bool IsLocationForeignKeyViolation(DbUpdateException ex) + { + if (ex.InnerException is not PostgresException pg) + { + return false; + } + + return pg.SqlState == PostgresErrorCodes.ForeignKeyViolation + && string.Equals(pg.ConstraintName, "FK_NominativeServiceCommand_Locations_LocationId", StringComparison.Ordinal); + } + + private static void EnsureLocationForeignKey(EntityEntry entry, long locationId) + { + SetFkIfPresent(entry, "LocationId", locationId); + SetFkIfPresent(entry, "RdvQuery_LocationId", locationId); + } + + private static void SetFkIfPresent(EntityEntry entry, string propertyName, long value) + { + var property = entry.Metadata.FindProperty(propertyName); + if (property is null) + { + return; + } + + entry.Property(propertyName).CurrentValue = value; + } + private static DateTime EnsureUtc(DateTime value) { return value.Kind switch diff --git a/src/Yavsc.Api/Program.cs b/src/Yavsc.Api/Program.cs index 8117fb1d4..5f7ef25c0 100644 --- a/src/Yavsc.Api/Program.cs +++ b/src/Yavsc.Api/Program.cs @@ -62,6 +62,9 @@ internal class Program services.AddAuthentication("Bearer") .AddYavscJwtBearer(builder.Configuration); + services.AddSignalR(); + services.AddSingleton(); + // DbContextBuilder services.AddDbContext(options => options.UseNpgsql(builder.Configuration.GetConnectionString( diff --git a/src/Yavsc.Org/Migrations/20260913022000_cleanupLegacyNominativeServiceCommandLocationId.cs b/src/Yavsc.Org/Migrations/20260913022000_cleanupLegacyNominativeServiceCommandLocationId.cs new file mode 100644 index 000000000..dc68aa9f1 --- /dev/null +++ b/src/Yavsc.Org/Migrations/20260913022000_cleanupLegacyNominativeServiceCommandLocationId.cs @@ -0,0 +1,63 @@ +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Yavsc.Models; + +#nullable disable + +namespace Yavsc.Migrations +{ + [DbContext(typeof(ApplicationDbContext))] + [Migration("20260913022000_cleanupLegacyNominativeServiceCommandLocationId")] + public partial class cleanupLegacyNominativeServiceCommandLocationId : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.Sql(@" +UPDATE ""NominativeServiceCommand"" +SET ""RdvQuery_LocationId"" = COALESCE(""RdvQuery_LocationId"", ""LocationId"") +WHERE ""Discriminator"" = 'RdvQuery' + AND ""LocationId"" IS NOT NULL; +"); + + migrationBuilder.DropForeignKey( + name: "FK_NominativeServiceCommand_Locations_LocationId", + table: "NominativeServiceCommand"); + + migrationBuilder.DropIndex( + name: "IX_NominativeServiceCommand_LocationId", + table: "NominativeServiceCommand"); + + migrationBuilder.DropColumn( + name: "LocationId", + table: "NominativeServiceCommand"); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "LocationId", + table: "NominativeServiceCommand", + type: "bigint", + nullable: true); + + migrationBuilder.Sql(@" +UPDATE ""NominativeServiceCommand"" +SET ""LocationId"" = ""RdvQuery_LocationId"" +WHERE ""Discriminator"" = 'RdvQuery' + AND ""RdvQuery_LocationId"" IS NOT NULL; +"); + + migrationBuilder.CreateIndex( + name: "IX_NominativeServiceCommand_LocationId", + table: "NominativeServiceCommand", + column: "LocationId"); + + migrationBuilder.AddForeignKey( + name: "FK_NominativeServiceCommand_Locations_LocationId", + table: "NominativeServiceCommand", + column: "LocationId", + principalTable: "Locations", + principalColumn: "Id"); + } + } +} \ No newline at end of file diff --git a/src/Yavsc.Server/Interfaces/IConnexionManager.cs b/src/Yavsc.Server/Interfaces/IConnexionManager.cs index 46374d40a..434054249 100644 --- a/src/Yavsc.Server/Interfaces/IConnexionManager.cs +++ b/src/Yavsc.Server/Interfaces/IConnexionManager.cs @@ -19,7 +19,7 @@ namespace Yavsc.Services bool Kick(string cxId, string userName, string roomName, string reason); bool Op(string roomName, string userName); - bool Deop(string roomName, string userName); + bool DeOp(string roomName, string userName); bool Hop(string roomName, string userName); bool DeHop(string roomName, string userName); bool TryGetChanInfo(string room, out ChatRoomInfo channelInfo); diff --git a/src/Yavsc.Org/Services/ChatHubConnexionManager.cs b/src/Yavsc.Server/Services/HubConnectionManager.cs similarity index 81% rename from src/Yavsc.Org/Services/ChatHubConnexionManager.cs rename to src/Yavsc.Server/Services/HubConnectionManager.cs index a97826616..05ed49dda 100644 --- a/src/Yavsc.Org/Services/ChatHubConnexionManager.cs +++ b/src/Yavsc.Server/Services/HubConnectionManager.cs @@ -1,5 +1,7 @@ using System.Collections.Concurrent; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Localization; +using Microsoft.Extensions.Logging; using Yavsc.Abstract.Chat; using Yavsc.Models; using Yavsc.ViewModels.Chat; @@ -119,10 +121,10 @@ namespace Yavsc.Services public bool Part(string cxId, string roomName, string reason) { - ChatRoomInfo chanInfo; - if (Channels.TryGetValue(roomName, out chanInfo)) + ChatRoomInfo channelInfo; + if (Channels.TryGetValue(roomName, out channelInfo)) { - if (!chanInfo.Users.Contains(cxId)) + if (!channelInfo.Users.Contains(cxId)) { // TODO NotifyErrorToCaller(roomName, "you didn't join."); return false; @@ -130,11 +132,11 @@ namespace Yavsc.Services // FIXME only remove cx, not username, // as long as he might be connected // from another device, to the same room - chanInfo.Users.Remove(cxId); - if (chanInfo.Users.Count == 0) + channelInfo.Users.Remove(cxId); + if (channelInfo.Users.Count == 0) { - ChatRoomInfo deadchanInfo; - if (Channels.TryRemove(roomName, out deadchanInfo)) + ChatRoomInfo deadChannelInfo; + if (Channels.TryRemove(roomName, out deadChannelInfo)) { var room = _dbContext.ChatRoom.FirstOrDefault(r => r.Name == roomName); room.LatestJoinPart = DateTime.UtcNow; @@ -155,67 +157,67 @@ namespace Yavsc.Services var userName = ChatUserNames[cxId]; _logger.LogInformation($"Join: {userName}=>{roomName}"); - ChatRoomInfo chanInfo; + ChatRoomInfo channelInfo; // if channel already is open if (Channels.ContainsKey(roomName)) { - if (Channels.TryGetValue(roomName, out chanInfo)) + if (Channels.TryGetValue(roomName, out channelInfo)) { if (IsPresent(roomName, userName)) { // TODO implement some unique connection sharing protocol // between all terminals from a single user. - return chanInfo; + return channelInfo; } else { if (IsCop(userName)) { - chanInfo.Ops.Add(cxId); + channelInfo.Ops.Add(cxId); } else{ - chanInfo.Users.Add(cxId); + channelInfo.Users.Add(cxId); } _logger.LogInformation($"existing room joint: {userName}=>{roomName}"); if (!ChatRoomPresence[userName].Contains(roomName)) ChatRoomPresence[userName].Add(roomName); - return chanInfo; + return channelInfo; } } else { - string msg = "room seemd to be avaible ... but we could get no info on it."; + string msg = "room seemed to be available ... but we could get no info on it."; _errorHandler(roomName, msg); return null; } } // room was closed. var room = _dbContext.ChatRoom.FirstOrDefault(r => r.Name == roomName); - chanInfo = new ChatRoomInfo(); + channelInfo = new ChatRoomInfo(); if (room != null) { - chanInfo.Topic = room.Topic; - chanInfo.Name = room.Name; - chanInfo.Users.Add(cxId); + channelInfo.Topic = room.Topic; + channelInfo.Name = room.Name; + channelInfo.Users.Add(cxId); } else { // a first join, we create it. - chanInfo.Name = roomName; - chanInfo.Topic = _localizer.GetString(ChatHubConstants.JustCreatedBy)+userName; - chanInfo.Ops.Add(cxId); + channelInfo.Name = roomName; + channelInfo.Topic = _localizer.GetString(ChatHubConstants.JustCreatedBy)+userName; + channelInfo.Ops.Add(cxId); } - if (Channels.TryAdd(roomName, chanInfo)) + if (Channels.TryAdd(roomName, channelInfo)) { ChatRoomPresence[userName].Add(roomName); _logger.LogInformation("new room joint"); - return (chanInfo); + return (channelInfo); } else { - string msg = "Chan create failed unexpectly..."; + string msg = "Chan create failed unexpectedly..."; _errorHandler(roomName, msg); return null; } @@ -226,7 +228,7 @@ namespace Yavsc.Services throw new System.NotImplementedException(); } - public bool Deop(string roomName, string userName) + public bool DeOp(string roomName, string userName) { throw new System.NotImplementedException(); } @@ -246,9 +248,9 @@ namespace Yavsc.Services return ChatUserNames[cxId]; } - public bool TryGetChanInfo(string room, out ChatRoomInfo chanInfo) + public bool TryGetChanInfo(string room, out ChatRoomInfo channelInfo) { - return Channels.TryGetValue(room, out chanInfo); + return Channels.TryGetValue(room, out channelInfo); } public IEnumerable ListChannels(string pattern) @@ -277,22 +279,22 @@ namespace Yavsc.Services public bool Kick(string cxId, string userName, string roomName, string reason) { - ChatRoomInfo chanInfo; + ChatRoomInfo channelInfo; if (!Channels.ContainsKey(roomName)) { _errorHandler(roomName, _localizer.GetString(ChatHubConstants.LabNoSuchChan).ToString()); return false; } - if (!Channels.TryGetValue(roomName, out chanInfo)) + if (!Channels.TryGetValue(roomName, out channelInfo)) { _errorHandler(roomName, _localizer.GetString(ChatHubConstants.LabNoSuchChan).ToString()); return false; } var kickerName = GetUserName(cxId); - if (!chanInfo.Ops.Contains(cxId)) - if (!chanInfo.Hops.Contains(cxId)) + if (!channelInfo.Ops.Contains(cxId)) + if (!channelInfo.Hops.Contains(cxId)) { _errorHandler(roomName, _localizer.GetString(ChatHubConstants.LabYouNotOp).ToString()); return false; @@ -303,9 +305,9 @@ namespace Yavsc.Services _errorHandler(roomName, _localizer.GetString(ChatHubConstants.LabNoSuchUser).ToString()); return false; } - var ucxs = GetConnexionIds(userName); - if (chanInfo.Hops.Contains(cxId)) - if (chanInfo.Ops.Any(c => ucxs.Contains(c))) + var userConnectionIds = GetConnexionIds(userName); + if (channelInfo.Hops.Contains(cxId)) + if (channelInfo.Ops.Any(c => userConnectionIds.Contains(c))) { _errorHandler(roomName, _localizer.GetString(ChatHubConstants.HopWontKickOp).ToString()); return false; @@ -317,15 +319,15 @@ namespace Yavsc.Services } // all good, time to kick :-) - foreach (var ucx in ucxs) { - if (chanInfo.Users.Contains(ucx)) - chanInfo.Users.Remove(ucx); + foreach (var ucx in userConnectionIds) { + if (channelInfo.Users.Contains(ucx)) + channelInfo.Users.Remove(ucx); - else if (chanInfo.Ops.Contains(ucx)) - chanInfo.Ops.Remove(ucx); + else if (channelInfo.Ops.Contains(ucx)) + channelInfo.Ops.Remove(ucx); - else if (chanInfo.Hops.Contains(ucx)) - chanInfo.Hops.Remove(ucx); + else if (channelInfo.Hops.Contains(ucx)) + channelInfo.Hops.Remove(ucx); } return true; From 9832d2817377d473ae1e1f7d696db3a4be2ad950 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sun, 13 Sep 2026 03:22:22 +0100 Subject: [PATCH 57/67] use Sqlite --- .forgejo/workflows/buildAndTest.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.forgejo/workflows/buildAndTest.yml b/.forgejo/workflows/buildAndTest.yml index 4e7bea2e4..c6511dcfb 100644 --- a/.forgejo/workflows/buildAndTest.yml +++ b/.forgejo/workflows/buildAndTest.yml @@ -48,7 +48,6 @@ jobs: - name: Test run: | echo "🚀 Lancement des tests..." - export YAVSC_API_TEST_DB_PROVIDER=npgsql cd /src/_src && dotnet test \ --verbosity normal \ --filter="Category!=Platform-Android" \ From 7c565d3af95a181725dda15d4cdc809429f651aa Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sun, 13 Sep 2026 03:25:09 +0100 Subject: [PATCH 58/67] take the scanning in account --- .forgejo/workflows/buildAndTest.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.forgejo/workflows/buildAndTest.yml b/.forgejo/workflows/buildAndTest.yml index c6511dcfb..64e522bab 100644 --- a/.forgejo/workflows/buildAndTest.yml +++ b/.forgejo/workflows/buildAndTest.yml @@ -31,6 +31,7 @@ jobs: steps: - name: Clone yavsc run: | + set -e cd /src git clone https://forgejo.pschneider.fr/notazof/yavsc.git _src cd _src @@ -44,7 +45,6 @@ jobs: run: | echo "🔍 Scanning for secrets..." cd /src/_src && dotnet tool restore && dotnet picket git --verbose --redact --exit-code 1 --log-opts -n1 \ - && echo "✅ Success !" || echo "❌ Fail ($?)!" - name: Test run: | echo "🚀 Lancement des tests..." From f7e1f4a7363b1548bcef13bf77537002a10fb0e7 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sun, 13 Sep 2026 03:49:07 +0100 Subject: [PATCH 59/67] list only my billing codes --- src/Yavsc.Api.Test/BillingControllerTests.cs | 69 +++++++ .../Fixtures/ApiWebServerFixture.cs | 169 +++++++++++------- .../Controllers/Business/BillingController.cs | 77 +++++--- 3 files changed, 225 insertions(+), 90 deletions(-) diff --git a/src/Yavsc.Api.Test/BillingControllerTests.cs b/src/Yavsc.Api.Test/BillingControllerTests.cs index d06ae7dba..43c2df729 100644 --- a/src/Yavsc.Api.Test/BillingControllerTests.cs +++ b/src/Yavsc.Api.Test/BillingControllerTests.cs @@ -7,6 +7,7 @@ using Yavsc.Api.Test.Fixtures; using Yavsc.Helpers; using Yavsc.Models; using Yavsc.Models.Billing; +using Yavsc.Models.Haircut; using Yavsc.Models.Workflow; using Yavsc.Tests.Shared; @@ -154,6 +155,74 @@ VALUES Assert.DoesNotContain(payload!, item => string.IsNullOrWhiteSpace(item.BillingCode)); } + [Fact] + public async Task GetProviderOngoingCommands_returns_haircut_and_grouped_haircut_requests() + { + WorkflowHelpers.ConfigureBillingService(); + _fixture.ResetAndSeedHaircutGraph(); + + using (var scope = _fixture.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.UserActivities.Add(new UserActivity + { + UserId = "alice", + DoesCode = "brush", + Weight = 50, + }); + db.UserActivities.Add(new UserActivity + { + UserId = "alice", + DoesCode = "mbrush", + Weight = 50, + }); + db.CommandForm.Add(new CommandForm + { + ActivityCode = "brush", + ActionName = BillingCodes.Brush, + Title = "Brush", + }); + db.CommandForm.Add(new CommandForm + { + ActivityCode = "mbrush", + ActionName = BillingCodes.MBrush, + Title = "MBrush", + }); + db.SaveChanges(); + } + + using var http = NewClient(); + + var response = await http.GetAsync("/api/v1/bill/provider/ongoing", 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}"); + + var payload = await response.Content.ReadFromJsonAsync>(TestContext.Current.CancellationToken); + Assert.NotNull(payload); + Assert.Contains(payload!, item => item.BillingCode == BillingCodes.Brush && item.PerformerId == "alice"); + Assert.Contains(payload!, item => item.BillingCode == BillingCodes.MBrush && item.PerformerId == "alice"); + } + + [Fact] + public async Task GetProviderOngoingCommands_excludes_requests_outside_performer_declared_activities() + { + WorkflowHelpers.ConfigureBillingService(); + _fixture.ResetAndSeedHaircutGraph(); + + using var http = NewClient(); + + var response = await http.GetAsync("/api/v1/bill/provider/ongoing", 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}"); + + var payload = await response.Content.ReadFromJsonAsync>(TestContext.Current.CancellationToken); + Assert.NotNull(payload); + Assert.DoesNotContain(payload!, item => item.BillingCode == BillingCodes.Brush); + Assert.DoesNotContain(payload!, item => item.BillingCode == BillingCodes.MBrush); + } + private sealed class ProviderOngoingCommandDto { public long Id { get; set; } diff --git a/src/Yavsc.Api.Test/Fixtures/ApiWebServerFixture.cs b/src/Yavsc.Api.Test/Fixtures/ApiWebServerFixture.cs index 3079e48c5..29d282a32 100644 --- a/src/Yavsc.Api.Test/Fixtures/ApiWebServerFixture.cs +++ b/src/Yavsc.Api.Test/Fixtures/ApiWebServerFixture.cs @@ -1,10 +1,10 @@ using Microsoft.AspNetCore.Builder; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Tokens; using Npgsql; -using System.Runtime.Loader; using Yavsc.Controllers; using Yavsc.Interfaces.Workflow; using Yavsc.Models; @@ -22,6 +22,7 @@ public sealed class ApiWebServerFixture : WebHostFixture { private const string DbProviderEnvVar = "YAVSC_API_TEST_DB_PROVIDER"; private const string NpgsqlAdminConnectionEnvVar = "YAVSC_API_TEST_NPGSQL_ADMIN_CONNECTION"; + private const string DedicatedNpgsqlDatabaseName = "yavscTestDb"; private const string DefaultDevelopmentConnectionString = "Server=localhost;Port=5432;Database=yavscdev;Username=yavscdev;Password=8*5idas;Include Error Detail=true"; protected override int HttpsPort => 5104; @@ -30,9 +31,6 @@ public sealed class ApiWebServerFixture : WebHostFixture private static readonly object _sqliteLock = new(); private static readonly object _npgsqlLock = new(); private static string? _sharedNpgsqlConnectionString; - private static string? _sharedNpgsqlAdminConnectionString; - private static string? _sharedNpgsqlDatabaseName; - private static bool _npgsqlCleanupRegistered; protected override WebApplication BuildApp(WebApplicationBuilder builder) { @@ -126,14 +124,21 @@ public sealed class ApiWebServerFixture : WebHostFixture } var adminConnectionString = BuildAdminConnectionString(); - var databaseName = $"yavsc_api_test_{Guid.NewGuid():N}"; + var databaseName = DedicatedNpgsqlDatabaseName; using (var adminConnection = new NpgsqlConnection(adminConnectionString)) { adminConnection.Open(); - using var createCommand = adminConnection.CreateCommand(); - createCommand.CommandText = $"CREATE DATABASE \"{databaseName}\""; - createCommand.ExecuteNonQuery(); + using var existsCommand = adminConnection.CreateCommand(); + existsCommand.CommandText = "SELECT 1 FROM pg_database WHERE datname = @databaseName"; + existsCommand.Parameters.AddWithValue("databaseName", databaseName); + + if (existsCommand.ExecuteScalar() is null) + { + using var createCommand = adminConnection.CreateCommand(); + createCommand.CommandText = $"CREATE DATABASE \"{databaseName}\""; + createCommand.ExecuteNonQuery(); + } } var testConnectionBuilder = new NpgsqlConnectionStringBuilder(adminConnectionString) @@ -143,10 +148,7 @@ public sealed class ApiWebServerFixture : WebHostFixture IncludeErrorDetail = true }; - _sharedNpgsqlAdminConnectionString = adminConnectionString; - _sharedNpgsqlDatabaseName = databaseName; _sharedNpgsqlConnectionString = testConnectionBuilder.ToString(); - RegisterNpgsqlCleanup(); return _sharedNpgsqlConnectionString; } } @@ -176,61 +178,6 @@ public sealed class ApiWebServerFixture : WebHostFixture return builder.ToString(); } - private static void RegisterNpgsqlCleanup() - { - if (_npgsqlCleanupRegistered) - { - return; - } - - AppDomain.CurrentDomain.ProcessExit += (_, __) => DropTemporaryNpgsqlDatabase(); - AssemblyLoadContext.Default.Unloading += _ => DropTemporaryNpgsqlDatabase(); - _npgsqlCleanupRegistered = true; - } - - private static void DropTemporaryNpgsqlDatabase() - { - lock (_npgsqlLock) - { - if (string.IsNullOrWhiteSpace(_sharedNpgsqlDatabaseName) - || string.IsNullOrWhiteSpace(_sharedNpgsqlAdminConnectionString)) - { - return; - } - - try - { - using var adminConnection = new NpgsqlConnection(_sharedNpgsqlAdminConnectionString); - adminConnection.Open(); - - using (var terminateCommand = adminConnection.CreateCommand()) - { - terminateCommand.CommandText = @" -SELECT pg_terminate_backend(pid) -FROM pg_stat_activity -WHERE datname = @databaseName - AND pid <> pg_backend_pid();"; - terminateCommand.Parameters.AddWithValue("databaseName", _sharedNpgsqlDatabaseName); - terminateCommand.ExecuteNonQuery(); - } - - using var dropCommand = adminConnection.CreateCommand(); - dropCommand.CommandText = $"DROP DATABASE IF EXISTS \"{_sharedNpgsqlDatabaseName}\""; - dropCommand.ExecuteNonQuery(); - } - catch - { - // Best-effort cleanup only. - } - finally - { - _sharedNpgsqlConnectionString = null; - _sharedNpgsqlAdminConnectionString = null; - _sharedNpgsqlDatabaseName = null; - } - } - } - private sealed class NoopMessageSender : IYavscMessageSender { public Task NotifyBookQueryAsync(IEnumerable connectionIds, RdvQueryEvent ev) @@ -251,7 +198,7 @@ WHERE datname = @databaseName using var scope = Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); - db.Database.EnsureDeleted(); + ResetDatabase(db); db.Database.EnsureCreated(); var user = new ApplicationUser @@ -352,6 +299,94 @@ WHERE datname = @databaseName db.SaveChanges(); } + private static void ResetDatabase(ApplicationDbContext db) + { + if (UseNpgsqlProvider()) + { + db.Set().RemoveRange(db.Set()); + db.Set().RemoveRange(db.Set()); + db.Set().RemoveRange(db.Set()); + db.Set().RemoveRange(db.Set()); + db.Set().RemoveRange(db.Set()); + db.Set().RemoveRange(db.Set()); + db.Set().RemoveRange(db.Set()); + db.Set().RemoveRange(db.Set()); + db.Set().RemoveRange(db.Set()); + db.Set().RemoveRange(db.Set()); + + db.SaveChanges(); + return; + } + + db.Database.EnsureDeleted(); + } + + + + private static IReadOnlyList GetDeletionOrder(IModel model) + { + var entityTypes = model + .GetEntityTypes() + .Where(et => + et.ClrType is not null && + !et.IsOwned() && + et.FindPrimaryKey() is not null) + .ToArray(); + + var included = new HashSet(entityTypes); + var dependencies = new Dictionary>(); + + foreach (var entityType in entityTypes) + { + var principals = entityType + .GetForeignKeys() + .Where(fk => !fk.IsOwnership) + .Select(fk => fk.PrincipalEntityType) + .Where(included.Contains) + .ToHashSet(); + + dependencies[entityType] = principals; + } + + var queue = new Queue( + dependencies.Where(kvp => kvp.Value.Count == 0).Select(kvp => kvp.Key)); + + var order = new List(entityTypes.Length); + + while (queue.Count > 0) + { + var current = queue.Dequeue(); + if (!order.Contains(current)) + { + order.Add(current); + } + + foreach (var kvp in dependencies) + { + if (!kvp.Value.Remove(current) || kvp.Value.Count != 0) + { + continue; + } + + if (!order.Contains(kvp.Key) && !queue.Contains(kvp.Key)) + { + queue.Enqueue(kvp.Key); + } + } + } + + // If cycles remain (rare), append unresolved types last and rely on DB cascades. + foreach (var entityType in entityTypes) + { + if (!order.Contains(entityType)) + { + order.Add(entityType); + } + } + + return order; + } + public void ResetAndSeedRdvQueryGraph() { ResetAndSeedActivityGraph(); diff --git a/src/Yavsc.Api/Controllers/Business/BillingController.cs b/src/Yavsc.Api/Controllers/Business/BillingController.cs index 219431b7e..d10e166e3 100644 --- a/src/Yavsc.Api/Controllers/Business/BillingController.cs +++ b/src/Yavsc.Api/Controllers/Business/BillingController.cs @@ -123,34 +123,65 @@ namespace Yavsc.ApiControllers WorkflowHelpers.ConfigureBillingService(); } - // Query known derived types explicitly so legacy rows with - // invalid/empty discriminator values are naturally ignored. - var rdvCommands = dbContext.Set() + var allowedActivityCodes = dbContext.UserActivities .AsNoTracking() - .Where(q => q.PerformerId == uid) - .Where(q => q.Status == QueryStatus.Inserted - || q.Status == QueryStatus.Accepted - || q.Status == QueryStatus.InProgress) - .Cast() + .Where(a => a.UserId == uid) + .Select(a => a.DoesCode) + .Distinct() .ToList(); - var hairCommands = dbContext.Set() - .AsNoTracking() - .Where(q => q.PerformerId == uid) - .Where(q => q.Status == QueryStatus.Inserted - || q.Status == QueryStatus.Accepted - || q.Status == QueryStatus.InProgress) - .Cast() - .ToList(); + if (allowedActivityCodes.Count == 0) + { + return Ok(Array.Empty()); + } - var hairMultiCommands = dbContext.Set() + var allowedBillingCodes = dbContext.CommandForm .AsNoTracking() - .Where(q => q.PerformerId == uid) - .Where(q => q.Status == QueryStatus.Inserted - || q.Status == QueryStatus.Accepted - || q.Status == QueryStatus.InProgress) - .Cast() - .ToList(); + .Where(form => allowedActivityCodes.Contains(form.ActivityCode)) + .Select(form => form.ActionName) + .Where(actionName => !string.IsNullOrWhiteSpace(actionName)) + .Distinct() + .ToHashSet(StringComparer.OrdinalIgnoreCase); + + var fallbackToActivityFilteringOnly = allowedBillingCodes.Count == 0; + + // Query only the command types allowed by the performer's declared + // activities; this avoids touching unrelated legacy slices. + var rdvCommands = fallbackToActivityFilteringOnly || allowedBillingCodes.Contains(BillingCodes.Rdv) + ? dbContext.Set() + .AsNoTracking() + .Where(q => q.PerformerId == uid) + .Where(q => allowedActivityCodes.Contains(q.ActivityCode)) + .Where(q => q.Status == QueryStatus.Inserted + || q.Status == QueryStatus.Accepted + || q.Status == QueryStatus.InProgress) + .Cast() + .ToList() + : new List(); + + var hairCommands = fallbackToActivityFilteringOnly || allowedBillingCodes.Contains(BillingCodes.Brush) + ? dbContext.Set() + .AsNoTracking() + .Where(q => q.PerformerId == uid) + .Where(q => allowedActivityCodes.Contains(q.ActivityCode)) + .Where(q => q.Status == QueryStatus.Inserted + || q.Status == QueryStatus.Accepted + || q.Status == QueryStatus.InProgress) + .Cast() + .ToList() + : new List(); + + var hairMultiCommands = fallbackToActivityFilteringOnly || allowedBillingCodes.Contains(BillingCodes.MBrush) + ? dbContext.Set() + .AsNoTracking() + .Where(q => q.PerformerId == uid) + .Where(q => allowedActivityCodes.Contains(q.ActivityCode)) + .Where(q => q.Status == QueryStatus.Inserted + || q.Status == QueryStatus.Accepted + || q.Status == QueryStatus.InProgress) + .Cast() + .ToList() + : new List(); var commands = rdvCommands .Concat(hairCommands) From 1af839e14e98be80fcecd81226ce83fcd9604343 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sun, 13 Sep 2026 13:34:39 +0100 Subject: [PATCH 60/67] POSTIT_SETTINGS_JSON env var --- .../PostIt/ViewModels/Settings/Settings.cs | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs index 23e9955f4..fee7206ef 100644 --- a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs +++ b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs @@ -15,7 +15,7 @@ namespace PostIt.ViewModels; public partial class Settings : ViewModelBase { - const string SettingsFileName = "postit-settings.json"; + public string SettingsFileName {get; private set;} = "postit-settings.json"; [ObservableProperty] public partial AuthenticationSettings Authentication { get; set; } = new(); @@ -251,12 +251,18 @@ public partial class Settings : ViewModelBase return; } } - + if (Environment.GetEnvironmentVariable("POSTIT_SETTINGS_JSON") is string envJson + && !string.IsNullOrWhiteSpace(envJson)) + { + Console.WriteLine("🔎 Loading settings from POSTIT_SETTINGS_JSON environment variable."); + ApplyJson(envJson, "POSTIT_SETTINGS_JSON"); + Loaded = true; + return; + } string configDir = Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), - "PostIt" -); - Directory.CreateDirectory(configDir); + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), + "PostIt" + ); string configPath = Path.Combine(configDir, SettingsFileName); From f70f487777495bfacf547ac782d8eb6c7875324c Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sun, 13 Sep 2026 17:51:42 +0100 Subject: [PATCH 61/67] better and simpler UI --- .../PostIt/ViewModels/Blogs/BlogsViewModel.cs | 6 - .../PostIt/ViewModels/Settings/Settings.cs | 4 +- .../ProviderOngoingRequestsPage.axaml | 3 +- src/PostIt/PostIt/Views/Blogs/BlogsPage.axaml | 143 +++++++++--------- 4 files changed, 78 insertions(+), 78 deletions(-) diff --git a/src/PostIt/PostIt/ViewModels/Blogs/BlogsViewModel.cs b/src/PostIt/PostIt/ViewModels/Blogs/BlogsViewModel.cs index 8ac05c85e..78be2e789 100644 --- a/src/PostIt/PostIt/ViewModels/Blogs/BlogsViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/Blogs/BlogsViewModel.cs @@ -96,12 +96,6 @@ public partial class BlogsViewModel : ViewModelBase, IActionStatusViewModel }); } - [RelayCommand] - internal async Task SearchAsync() { - await RefreshAsync(); - ApplyFilter(); - } - [RelayCommand] internal async Task SaveAsync() { diff --git a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs index fee7206ef..6b6ed5d4f 100644 --- a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs +++ b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs @@ -346,7 +346,7 @@ public partial class Settings : ViewModelBase // → our overridden dispatcher-safe marshaller below. else lock (_mutationGate) { - var legacyApiUrl = TryReadLegacyApiUrl(json); + var legacyApiUrl = TryReadApiUrl(json); this.Authentication = settings.Authentication; this.DarkMode = settings.DarkMode; this.BlogsApiUrl = !string.IsNullOrWhiteSpace(settings.BlogsApiUrl) @@ -402,7 +402,7 @@ public partial class Settings : ViewModelBase } } - private static string? TryReadLegacyApiUrl(string json) + private static string? TryReadApiUrl(string json) { try { diff --git a/src/PostIt/PostIt/Views/Activity/ProviderOngoingRequestsPage.axaml b/src/PostIt/PostIt/Views/Activity/ProviderOngoingRequestsPage.axaml index 010bab7b5..e6db2988b 100644 --- a/src/PostIt/PostIt/Views/Activity/ProviderOngoingRequestsPage.axaml +++ b/src/PostIt/PostIt/Views/Activity/ProviderOngoingRequestsPage.axaml @@ -85,7 +85,8 @@