diff --git a/CHANGELOG.md b/CHANGELOG.md index 7df6ba171..521516595 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ ### Added +* [PostIt/PayPal] Add a native subscription page reachable from Home, profile and About: load server-priced Discovery/Premium offers, prepare or resume checkout with the current bearer session, open only PayPal for approval, reconcile confirmed payments and balances, and cancel with confirmation. Add quota-exempt bearer-only endpoints on Yavsc.Org, sharing checkout/cancellation logic with the existing web flow, and regression coverage. Browser return never confirms payment. + * [Resource usage] Let users with the `Administrator` role continue making requests after reaching their consumption quota, while still recording their usage. * [PostIt.Android/Podcasts] Add an optional persisted background blur for camera preview and broadcasting. Run the bundled PPHumanSeg model locally with ONNX Runtime and composite with OpenGL before encoding; preserve the unfiltered pipeline for calls and OBS. diff --git a/INSTALL.md b/INSTALL.md index 696f3924f..d1f84945d 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -227,6 +227,22 @@ any still-paid Discovery period applies. Configure only **Yavsc.Org** for PayPal subscriptions. API and Blogs need the migrated shared database and matching resource weights, not PayPal credentials. Existing Classic donation settings remain unchanged. + +PostIt's **Mon abonnement PayPal** page (Home, profile or About) loads offers +and creates/resumes checkout through `api/v1/resource-subscriptions` on the +configured OIDC **authority**, not the business API host. These routes require +the current bearer token, reject cookie-only requests, and remain accessible +at the resource-consumption limit. Prices, VAT, monthly points and plan IDs +are controlled by the server; no PayPal credentials are shipped to PostIt. +Only approval opens in the browser. The anonymous `/api/v1/resource-subscriptions/return` +landing page asks the user to return to PostIt and press **Actualiser**: +it does not reconcile or grant credit, and requires no second web login. +The authenticated `POST refresh` reconciles verified PayPal transactions; +`POST {id}/cancel` cancels only the caller's subscription. Existing web +checkout and verified webhooks remain supported. Deploy Yavsc.Org with the +new routes before distributing the updated client. Example requests are in +[`resource-subscriptions.http`](src/Yavsc.Org/resource-subscriptions.http). + Use the existing `PayPal:Mode`, `PayPal:ClientId` and `PayPal:ClientSecret` REST settings; keep credentials in user-secrets or environment variables. diff --git a/doc/architecture/postit.md b/doc/architecture/postit.md index baa2331e8..b32832559 100644 --- a/doc/architecture/postit.md +++ b/doc/architecture/postit.md @@ -47,6 +47,21 @@ spécifiques (IntentFilter Android, `app.manifest` Desktop). Toute la logique (VM, services, navigation, settings, OIDC) est dans le code-base partagé. +## Abonnements PayPal + +La page native **Mon abonnement PayPal** est accessible depuis l'accueil, +le profil et « À propos ». Elle utilise `ResourceSubscriptionsApiClient` +avec l'autorité OIDC configurée pour charger les offres, l'abonnement en +cours et le solde. Les prix HT/TTC, la TVA et les droits proviennent du serveur. +La création ou reprise de souscription utilise la session bearer de PostIt ; +seule l'approbation est ouverte dans le navigateur, sur un domaine PayPal HTTPS. +Après approbation ou abandon, l'utilisateur revient dans PostIt et utilise +**Actualiser les paiements et mon solde**. Ni l'ouverture du navigateur ni +la page de retour ne prouvent un paiement : seul le rapprochement serveur +des transactions vérifiées accorde les droits. La résiliation demande une +confirmation explicite et conserve les droits des périodes déjà payées. +La configuration serveur et les routes sont décrites dans [INSTALL.md](../../INSTALL.md). + ## Reprise Android `IActivityApplicationLifetime.MainViewFactory` crée une nouvelle `MainView` diff --git a/src/PostIt/PostIt.Tests/SubscriptionsPageTests.cs b/src/PostIt/PostIt.Tests/SubscriptionsPageTests.cs new file mode 100644 index 000000000..318d99971 --- /dev/null +++ b/src/PostIt/PostIt.Tests/SubscriptionsPageTests.cs @@ -0,0 +1,174 @@ +using System.Net.Http; +using System.Text.Json; +using System.Globalization; +using Avalonia.Controls; +using Avalonia.Headless.XUnit; +using PostIt.ViewModels; +using PostIt.Views; +using Yavsc.Abstract.Resources; +using Yavsc.Api.Client; + +namespace PostIt.Tests; + +public sealed class SubscriptionsPageTests +{ + [AvaloniaFact] + public async Task Page_binds_server_offers_prices_and_balance() + { + await using var api = new FakeApi(); + var model = Model(api); + await model.InitializeAsync(); + var page = new SubscriptionsPage { DataContext = model }; + Assert.IsType(new ViewLocator().Build(model)); + var selector = page.FindControl("OfferSelector")!; + Assert.Equal(2, selector.ItemCount); + Assert.Equal(1.2m, model.SelectedOffer?.PriceIncludingTax); + Assert.Equal($"Prix TTC : {1.2m.ToString("F2", CultureInfo.CurrentCulture)} EUR / mois", + page.FindControl("OfferPrice")!.Text); + selector.SelectedIndex = 1; + Assert.Equal("Premium", model.SelectedOffer?.Pack); + Assert.Equal($"Prix TTC : {2.4m.ToString("F2", CultureInfo.CurrentCulture)} EUR / mois", + page.FindControl("OfferPrice")!.Text); + Assert.Equal(45m, model.Usage?.Consumption); + Assert.Null(model.StatusMessage); + Assert.True(model.SubscribeCommand.CanExecute(null)); + Assert.False(model.CancelSubscriptionCommand.CanExecute(null)); + } + + [Fact] + public async Task Checkout_uses_authority_and_selected_pack_without_granting_local_credit() + { + await using var api = new FakeApi(); + Uri? opened = null; + var authority = "https://first.example/"; + var client = new ResourceSubscriptionsApiClient(api, () => authority); + var model = new SubscriptionsPageViewModel(client, uri => { opened = uri; return Task.FromResult(true); }); + await model.InitializeAsync(); + authority = "https://second.example/instance"; + model.SelectedOffer = model.Offers[1]; + await model.SubscribeCommand.ExecuteAsync(null); + Assert.Equal("https://second.example/instance/api/v1/resource-subscriptions", api.LastPath); + Assert.Equal("Premium", Assert.IsType(api.LastBody).Pack); + Assert.Equal("www.sandbox.paypal.com", opened?.Host); + Assert.Equal("APPROVAL_PENDING", model.CurrentSubscription?.State); + Assert.Equal(45m, model.Usage?.Consumption); + Assert.False(model.IsBusy); + Assert.Contains("Actualiser", model.StatusMessage); + } + + [Theory] + [InlineData("https://attacker.example/approve", true)] + [InlineData("http://www.paypal.com/approve", true)] + [InlineData("https://www.paypal.com@attacker.example/approve", true)] + [InlineData("https://www.paypal.com:444/approve", true)] + [InlineData("https://www.sandbox.paypal.com/approve", false)] + public async Task Invalid_link_or_browser_failure_is_explicit_and_checkout_can_be_resumed(string link, bool launchResult) + { + await using var api = new FakeApi { ApprovalUrl = link }; + var launches = 0; + var model = new SubscriptionsPageViewModel(new(api, () => "https://org.example"), _ => + { + launches++; + return Task.FromResult(launchResult); + }); + await model.InitializeAsync(); + await model.SubscribeCommand.ExecuteAsync(null); + Assert.Contains("impossible", model.StatusMessage); + Assert.Equal(launchResult ? 0 : 1, launches); + Assert.True(model.SubscribeCommand.CanExecute(null)); + Assert.Equal(45m, model.Usage?.Consumption); + } + + [Fact] + public async Task Active_subscription_blocks_duplicate_checkout_and_cancel_requires_confirmation() + { + await using var api = new FakeApi { State = "ACTIVE" }; + var model = Model(api); + await model.InitializeAsync(); + Assert.False(model.SubscribeCommand.CanExecute(null)); + await model.CancelSubscriptionCommand.ExecuteAsync(null); + Assert.Contains("confirmation", model.StatusMessage); + Assert.Equal(HttpMethod.Get, api.LastMethod); + model.ConfirmCancellation = true; + await model.CancelSubscriptionCommand.ExecuteAsync(null); + Assert.EndsWith($"/{api.Id}/cancel", api.LastPath); + Assert.Null(model.CurrentSubscription); + Assert.False(model.ConfirmCancellation); + Assert.True(model.SubscribeCommand.CanExecute(null)); + } + + [Fact] + public async Task Refresh_uses_server_reconciliation_and_reports_failures_without_fake_success() + { + await using var api = new FakeApi(); + var model = Model(api); + await model.InitializeAsync(); + api.Fail = true; + await model.RefreshCommand.ExecuteAsync(null); + Assert.Contains("offline", model.StatusMessage); + Assert.False(model.IsBusy); + Assert.Equal(45m, model.Usage?.Consumption); + api.Fail = false; + await model.RefreshCommand.ExecuteAsync(null); + Assert.EndsWith("/refresh", api.LastPath); + Assert.Equal(HttpMethod.Post, api.LastMethod); + Assert.Equal(0m, model.Usage?.Consumption); + } + + [Fact] + public async Task Unavailable_offers_and_changing_an_existing_pack_cannot_start_checkout() + { + await using var api = new FakeApi { State = "APPROVAL_PENDING" }; + var model = Model(api); + await model.InitializeAsync(); + Assert.False(model.SubscribeCommand.CanExecute(null)); + model.SelectedOffer = model.Offers[1]; + Assert.True(model.SubscribeCommand.CanExecute(null)); + model.SelectedOffer = model.SelectedOffer with { Available = false }; + Assert.False(model.SubscribeCommand.CanExecute(null)); + } + + private static SubscriptionsPageViewModel Model(FakeApi api) + => new(new(api, () => "https://org.example"), _ => Task.FromResult(true)); + + private sealed class FakeApi : IYavscApiClient + { + public HttpClient Http { get; } = new(); + public Guid Id { get; } = Guid.NewGuid(); + public string? State { get; set; } + public string ApprovalUrl { get; set; } = "https://www.sandbox.paypal.com/approve"; + public bool Fail { get; set; } + public HttpMethod? LastMethod { get; private set; } + public string? LastPath { get; private set; } + public object? LastBody { get; private set; } + + public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) + { + LastMethod = method; + LastPath = path; + LastBody = body; + if (Fail) throw new HttpRequestException("offline"); + var pack = (body as CreateResourceSubscriptionRequest)?.Pack ?? "Premium"; + var subscription = new ResourceSubscriptionResponse(Id, pack, State ?? "APPROVAL_PENDING", 2.4m, 3000m, null); + object result; + if (body is CreateResourceSubscriptionRequest) + result = new ResourceSubscriptionCheckoutResponse(subscription, ApprovalUrl); + else + { + if (path.EndsWith("/cancel")) State = null; + result = new ResourceSubscriptionsResponse( + [new("Discovery", "Découverte", 1m, 20m, 1.2m, 1000m, 2, true), + new("Premium", "Premium", 2m, 20m, 2.4m, 3000m, 5, true)], + State is null ? [] : [subscription], + new ResourceUsageSummary { Consumption = path.EndsWith("/refresh") ? 0m : 45m }); + } + return Task.FromResult(JsonSerializer.Deserialize(JsonSerializer.Serialize(result))!); + } + + public Task CallAsync(HttpMethod method, string path, Func factory, CancellationToken ct = default) => throw new NotSupportedException(); + public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) => throw new NotSupportedException(); + public Task CallAsync(HttpMethod method, string path, Func factory, CancellationToken ct = default) => throw new NotSupportedException(); + public Task DownloadAsync(HttpMethod method, string path, CancellationToken ct = default) => throw new NotSupportedException(); + public ValueTask DisposeAsync() { Http.Dispose(); return ValueTask.CompletedTask; } + } +} diff --git a/src/PostIt/PostIt/Helpers/ServiceCollectionHelpers.cs b/src/PostIt/PostIt/Helpers/ServiceCollectionHelpers.cs index be3589160..15b7e5638 100644 --- a/src/PostIt/PostIt/Helpers/ServiceCollectionHelpers.cs +++ b/src/PostIt/PostIt/Helpers/ServiceCollectionHelpers.cs @@ -94,6 +94,7 @@ public static class ServiceCollectionHelpers services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -110,6 +111,7 @@ public static class ServiceCollectionHelpers services.AddSingleton(invoicesClient); services.AddSingleton(frontClient); services.AddSingleton(resourceUsageClient); + services.AddSingleton(new ResourceSubscriptionsApiClient(api, () => settings.Authentication.Authority)); services.AddSingleton(administrationClient); services.AddSingleton(notificationsClient); services.AddSingleton(podcastClient); @@ -120,6 +122,7 @@ public static class ServiceCollectionHelpers services.AddSingleton(); services.AddSingleton(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddSingleton(); diff --git a/src/PostIt/PostIt/ViewLocator.cs b/src/PostIt/PostIt/ViewLocator.cs index eff0094a5..0d35c22f8 100644 --- a/src/PostIt/PostIt/ViewLocator.cs +++ b/src/PostIt/PostIt/ViewLocator.cs @@ -63,6 +63,7 @@ public class ViewLocator : IDataTemplate EstimateValidationPageViewModel => services.GetRequiredService(), MyFilesViewModel => services.GetRequiredService(), UserProfilePageViewModel => services.GetRequiredService(), + SubscriptionsPageViewModel => services.GetRequiredService(), PerformerConfigurationPageViewModel => services.GetRequiredService(), AdministrationPageViewModel => services.GetRequiredService(), ChatViewModel => services.GetRequiredService(), diff --git a/src/PostIt/PostIt/ViewModels/Layout/AboutPageViewModel.cs b/src/PostIt/PostIt/ViewModels/Layout/AboutPageViewModel.cs index cf6883e90..c059e9282 100644 --- a/src/PostIt/PostIt/ViewModels/Layout/AboutPageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/Layout/AboutPageViewModel.cs @@ -64,7 +64,7 @@ public partial class AboutPageViewModel : ViewModelBase private Task OpenTerms() => OpenUrlAsync(TermsUri.AbsoluteUri); [RelayCommand] - private Task OpenSubscriptions() => OpenUrlAsync(SubscriptionsUri.AbsoluteUri); + private Task OpenSubscriptions() => SubscriptionsPageViewModel.OpenAsync(); private async Task OpenUrlAsync(string url) { diff --git a/src/PostIt/PostIt/ViewModels/Layout/HomePageViewModel.cs b/src/PostIt/PostIt/ViewModels/Layout/HomePageViewModel.cs index ebc49a4af..5600854f0 100644 --- a/src/PostIt/PostIt/ViewModels/Layout/HomePageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/Layout/HomePageViewModel.cs @@ -74,6 +74,7 @@ public class HomePageViewModel : ViewModelBase OpenBlogs = new AsyncRelayCommand(App.PushBlogsPageAsync); OpenMyFiles = new AsyncRelayCommand(OpenMyFilesAsync); OpenProfile = new AsyncRelayCommand(OpenProfileAsync); + OpenSubscriptions = new AsyncRelayCommand(SubscriptionsPageViewModel.OpenAsync); OpenPerformerConfiguration = new AsyncRelayCommand(OpenPerformerConfigurationAsync); OpenAdministration = new AsyncRelayCommand(OpenAdministrationAsync, () => SessionStatus.IsAdministrator); OpenChat = new AsyncRelayCommand(OpenChatAsync); @@ -92,6 +93,7 @@ public class HomePageViewModel : ViewModelBase public bool SupportsPodcasts => Platform.IsPodcastSupported; public IAsyncRelayCommand OpenBlogs { get; } public IAsyncRelayCommand OpenProfile { get; } + public IAsyncRelayCommand OpenSubscriptions { get; } public IAsyncRelayCommand OpenPerformerConfiguration { get; } public IAsyncRelayCommand OpenAdministration { get; } public IAsyncRelayCommand OpenActivities { get; } diff --git a/src/PostIt/PostIt/ViewModels/Layout/SubscriptionsPageViewModel.cs b/src/PostIt/PostIt/ViewModels/Layout/SubscriptionsPageViewModel.cs new file mode 100644 index 000000000..aed71b374 --- /dev/null +++ b/src/PostIt/PostIt/ViewModels/Layout/SubscriptionsPageViewModel.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.ObjectModel; +using System.Linq; +using System.Threading.Tasks; +using Avalonia.Controls; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using Microsoft.Extensions.DependencyInjection; +using Yavsc.Abstract.Resources; +using Yavsc.Api.Client; + +namespace PostIt.ViewModels; + +public partial class SubscriptionsPageViewModel : ViewModelBase +{ + private readonly ResourceSubscriptionsApiClient _client; + private readonly Func> _launch; + + public SubscriptionsPageViewModel(ResourceSubscriptionsApiClient client, Func>? launch = null) + { + _client = client; + _launch = launch ?? LaunchAsync; + } + + public ObservableCollection Offers { get; } = []; + + [ObservableProperty] + [NotifyCanExecuteChangedFor(nameof(SubscribeCommand))] + [NotifyCanExecuteChangedFor(nameof(CancelSubscriptionCommand))] + [NotifyCanExecuteChangedFor(nameof(RefreshCommand))] + public partial bool IsBusy { get; set; } + + [ObservableProperty] + [NotifyCanExecuteChangedFor(nameof(SubscribeCommand))] + public partial ResourceSubscriptionOfferResponse? SelectedOffer { get; set; } + + [ObservableProperty] + [NotifyCanExecuteChangedFor(nameof(SubscribeCommand))] + [NotifyCanExecuteChangedFor(nameof(CancelSubscriptionCommand))] + public partial ResourceSubscriptionResponse? CurrentSubscription { get; set; } + + [ObservableProperty] + public partial ResourceUsageSummary? Usage { get; set; } + + [ObservableProperty] + public partial string? StatusMessage { get; set; } + + [ObservableProperty] + public partial bool ConfirmCancellation { get; set; } + + public override bool CanNavigateNext { get => false; protected set { } } + public override bool CanNavigatePrevious { get => true; protected set { } } + + public Task InitializeAsync() => RunAsync(async () => Apply(await _client.GetAsync())); + + private bool CanRefresh() => !IsBusy; + + [RelayCommand(CanExecute = nameof(CanRefresh))] + private Task RefreshAsync() => RunAsync(async () => + { + Apply(await _client.RefreshAsync()); + StatusMessage = "État et paiements vérifiés auprès de PayPal."; + }); + + private bool CanSubscribe() => !IsBusy && SelectedOffer is { Available: true } + && (CurrentSubscription is null || (CurrentSubscription.Pack == SelectedOffer.Pack + && CurrentSubscription.State is "CREATING" or "APPROVAL_PENDING")); + + [RelayCommand(CanExecute = nameof(CanSubscribe))] + private Task SubscribeAsync() => RunAsync(async () => + { + var checkout = await _client.CreateAsync(SelectedOffer!.Pack); + CurrentSubscription = checkout.Subscription; + if (checkout.ApprovalUrl is null) + { + Apply(await _client.GetAsync()); + StatusMessage = "Abonnement rapproché. Seuls les paiements confirmés accordent des crédits."; + return; + } + if (!Uri.TryCreate(checkout.ApprovalUrl, UriKind.Absolute, out var uri) + || uri.Scheme != "https" || !string.IsNullOrEmpty(uri.UserInfo) || !uri.IsDefaultPort + || uri.Host is not ("www.paypal.com" or "www.sandbox.paypal.com")) + throw new InvalidOperationException("Lien d'approbation PayPal invalide."); + if (!await _launch(uri)) + throw new InvalidOperationException("Impossible d'ouvrir PayPal. Réessayez pour reprendre l'approbation."); + StatusMessage = "Approuvez l'abonnement mensuel dans PayPal, puis revenez ici et appuyez sur Actualiser. Aucun paiement n'est confirmé par l'ouverture du navigateur."; + }); + + private bool CanCancelSubscription() => !IsBusy && CurrentSubscription is { State: not "CREATING" }; + + [RelayCommand(CanExecute = nameof(CanCancelSubscription))] + private Task CancelSubscriptionAsync() => RunAsync(async () => + { + if (!ConfirmCancellation) + throw new InvalidOperationException("Cochez la confirmation de résiliation avant de continuer."); + Apply(await _client.CancelAsync(CurrentSubscription!.Id)); + ConfirmCancellation = false; + StatusMessage = "Abonnement résilié. Les droits déjà acquis restent soumis aux périodes payées."; + }); + + private void Apply(ResourceSubscriptionsResponse response) + { + var pack = SelectedOffer?.Pack; + Offers.Clear(); + foreach (var offer in response.Offers) Offers.Add(offer); + SelectedOffer = Offers.FirstOrDefault(o => o.Pack == pack) ?? Offers.FirstOrDefault(); + CurrentSubscription = response.Subscriptions.FirstOrDefault(s => s.State is not ("CANCELLED" or "EXPIRED")); + Usage = response.Usage; + } + + private async Task RunAsync(Func action) + { + IsBusy = true; + StatusMessage = null; + try { await action(); } + catch (Exception ex) { StatusMessage = $"Opération d'abonnement impossible : {ex.Message}"; } + finally { IsBusy = false; } + } + + private static async Task LaunchAsync(Uri uri) + { + var topLevel = TopLevel.GetTopLevel((App.Current as App)?.View); + return topLevel is not null && await topLevel.Launcher.LaunchUriAsync(uri); + } + + public static async Task OpenAsync() + { + var app = App.Current as App ?? throw new InvalidOperationException("Application PostIt indisponible."); + var vm = app.ServiceProvider!.GetRequiredService(); + await vm.InitializeAsync(); + await app.PushPageAsync(vm); + } +} diff --git a/src/PostIt/PostIt/ViewModels/Layout/UserProfilePageViewModel.cs b/src/PostIt/PostIt/ViewModels/Layout/UserProfilePageViewModel.cs index 9dfa45704..76f1b3735 100644 --- a/src/PostIt/PostIt/ViewModels/Layout/UserProfilePageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/Layout/UserProfilePageViewModel.cs @@ -17,9 +17,7 @@ public partial class UserProfilePageViewModel : ViewModelBase private readonly YavscApiClient? _api; private readonly SessionStatusViewModel? _sessionStatus; private readonly ResourceUsageApiClient? _usageClient; - private readonly AboutPageViewModel _subscriptionLinks; - public IAsyncRelayCommand OpenSubscriptionsCommand => _subscriptionLinks.OpenSubscriptionsCommand; - public string? SubscriptionLinkError => _subscriptionLinks.StatusMessage; + public IAsyncRelayCommand OpenSubscriptionsCommand { get; } = new AsyncRelayCommand(SubscriptionsPageViewModel.OpenAsync); [ObservableProperty] public partial ResourceUsageSummary? ResourceUsage { get; set; } @@ -161,8 +159,6 @@ public partial class UserProfilePageViewModel : ViewModelBase _api = api; _sessionStatus = sessionStatus; _usageClient = usageClient; - _subscriptionLinks = new AboutPageViewModel(api?.Settings); - _subscriptionLinks.PropertyChanged += (_, _) => OnPropertyChanged(nameof(SubscriptionLinkError)); } public UserProfilePageViewModel() : this(null, null) { } diff --git a/src/PostIt/PostIt/Views/Layout/HomePage.axaml b/src/PostIt/PostIt/Views/Layout/HomePage.axaml index 88326b049..5407e7290 100644 --- a/src/PostIt/PostIt/Views/Layout/HomePage.axaml +++ b/src/PostIt/PostIt/Views/Layout/HomePage.axaml @@ -94,6 +94,10 @@ Command="{Binding OpenPerformerConfiguration}" HorizontalAlignment="Center" IsEnabled="{Binding SessionStatus.IsLoggedIn}"/> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +