feat(postit): add native PayPal subscription page

Add bearer-authenticated subscription checkout, reconciliation and cancellation on the authority host, reuse web subscription services, and document the flow with regression tests.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Paul Schneider 2026-11-10 23:57:26 +00:00
commit 7cda466fa8
Signed by: notazof
GPG key ID: AD4B9B545FBD7D12
21 changed files with 774 additions and 28 deletions

View file

@ -5,6 +5,8 @@
### Added ### 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. * [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. * [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.

View file

@ -227,6 +227,22 @@ any still-paid Discovery period applies.
Configure only **Yavsc.Org** for PayPal subscriptions. API and Blogs need Configure only **Yavsc.Org** for PayPal subscriptions. API and Blogs need
the migrated shared database and matching resource weights, not PayPal the migrated shared database and matching resource weights, not PayPal
credentials. Existing Classic donation settings remain unchanged. 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` Use the existing `PayPal:Mode`, `PayPal:ClientId` and `PayPal:ClientSecret`
REST settings; keep credentials in user-secrets or environment variables. REST settings; keep credentials in user-secrets or environment variables.

View file

@ -47,6 +47,21 @@ spécifiques (IntentFilter Android, `app.manifest` Desktop).
Toute la logique (VM, services, navigation, settings, OIDC) est Toute la logique (VM, services, navigation, settings, OIDC) est
dans le code-base partagé. 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 ## Reprise Android
`IActivityApplicationLifetime.MainViewFactory` crée une nouvelle `MainView` `IActivityApplicationLifetime.MainViewFactory` crée une nouvelle `MainView`

View file

@ -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<SubscriptionsPage>(new ViewLocator().Build(model));
var selector = page.FindControl<ComboBox>("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<TextBlock>("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<TextBlock>("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<CreateResourceSubscriptionRequest>(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<T> CallAsync<T>(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<T>(JsonSerializer.Serialize(result))!);
}
public Task<T> CallAsync<T>(HttpMethod method, string path, Func<HttpContent> 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<HttpContent> factory, CancellationToken ct = default) => throw new NotSupportedException();
public Task<byte[]> DownloadAsync(HttpMethod method, string path, CancellationToken ct = default) => throw new NotSupportedException();
public ValueTask DisposeAsync() { Http.Dispose(); return ValueTask.CompletedTask; }
}
}

View file

@ -94,6 +94,7 @@ public static class ServiceCollectionHelpers
services.AddTransient<EstimateValidationPage>(); services.AddTransient<EstimateValidationPage>();
services.AddTransient<MyFilesPage>(); services.AddTransient<MyFilesPage>();
services.AddTransient<UserProfilePage>(); services.AddTransient<UserProfilePage>();
services.AddTransient<SubscriptionsPage>();
services.AddTransient<PerformerConfigurationPage>(); services.AddTransient<PerformerConfigurationPage>();
services.AddTransient<AdministrationPage>(); services.AddTransient<AdministrationPage>();
@ -110,6 +111,7 @@ public static class ServiceCollectionHelpers
services.AddSingleton(invoicesClient); services.AddSingleton(invoicesClient);
services.AddSingleton(frontClient); services.AddSingleton(frontClient);
services.AddSingleton(resourceUsageClient); services.AddSingleton(resourceUsageClient);
services.AddSingleton(new ResourceSubscriptionsApiClient(api, () => settings.Authentication.Authority));
services.AddSingleton(administrationClient); services.AddSingleton(administrationClient);
services.AddSingleton(notificationsClient); services.AddSingleton(notificationsClient);
services.AddSingleton(podcastClient); services.AddSingleton(podcastClient);
@ -120,6 +122,7 @@ public static class ServiceCollectionHelpers
services.AddSingleton<AboutPageViewModel>(); services.AddSingleton<AboutPageViewModel>();
services.AddSingleton<HomePageViewModel>(); services.AddSingleton<HomePageViewModel>();
services.AddTransient<UserProfilePageViewModel>(); services.AddTransient<UserProfilePageViewModel>();
services.AddTransient<SubscriptionsPageViewModel>();
services.AddTransient<PerformerConfigurationPageViewModel>(); services.AddTransient<PerformerConfigurationPageViewModel>();
services.AddTransient<AdministrationPageViewModel>(); services.AddTransient<AdministrationPageViewModel>();
services.AddSingleton<SignaturePageViewModel>(); services.AddSingleton<SignaturePageViewModel>();

View file

@ -63,6 +63,7 @@ public class ViewLocator : IDataTemplate
EstimateValidationPageViewModel => services.GetRequiredService<EstimateValidationPage>(), EstimateValidationPageViewModel => services.GetRequiredService<EstimateValidationPage>(),
MyFilesViewModel => services.GetRequiredService<MyFilesPage>(), MyFilesViewModel => services.GetRequiredService<MyFilesPage>(),
UserProfilePageViewModel => services.GetRequiredService<UserProfilePage>(), UserProfilePageViewModel => services.GetRequiredService<UserProfilePage>(),
SubscriptionsPageViewModel => services.GetRequiredService<SubscriptionsPage>(),
PerformerConfigurationPageViewModel => services.GetRequiredService<PerformerConfigurationPage>(), PerformerConfigurationPageViewModel => services.GetRequiredService<PerformerConfigurationPage>(),
AdministrationPageViewModel => services.GetRequiredService<AdministrationPage>(), AdministrationPageViewModel => services.GetRequiredService<AdministrationPage>(),
ChatViewModel => services.GetRequiredService<ChatPage>(), ChatViewModel => services.GetRequiredService<ChatPage>(),

View file

@ -64,7 +64,7 @@ public partial class AboutPageViewModel : ViewModelBase
private Task OpenTerms() => OpenUrlAsync(TermsUri.AbsoluteUri); private Task OpenTerms() => OpenUrlAsync(TermsUri.AbsoluteUri);
[RelayCommand] [RelayCommand]
private Task OpenSubscriptions() => OpenUrlAsync(SubscriptionsUri.AbsoluteUri); private Task OpenSubscriptions() => SubscriptionsPageViewModel.OpenAsync();
private async Task OpenUrlAsync(string url) private async Task OpenUrlAsync(string url)
{ {

View file

@ -74,6 +74,7 @@ public class HomePageViewModel : ViewModelBase
OpenBlogs = new AsyncRelayCommand(App.PushBlogsPageAsync); OpenBlogs = new AsyncRelayCommand(App.PushBlogsPageAsync);
OpenMyFiles = new AsyncRelayCommand(OpenMyFilesAsync); OpenMyFiles = new AsyncRelayCommand(OpenMyFilesAsync);
OpenProfile = new AsyncRelayCommand(OpenProfileAsync); OpenProfile = new AsyncRelayCommand(OpenProfileAsync);
OpenSubscriptions = new AsyncRelayCommand(SubscriptionsPageViewModel.OpenAsync);
OpenPerformerConfiguration = new AsyncRelayCommand(OpenPerformerConfigurationAsync); OpenPerformerConfiguration = new AsyncRelayCommand(OpenPerformerConfigurationAsync);
OpenAdministration = new AsyncRelayCommand(OpenAdministrationAsync, () => SessionStatus.IsAdministrator); OpenAdministration = new AsyncRelayCommand(OpenAdministrationAsync, () => SessionStatus.IsAdministrator);
OpenChat = new AsyncRelayCommand(OpenChatAsync); OpenChat = new AsyncRelayCommand(OpenChatAsync);
@ -92,6 +93,7 @@ public class HomePageViewModel : ViewModelBase
public bool SupportsPodcasts => Platform.IsPodcastSupported; public bool SupportsPodcasts => Platform.IsPodcastSupported;
public IAsyncRelayCommand OpenBlogs { get; } public IAsyncRelayCommand OpenBlogs { get; }
public IAsyncRelayCommand OpenProfile { get; } public IAsyncRelayCommand OpenProfile { get; }
public IAsyncRelayCommand OpenSubscriptions { get; }
public IAsyncRelayCommand OpenPerformerConfiguration { get; } public IAsyncRelayCommand OpenPerformerConfiguration { get; }
public IAsyncRelayCommand OpenAdministration { get; } public IAsyncRelayCommand OpenAdministration { get; }
public IAsyncRelayCommand OpenActivities { get; } public IAsyncRelayCommand OpenActivities { get; }

View file

@ -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<Uri, Task<bool>> _launch;
public SubscriptionsPageViewModel(ResourceSubscriptionsApiClient client, Func<Uri, Task<bool>>? launch = null)
{
_client = client;
_launch = launch ?? LaunchAsync;
}
public ObservableCollection<ResourceSubscriptionOfferResponse> 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<Task> 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<bool> 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<SubscriptionsPageViewModel>();
await vm.InitializeAsync();
await app.PushPageAsync(vm);
}
}

View file

@ -17,9 +17,7 @@ public partial class UserProfilePageViewModel : ViewModelBase
private readonly YavscApiClient? _api; private readonly YavscApiClient? _api;
private readonly SessionStatusViewModel? _sessionStatus; private readonly SessionStatusViewModel? _sessionStatus;
private readonly ResourceUsageApiClient? _usageClient; private readonly ResourceUsageApiClient? _usageClient;
private readonly AboutPageViewModel _subscriptionLinks; public IAsyncRelayCommand OpenSubscriptionsCommand { get; } = new AsyncRelayCommand(SubscriptionsPageViewModel.OpenAsync);
public IAsyncRelayCommand OpenSubscriptionsCommand => _subscriptionLinks.OpenSubscriptionsCommand;
public string? SubscriptionLinkError => _subscriptionLinks.StatusMessage;
[ObservableProperty] [ObservableProperty]
public partial ResourceUsageSummary? ResourceUsage { get; set; } public partial ResourceUsageSummary? ResourceUsage { get; set; }
@ -161,8 +159,6 @@ public partial class UserProfilePageViewModel : ViewModelBase
_api = api; _api = api;
_sessionStatus = sessionStatus; _sessionStatus = sessionStatus;
_usageClient = usageClient; _usageClient = usageClient;
_subscriptionLinks = new AboutPageViewModel(api?.Settings);
_subscriptionLinks.PropertyChanged += (_, _) => OnPropertyChanged(nameof(SubscriptionLinkError));
} }
public UserProfilePageViewModel() : this(null, null) { } public UserProfilePageViewModel() : this(null, null) { }

View file

@ -94,6 +94,10 @@
Command="{Binding OpenPerformerConfiguration}" Command="{Binding OpenPerformerConfiguration}"
HorizontalAlignment="Center" HorizontalAlignment="Center"
IsEnabled="{Binding SessionStatus.IsLoggedIn}"/> IsEnabled="{Binding SessionStatus.IsLoggedIn}"/>
<Button Content="Mon abonnement PayPal"
Command="{Binding OpenSubscriptions}"
HorizontalAlignment="Center"
IsEnabled="{Binding SessionStatus.IsLoggedIn}"/>
<Button Content="Administration" <Button Content="Administration"
Command="{Binding OpenAdministration}" Command="{Binding OpenAdministration}"
HorizontalAlignment="Center" HorizontalAlignment="Center"

View file

@ -0,0 +1,62 @@
<ContentPage xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:PostIt.ViewModels"
xmlns:resources="using:Yavsc.Abstract.Resources"
x:Class="PostIt.Views.SubscriptionsPage"
x:DataType="vm:SubscriptionsPageViewModel"
Header="Mon abonnement">
<ScrollViewer HorizontalScrollBarVisibility="Disabled">
<StackPanel Margin="16" Spacing="12" MaxWidth="720">
<TextBlock Text="Mon abonnement PayPal" FontSize="22" FontWeight="SemiBold"/>
<TextBlock Text="Abonnement mensuel à renouvellement automatique. Choisissez une offre, puis approuvez le paiement sur le site sécurisé de PayPal."
TextWrapping="Wrap"/>
<ProgressBar IsVisible="{Binding IsBusy}" IsIndeterminate="True" Height="4"/>
<TextBlock Text="{Binding StatusMessage}" TextWrapping="Wrap"/>
<Button Command="{Binding RefreshCommand}" HorizontalAlignment="Stretch">
<TextBlock Text="Actualiser les paiements et mon solde" TextWrapping="Wrap"/>
</Button>
<TextBlock Text="Offres de cette instance (EUR par mois)" FontSize="18" FontWeight="SemiBold"/>
<ComboBox x:Name="OfferSelector" ItemsSource="{Binding Offers}" SelectedItem="{Binding SelectedOffer, Mode=TwoWay}"
IsEnabled="{Binding !IsBusy}" HorizontalAlignment="Stretch">
<ComboBox.ItemTemplate>
<DataTemplate x:DataType="resources:ResourceSubscriptionOfferResponse">
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<StackPanel DataContext="{Binding SelectedOffer}" Spacing="6">
<TextBlock Text="{Binding PriceExcludingTax, StringFormat='Prix HT : {0:F2} EUR / mois'}"/>
<TextBlock Text="{Binding VatPercent, StringFormat='TVA : {0:F2} %'}"/>
<TextBlock x:Name="OfferPrice" Text="{Binding PriceIncludingTax, StringFormat='Prix TTC : {0:F2} EUR / mois'}" FontWeight="Bold"/>
<TextBlock Text="{Binding MonthlyPoints, StringFormat='Crédit mensuel : {0:F0} points'}"/>
<TextBlock Text="{Binding DiskQuotaMultiplier, StringFormat='Stockage : {0} fois le quota standard pendant les périodes payées'}" TextWrapping="Wrap"/>
<TextBlock Text="Cette offre n'est pas configurée sur cette instance." IsVisible="{Binding !Available}" TextWrapping="Wrap"/>
</StackPanel>
<TextBlock Text="Les paiements mensuels confirmés effacent l'usage dans la limite du crédit de l'offre. Deux tiers du crédit mensuel inutilisé sont reportés sans expiration. Aucun crédit n'est accordé avant vérification du paiement."
TextWrapping="Wrap"/>
<Button Command="{Binding SubscribeCommand}" HorizontalAlignment="Stretch">
<TextBlock Text="Souscrire / reprendre l'approbation PayPal" TextWrapping="Wrap"/>
</Button>
<TextBlock Text="Abonnement en cours" FontSize="18" FontWeight="SemiBold"/>
<TextBlock Text="Aucun abonnement en cours." IsVisible="{Binding CurrentSubscription, Converter={x:Static ObjectConverters.IsNull}}"/>
<StackPanel DataContext="{Binding CurrentSubscription}" Spacing="6">
<TextBlock Text="{Binding Pack, StringFormat='Offre : {0}'}"/>
<TextBlock Text="{Binding State, StringFormat='Etat PayPal : {0}'}"/>
<TextBlock Text="{Binding PriceIncludingTax, StringFormat='Mensualité TTC souscrite : {0:F2} EUR'}"/>
<TextBlock Text="{Binding NextBillingAt, StringFormat='Prochaine échéance : {0:g}'}"/>
</StackPanel>
<TextBlock Text="Résiliez l'abonnement existant avant de changer d'offre. La résiliation arrête les prochains renouvellements, sans effacer les droits déjà acquis."
TextWrapping="Wrap"/>
<CheckBox Content="Je confirme la résiliation de mon abonnement" IsChecked="{Binding ConfirmCancellation}"
IsEnabled="{Binding !IsBusy}"/>
<Button Content="Résilier l'abonnement" Command="{Binding CancelSubscriptionCommand}"/>
<TextBlock Text="Mon solde" FontSize="18" FontWeight="SemiBold"/>
<StackPanel DataContext="{Binding Usage}" Spacing="6">
<TextBlock Text="{Binding Consumption, StringFormat='Consommation : {0:F3} points'}"/>
<TextBlock Text="{Binding CreditBalance, StringFormat='Crédit reporté disponible : {0:F3} points'}"/>
<TextBlock Text="{Binding RemainingConsumption, StringFormat='Solde : {0:F3} points'}"/>
<TextBlock Text="{Binding DiskQuota, StringFormat='Quota de stockage effectif : {0} octets'}"/>
</StackPanel>
</StackPanel>
</ScrollViewer>
</ContentPage>

View file

@ -0,0 +1,8 @@
using Avalonia.Controls;
namespace PostIt.Views;
public partial class SubscriptionsPage : ContentPage
{
public SubscriptionsPage() => InitializeComponent();
}

View file

@ -33,7 +33,6 @@
<TextBlock Text="{Binding UsageError}" TextWrapping="Wrap"/> <TextBlock Text="{Binding UsageError}" TextWrapping="Wrap"/>
<Button Content="Abonnements Découverte et Premium" <Button Content="Abonnements Découverte et Premium"
Command="{Binding OpenSubscriptionsCommand}"/> Command="{Binding OpenSubscriptionsCommand}"/>
<TextBlock Text="{Binding SubscriptionLinkError}" TextWrapping="Wrap"/>
<StackPanel DataContext="{Binding ResourceUsage}" Spacing="4"> <StackPanel DataContext="{Binding ResourceUsage}" Spacing="4">
<TextBlock Text="{Binding ApiCalls, StringFormat='Appels API : {0:F0}'}"/> <TextBlock Text="{Binding ApiCalls, StringFormat='Appels API : {0:F0}'}"/>
<TextBlock Text="{Binding CpuSeconds, StringFormat='CPU : {0:F3} s'}"/> <TextBlock Text="{Binding CpuSeconds, StringFormat='CPU : {0:F3} s'}"/>

View file

@ -0,0 +1,26 @@
#nullable enable
using System.ComponentModel.DataAnnotations;
namespace Yavsc.Abstract.Resources;
/// <summary>Monthly resource offer configured by the instance.</summary>
public sealed record ResourceSubscriptionOfferResponse(string Pack, string Name, decimal PriceExcludingTax,
decimal VatPercent, decimal PriceIncludingTax, decimal MonthlyPoints, int DiskQuotaMultiplier, bool Available);
/// <summary>Subscription status without merchant credentials or PayPal identifiers.</summary>
public sealed record ResourceSubscriptionResponse(Guid Id, string Pack, string State,
decimal PriceIncludingTax, decimal MonthlyPoints, DateTimeOffset? NextBillingAt);
/// <summary>Current user's subscription catalogue, history and resource balance.</summary>
public sealed record ResourceSubscriptionsResponse(IReadOnlyList<ResourceSubscriptionOfferResponse> Offers,
IReadOnlyList<ResourceSubscriptionResponse> Subscriptions, ResourceUsageSummary Usage);
/// <summary>Chooses a server-priced monthly pack; amounts are never supplied by the client.</summary>
public sealed record CreateResourceSubscriptionRequest
{
[Required, RegularExpression("^(Discovery|Premium)$")]
public required string Pack { get; init; }
}
/// <summary>Prepared subscription and optional PayPal approval link; not proof of payment.</summary>
public sealed record ResourceSubscriptionCheckoutResponse(ResourceSubscriptionResponse Subscription, string? ApprovalUrl);

View file

@ -0,0 +1,23 @@
using Yavsc.Abstract.Resources;
namespace Yavsc.Api.Client;
public sealed class ResourceSubscriptionsApiClient(IYavscApiClient api, Func<string> authority)
{
private string Absolute(string suffix = "")
=> new Uri(new Uri(authority().TrimEnd('/') + "/", UriKind.Absolute),
"api/v1/resource-subscriptions" + suffix).AbsoluteUri;
public Task<ResourceSubscriptionsResponse> GetAsync(CancellationToken ct = default)
=> api.CallAsync<ResourceSubscriptionsResponse>(HttpMethod.Get, Absolute(), ct: ct);
public Task<ResourceSubscriptionCheckoutResponse> CreateAsync(string pack, CancellationToken ct = default)
=> api.CallAsync<ResourceSubscriptionCheckoutResponse>(HttpMethod.Post, Absolute(),
new CreateResourceSubscriptionRequest { Pack = pack }, ct);
public Task<ResourceSubscriptionsResponse> RefreshAsync(CancellationToken ct = default)
=> api.CallAsync<ResourceSubscriptionsResponse>(HttpMethod.Post, Absolute("/refresh"), ct: ct);
public Task<ResourceSubscriptionsResponse> CancelAsync(Guid id, CancellationToken ct = default)
=> api.CallAsync<ResourceSubscriptionsResponse>(HttpMethod.Post, Absolute($"/{id}/cancel"), ct: ct);
}

View file

@ -30,23 +30,12 @@ public sealed class ResourceSubscriptionController(IResourceSubscriptionService
public async Task<IActionResult> Create(string pack, CancellationToken ct) public async Task<IActionResult> Create(string pack, CancellationToken ct)
{ {
var subscription = await subscriptions.PrepareAsync(User.GetUserId(), pack, ct); var subscription = await subscriptions.PrepareAsync(User.GetUserId(), pack, ct);
PayPalSubscriptionDetails remote; var root = subscription.PayPalId is null ? SiteRoot() : "";
if (subscription.PayPalId is null) var approvalUrl = await subscriptions.CheckoutAsync(subscription,
{ root + "ResourceSubscription/Return?id=" + subscription.Id,
var root = SiteRoot(); root + "ResourceSubscription", ct);
remote = await paypal.CreateAsync(subscription, if (approvalUrl is not null)
root + "ResourceSubscription/Return?id=" + subscription.Id, return Redirect(approvalUrl);
root + "ResourceSubscription", ct);
await subscriptions.BindAsync(subscription, remote, ct);
}
else
{
remote = await paypal.GetAsync(subscription.PayPalId, ct);
await subscriptions.BindAsync(subscription, remote, ct);
}
if (remote.ApprovalUrl is not null && remote.State == "APPROVAL_PENDING")
return Redirect(remote.ApprovalUrl);
await subscriptions.ReconcileAsync(subscription, ct);
return RedirectToAction(nameof(Index)); return RedirectToAction(nameof(Index));
} }
@ -72,10 +61,7 @@ public sealed class ResourceSubscriptionController(IResourceSubscriptionService
{ {
var subscription = await OwnedAsync(id, ct); var subscription = await OwnedAsync(id, ct);
if (subscription is null || subscription.PayPalId is null) return NotFound(); if (subscription is null || subscription.PayPalId is null) return NotFound();
await subscriptions.ReconcileAsync(subscription, ct); await subscriptions.CancelAsync(subscription, ct);
if (subscription.State is not ("CANCELLED" or "EXPIRED"))
await paypal.CancelAsync(subscription.PayPalId, ct);
await subscriptions.ReconcileAsync(subscription, ct);
return RedirectToAction(nameof(Index)); return RedirectToAction(nameof(Index));
} }

View file

@ -0,0 +1,101 @@
#nullable enable
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Options;
using Yavsc.Abstract.Resources;
using Yavsc.Models.Payment;
using Yavsc.Server.Helpers;
using Yavsc.Settings;
using Yavsc.Web.Services;
namespace Yavsc.Controllers;
[ApiController]
[Route("api/v1/resource-subscriptions")]
[Authorize(AuthenticationSchemes = "Bearer")]
[ResourceUsageExempt]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
public sealed class ResourceSubscriptionsApiController(IResourceSubscriptionService subscriptions,
IResourceUsageService usage, IOptions<ResourceSubscriptionOptions> options,
IOptions<ResourceUsageOptions> usageOptions, IOptions<SiteSettings> site,
ILogger<ResourceSubscriptionsApiController> logger) : Controller
{
[HttpGet]
[ProducesResponseType<ResourceSubscriptionsResponse>(StatusCodes.Status200OK)]
public async Task<ActionResult<ResourceSubscriptionsResponse>> Get(CancellationToken ct)
{
var prices = options.Value;
ResourceSubscriptionOfferResponse Offer(string pack, string name, decimal net, string plan, int points, int disk)
=> new(pack, name, net, prices.VatPercent, prices.TotalPrice(net),
usageOptions.Value.DefaultLimit * points, disk,
!string.IsNullOrWhiteSpace(plan) && !string.IsNullOrWhiteSpace(prices.WebhookId));
return Ok(new ResourceSubscriptionsResponse(
[Offer("Discovery", "Découverte", prices.DiscoveryPriceExcludingTax, prices.DiscoveryPlanId, 1, 2),
Offer("Premium", "Premium", prices.PremiumPriceExcludingTax, prices.PremiumPlanId, 3, 5)],
(await subscriptions.GetAllAsync(User.GetUserId(), ct)).Select(Response).ToArray(),
await usage.GetCurrentAsync(User.GetUserId(), User.Identity?.Name ?? User.GetUserId(), ct)));
}
[HttpPost]
[ProducesResponseType<ResourceSubscriptionCheckoutResponse>(StatusCodes.Status201Created)]
public async Task<ActionResult<ResourceSubscriptionCheckoutResponse>> Create(
CreateResourceSubscriptionRequest request, CancellationToken ct)
{
if (!Uri.TryCreate(site.Value.ExternalUrl, UriKind.Absolute, out var root)
|| root.Scheme != "https" || !string.IsNullOrEmpty(root.UserInfo))
throw new SubscriptionOperationException(503, "L'adresse HTTPS publique du site n'est pas configuree.");
var returnUrl = site.Value.ExternalUrl.TrimEnd('/') + "/api/v1/resource-subscriptions/return";
var subscription = await subscriptions.PrepareAsync(User.GetUserId(), request.Pack, ct);
var approval = await subscriptions.CheckoutAsync(subscription, returnUrl, returnUrl, ct);
return CreatedAtAction(nameof(Get), new ResourceSubscriptionCheckoutResponse(Response(subscription), approval));
}
[HttpPost("refresh")]
[ProducesResponseType<ResourceSubscriptionsResponse>(StatusCodes.Status200OK)]
public async Task<ActionResult<ResourceSubscriptionsResponse>> Refresh(CancellationToken ct)
{
foreach (var subscription in await subscriptions.GetAllAsync(User.GetUserId(), ct))
await subscriptions.ReconcileAsync(subscription, ct);
return await Get(ct);
}
[HttpPost("{id:guid}/cancel")]
[ProducesResponseType<ResourceSubscriptionsResponse>(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<ResourceSubscriptionsResponse>> Cancel(Guid id, CancellationToken ct)
{
var subscription = (await subscriptions.GetAllAsync(User.GetUserId(), ct)).SingleOrDefault(s => s.Id == id);
if (subscription is null) return NotFound();
await subscriptions.CancelAsync(subscription, ct);
return await Get(ct);
}
// A browser return is deliberately anonymous and never grants credit.
[AllowAnonymous, HttpGet("return")]
public ContentResult Return() => Content(
"<!doctype html><html lang=\"fr\"><meta charset=\"utf-8\"><title>PostIt - PayPal</title>" +
"<h1>Retour dans PostIt</h1><p>Revenez dans PostIt et appuyez sur Actualiser pour verifier " +
"votre abonnement et les paiements confirmes. Ce retour ne confirme aucun paiement.</p></html>", "text/html");
private static ResourceSubscriptionResponse Response(ResourceSubscription s)
=> new(s.Id, s.Pack, s.State, s.PriceIncludingTax, s.MonthlyPoints, s.NextBillingAt);
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var executed = await next();
if (executed.Exception is not SubscriptionOperationException error) return;
logger.LogWarning(error, "Resource subscription API operation failed");
executed.ExceptionHandled = true;
executed.Result = new JsonResult(new ProblemDetails
{
Status = error.StatusCode,
Title = error.Message,
Instance = Request.Path
})
{
StatusCode = error.StatusCode,
ContentType = "application/problem+json"
};
}
}

View file

@ -16,12 +16,37 @@ public interface IResourceSubscriptionService
Task<ResourceSubscription> PrepareAsync(string userId, string pack, CancellationToken ct); Task<ResourceSubscription> PrepareAsync(string userId, string pack, CancellationToken ct);
Task BindAsync(ResourceSubscription subscription, PayPalSubscriptionDetails remote, CancellationToken ct); Task BindAsync(ResourceSubscription subscription, PayPalSubscriptionDetails remote, CancellationToken ct);
Task ReconcileAsync(ResourceSubscription subscription, CancellationToken ct); Task ReconcileAsync(ResourceSubscription subscription, CancellationToken ct);
Task<string?> CheckoutAsync(ResourceSubscription subscription, string returnUrl, string cancelUrl, CancellationToken ct);
Task CancelAsync(ResourceSubscription subscription, CancellationToken ct);
} }
public sealed class ResourceSubscriptionService(ApplicationDbContext db, IPayPalSubscriptionGateway paypal, public sealed class ResourceSubscriptionService(ApplicationDbContext db, IPayPalSubscriptionGateway paypal,
IOptions<ResourceSubscriptionOptions> options, IOptions<ResourceUsageOptions> usageOptions, IOptions<ResourceSubscriptionOptions> options, IOptions<ResourceUsageOptions> usageOptions,
TimeProvider clock) : IResourceSubscriptionService TimeProvider clock) : IResourceSubscriptionService
{ {
public async Task<string?> CheckoutAsync(ResourceSubscription subscription, string returnUrl, string cancelUrl, CancellationToken ct)
{
var remote = subscription.PayPalId is null
? await paypal.CreateAsync(subscription, returnUrl, cancelUrl, ct)
: await paypal.GetAsync(subscription.PayPalId, ct);
await BindAsync(subscription, remote, ct);
if (remote.State == "APPROVAL_PENDING")
return remote.ApprovalUrl
?? throw new SubscriptionOperationException(502, "Le lien d'approbation PayPal est manquant.");
await ReconcileAsync(subscription, ct);
return null;
}
public async Task CancelAsync(ResourceSubscription subscription, CancellationToken ct)
{
if (subscription.PayPalId is null)
throw new SubscriptionOperationException(409, "Reprenez la creation PayPal avant de resilier cet abonnement.");
await ReconcileAsync(subscription, ct);
if (subscription.State is not ("CANCELLED" or "EXPIRED"))
await paypal.CancelAsync(subscription.PayPalId, ct);
await ReconcileAsync(subscription, ct);
}
public Task<List<ResourceSubscription>> GetAllAsync(string userId, CancellationToken ct) public Task<List<ResourceSubscription>> GetAllAsync(string userId, CancellationToken ct)
=> db.ResourceSubscriptions.Where(s => s.UserId == userId).OrderByDescending(s => s.CreatedAt).ToListAsync(ct); => db.ResourceSubscriptions.Where(s => s.UserId == userId).OrderByDescending(s => s.CreatedAt).ToListAsync(ct);

View file

@ -0,0 +1,32 @@
@baseUrl = https://localhost:5001
@token = replace-with-access-token
@subscriptionId = 00000000-0000-0000-0000-000000000000
### Offers, own subscriptions and balance (authority host, not business API host)
GET {{baseUrl}}/api/v1/resource-subscriptions
Authorization: Bearer {{token}}
### Prepare or resume approval; server owns all prices and PayPal plan identifiers
POST {{baseUrl}}/api/v1/resource-subscriptions
Authorization: Bearer {{token}}
Content-Type: application/json
{"pack":"Discovery"}
### Reconcile verified payments after returning from PayPal
POST {{baseUrl}}/api/v1/resource-subscriptions/refresh
Authorization: Bearer {{token}}
### Cancel own subscription; unknown or foreign identifiers return 404
POST {{baseUrl}}/api/v1/resource-subscriptions/{{subscriptionId}}/cancel
Authorization: Bearer {{token}}
### Browser landing page (anonymous, never grants credit)
GET {{baseUrl}}/api/v1/resource-subscriptions/return
### Invalid pack: 400
POST {{baseUrl}}/api/v1/resource-subscriptions
Authorization: Bearer {{token}}
Content-Type: application/json
{"pack":"Unknown"}

View file

@ -1,12 +1,18 @@
using System.Net; using System.Net;
using System.Net.Http.Json; using System.Net.Http.Json;
using System.Net.Http.Headers;
using System.Text.Json; using System.Text.Json;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.TestHost; using Microsoft.AspNetCore.TestHost;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Yavsc.Abstract.Resources;
using Yavsc.Tests.Shared;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Models.Payment; using Yavsc.Models.Payment;
using Yavsc.Server.Helpers; using Yavsc.Server.Helpers;
@ -66,6 +72,123 @@ public sealed class ResourceSubscriptionControllerTests : IClassFixture<Resource
Assert.Equal(HttpStatusCode.BadRequest, create.StatusCode); Assert.Equal(HttpStatusCode.BadRequest, create.StatusCode);
} }
[Fact]
public async Task Native_api_requires_bearer_and_does_not_accept_a_web_cookie()
{
using var anonymous = _factory.CreateClient(new() { AllowAutoRedirect = false });
using var unsigned = await anonymous.GetAsync("/api/v1/resource-subscriptions", Ct);
Assert.Equal(HttpStatusCode.Unauthorized, unsigned.StatusCode);
using var cookie = _factory.SignedInClient();
using var response = await cookie.PostAsJsonAsync("/api/v1/resource-subscriptions",
new { pack = "Premium" }, Ct);
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task Native_checkout_reuses_subscription_ignores_client_prices_and_requires_verified_payment()
{
using (var scope = _factory.Services.CreateScope())
await ResourceUsageTracker.RecordAsync(scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(),
"listener", "Listener", cpuSeconds: 12000m, cancellationToken: Ct);
using var client = NativeClient();
var catalogue = await client.GetFromJsonAsync<ResourceSubscriptionsResponse>("/api/v1/resource-subscriptions", Ct);
Assert.Equal(1.2m, catalogue!.Offers[0].PriceIncludingTax);
Assert.Equal(2.4m, catalogue.Offers[1].PriceIncludingTax);
Assert.True(catalogue.Usage.IsQuotaReached);
using var created = await client.PostAsJsonAsync("/api/v1/resource-subscriptions",
new { pack = "Discovery", priceIncludingTax = 0.01m, userId = "author" }, Ct);
Assert.Equal(HttpStatusCode.Created, created.StatusCode);
Assert.NotNull(created.Headers.Location);
Assert.True(created.Headers.CacheControl?.NoStore);
var checkout = (await created.Content.ReadFromJsonAsync<ResourceSubscriptionCheckoutResponse>(Ct))!;
Assert.Equal("https://www.sandbox.paypal.com/approve", checkout.ApprovalUrl);
Assert.Equal(1.2m, checkout.Subscription.PriceIncludingTax);
Assert.Equal(1200m, (await UsageAsync()).Consumption);
using var resumed = await client.PostAsJsonAsync("/api/v1/resource-subscriptions", new { pack = "Discovery" }, Ct);
Assert.Equal(checkout.Subscription.Id,
(await resumed.Content.ReadFromJsonAsync<ResourceSubscriptionCheckoutResponse>(Ct))!.Subscription.Id);
using var conflict = await client.PostAsJsonAsync("/api/v1/resource-subscriptions", new { pack = "Premium" }, Ct);
Assert.Equal(HttpStatusCode.Conflict, conflict.StatusCode);
using var anonymous = _factory.CreateClient();
using var returned = await anonymous.GetAsync("/api/v1/resource-subscriptions/return?success=true", Ct);
Assert.Equal(HttpStatusCode.OK, returned.StatusCode);
Assert.Equal("text/html", returned.Content.Headers.ContentType?.MediaType);
Assert.Equal(1200m, (await UsageAsync()).Consumption);
using var other = NativeClient("author");
using var forbidden = await other.PostAsync($"/api/v1/resource-subscriptions/{checkout.Subscription.Id}/cancel", null, Ct);
Assert.Equal(HttpStatusCode.NotFound, forbidden.StatusCode);
Assert.Empty((await other.GetFromJsonAsync<ResourceSubscriptionsResponse>("/api/v1/resource-subscriptions", Ct))!.Subscriptions);
_factory.PayPal.Payments.Add(new("PAY-NATIVE", "COMPLETED", 1.2m, "EUR", DateTimeOffset.UtcNow));
using var refreshed = await client.PostAsync("/api/v1/resource-subscriptions/refresh", null, Ct);
Assert.Equal(HttpStatusCode.OK, refreshed.StatusCode);
Assert.Equal(200m, (await UsageAsync()).Consumption);
using var repeated = await client.PostAsync("/api/v1/resource-subscriptions/refresh", null, Ct);
Assert.Equal(HttpStatusCode.OK, repeated.StatusCode);
Assert.Equal(200m, (await UsageAsync()).Consumption);
using var cancelled = await client.PostAsync($"/api/v1/resource-subscriptions/{checkout.Subscription.Id}/cancel", null, Ct);
Assert.Equal(HttpStatusCode.OK, cancelled.StatusCode);
Assert.Equal("CANCELLED", (await cancelled.Content.ReadFromJsonAsync<ResourceSubscriptionsResponse>(Ct))!.Subscriptions.Single().State);
Assert.Equal(1, _factory.PayPal.CancelCount);
}
[Theory]
[InlineData("{}")]
[InlineData("""{"pack":"Other"}""")]
[InlineData("""{"pack":null}""")]
public async Task Native_checkout_rejects_invalid_packs(string json)
{
using var client = NativeClient();
using var response = await client.PostAsync("/api/v1/resource-subscriptions",
new StringContent(json, System.Text.Encoding.UTF8, "application/json"), Ct);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
using var scope = _factory.Services.CreateScope();
Assert.Empty(scope.ServiceProvider.GetRequiredService<ApplicationDbContext>().ResourceSubscriptions);
}
private HttpClient NativeClient(string userId = "listener")
{
var client = _factory.CreateClient(new() { AllowAutoRedirect = false });
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", TestTokenIssuer.Issue(userId, "api"));
return client;
}
[Fact]
public async Task Native_catalogue_uses_instance_prices_and_reports_unconfigured_offers_explicitly()
{
var options = _factory.Services.GetRequiredService<IOptions<ResourceSubscriptionOptions>>().Value;
var originalPrice = options.DiscoveryPriceExcludingTax;
var originalPlan = options.DiscoveryPlanId;
try
{
options.DiscoveryPriceExcludingTax = 3m;
options.DiscoveryPlanId = "";
using var client = NativeClient();
var catalogue = (await client.GetFromJsonAsync<ResourceSubscriptionsResponse>("/api/v1/resource-subscriptions", Ct))!;
Assert.Equal(3.6m, catalogue.Offers[0].PriceIncludingTax);
Assert.False(catalogue.Offers[0].Available);
using var response = await client.PostAsJsonAsync("/api/v1/resource-subscriptions", new { pack = "Discovery" }, Ct);
Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
}
finally
{
options.DiscoveryPriceExcludingTax = originalPrice;
options.DiscoveryPlanId = originalPlan;
}
}
[Fact]
public async Task Native_routes_are_described_in_the_existing_openapi_document()
{
using var client = NativeClient();
using var document = JsonDocument.Parse(await client.GetStringAsync("/swagger/v1/swagger.json", Ct));
var paths = document.RootElement.GetProperty("paths");
Assert.True(paths.GetProperty("/api/v1/resource-subscriptions").TryGetProperty("get", out _));
Assert.True(paths.GetProperty("/api/v1/resource-subscriptions").TryGetProperty("post", out _));
Assert.True(paths.GetProperty("/api/v1/resource-subscriptions/refresh").TryGetProperty("post", out _));
Assert.True(paths.GetProperty("/api/v1/resource-subscriptions/{id}/cancel").TryGetProperty("post", out _));
}
[Fact] [Fact]
public async Task Exhausted_free_usage_can_still_subscribe_and_browser_return_does_not_award_unpaid_credit() public async Task Exhausted_free_usage_can_still_subscribe_and_browser_return_does_not_award_unpaid_credit()
{ {
@ -225,6 +348,21 @@ public sealed class ResourceSubscriptionControllerTests : IClassFixture<Resource
base.ConfigureWebHost(builder); base.ConfigureWebHost(builder);
builder.ConfigureTestServices(services => builder.ConfigureTestServices(services =>
{ {
services.PostConfigure<JwtBearerOptions>("Bearer", o =>
{
o.Authority = null;
o.MetadataAddress = "";
o.ConfigurationManager = null;
o.Configuration = new OpenIdConnectConfiguration { Issuer = TestTokenIssuer.Issuer };
o.MapInboundClaims = false;
o.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true, ValidIssuer = TestTokenIssuer.Issuer,
ValidateAudience = false, ValidateLifetime = true,
ValidateIssuerSigningKey = true, IssuerSigningKey = TestTokenIssuer.SigningKey,
NameClaimType = "name"
};
});
services.AddSingleton<IPayPalSubscriptionGateway>(PayPal); services.AddSingleton<IPayPalSubscriptionGateway>(PayPal);
services.Configure<ResourceSubscriptionOptions>(o => services.Configure<ResourceSubscriptionOptions>(o =>
{ {